Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02cac6dd61 | ||
|
|
e2e40c24f1 | ||
|
|
ab974c882a | ||
|
|
29aa1ccaf8 | ||
|
|
c31becadc7 | ||
|
|
128b432bee | ||
|
|
a73408c324 | ||
|
|
1e0a7598c7 | ||
|
|
8a5b784eae | ||
|
|
7788858149 | ||
|
|
b743d0b66e | ||
|
|
ccb97da75c | ||
|
|
3a254bad33 | ||
|
|
a889dc68ca | ||
|
|
dcbb182f82 | ||
|
|
e21b1514a5 | ||
|
|
e795698818 | ||
|
|
506e0fc049 | ||
|
|
e8d67ffb91 | ||
|
|
c0e867b4d9 | ||
|
|
6d7de0b314 | ||
|
|
38185dc696 | ||
|
|
87c2e3e1ef | ||
|
|
5c227dcaa7 | ||
|
|
ccbad67c43 | ||
|
|
127e91bc86 | ||
|
|
e01c92ff0a | ||
|
|
a11d6b92ea | ||
|
|
82a8394cd8 | ||
|
|
0ce293b37e | ||
|
|
0b0d98c1fd | ||
|
|
ecac3ac795 | ||
|
|
5e0327dee6 | ||
|
|
8f09b8d0ab | ||
|
|
972a6876b8 | ||
|
|
0cd920f32e |
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.
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
### 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` remains a best-effort logical repo grouping mechanism across environments.
|
||||
@@ -214,8 +151,6 @@ Benefits:
|
||||
- no client-specific process management required
|
||||
- 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
|
||||
|
||||
Examples:
|
||||
@@ -235,8 +170,6 @@ This is especially useful when:
|
||||
- mobile must reach a desktop-hosted environment
|
||||
- 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
|
||||
|
||||
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.
|
||||
|
||||
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 answer a different question:
|
||||
@@ -296,15 +227,6 @@ The recommended T3 flow is:
|
||||
4. Desktop establishes local port forwarding.
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
||||
|
||||
@@ -22,4 +22,3 @@ apps/web/src/components/__screenshots__
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
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,6 +1,6 @@
|
||||
# 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
|
||||
|
||||
|
||||
@@ -22,41 +22,9 @@ If you are already running the desktop app and want to make it reachable from ot
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
- in the desktop app, enter the full pairing URL
|
||||
- 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.
|
||||
|
||||
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
|
||||
> The GUIs do not currently support adding projects on remote environments.
|
||||
> For now, use `t3 project ...` on the server machine instead.
|
||||
> 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
|
||||
|
||||
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.
|
||||
|
||||
## 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
|
||||
|
||||
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.
|
||||
- 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.
|
||||
- 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.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.21",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
@@ -15,17 +15,13 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
|
||||
@@ -52,8 +52,6 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
@@ -73,12 +71,6 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
};
|
||||
|
||||
describe("clientPersistence", () => {
|
||||
|
||||
@@ -57,12 +57,6 @@ function isPersistedSavedEnvironmentStorageRecord(
|
||||
typeof value.wsBaseUrl === "string" &&
|
||||
typeof value.createdAt === "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")
|
||||
);
|
||||
}
|
||||
@@ -83,7 +77,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentStorageRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
const nextRecord = {
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
@@ -91,7 +85,6 @@ function toPersistedSavedEnvironmentRecord(
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
};
|
||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
||||
}
|
||||
|
||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||
@@ -141,7 +134,6 @@ export function writeSavedEnvironmentRegistry(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
|
||||
encryptedBearerToken,
|
||||
}
|
||||
: record;
|
||||
@@ -197,7 +189,7 @@ export function writeSavedEnvironmentSecret(input: {
|
||||
const encryptedBearerToken = input.secretStorage
|
||||
.encryptString(input.secret)
|
||||
.toString("base64");
|
||||
const nextRecord = {
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
@@ -205,8 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
};
|
||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
||||
} satisfies PersistedSavedEnvironmentStorageRecord;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
return found;
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
readDesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopTailscaleServePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings.ts";
|
||||
@@ -36,8 +35,6 @@ describe("desktopSettings", () => {
|
||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
@@ -48,16 +45,12 @@ describe("desktopSettings", () => {
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
@@ -68,8 +61,6 @@ describe("desktopSettings", () => {
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
@@ -77,50 +68,6 @@ describe("desktopSettings", () => {
|
||||
),
|
||||
).toEqual({
|
||||
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",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
@@ -131,8 +78,6 @@ describe("desktopSettings", () => {
|
||||
setDesktopUpdateChannelPreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
@@ -140,8 +85,6 @@ describe("desktopSettings", () => {
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
@@ -160,8 +103,6 @@ describe("desktopSettings", () => {
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
@@ -180,8 +121,6 @@ describe("desktopSettings", () => {
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
@@ -201,30 +140,8 @@ describe("desktopSettings", () => {
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
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 {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
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(
|
||||
settings: DesktopSettings,
|
||||
requestedChannel: DesktopUpdateChannel,
|
||||
@@ -86,8 +57,6 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
|
||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly serverExposureMode?: unknown;
|
||||
readonly tailscaleServeEnabled?: unknown;
|
||||
readonly tailscaleServePort?: unknown;
|
||||
readonly updateChannel?: unknown;
|
||||
readonly updateChannelConfiguredByUser?: unknown;
|
||||
};
|
||||
@@ -103,8 +72,6 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
|
||||
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
|
||||
updateChannel:
|
||||
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
||||
? parsedUpdateChannel
|
||||
|
||||
+5
-128
@@ -36,14 +36,11 @@ import { autoUpdater } from "electron-updater";
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
import {
|
||||
type DesktopSettings,
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopTailscaleServePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings.ts";
|
||||
@@ -58,11 +55,7 @@ import {
|
||||
} from "./clientPersistence.ts";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import {
|
||||
resolveDesktopCoreAdvertisedEndpoints,
|
||||
resolveDesktopServerExposure,
|
||||
} from "./serverExposure.ts";
|
||||
import { DesktopSshEnvironmentBridge, resolveRemoteT3CliPackageSpec } from "./sshEnvironment.ts";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure.ts";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
||||
@@ -83,7 +76,6 @@ import {
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
|
||||
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 GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
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 STATE_DIR = Path.join(BASE_DIR, "userdata");
|
||||
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 ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
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({
|
||||
isDevelopment,
|
||||
appVersion: app.getVersion(),
|
||||
@@ -312,9 +297,6 @@ function backendChildEnv(): NodeJS.ProcessEnv {
|
||||
delete env.T3CODE_DESKTOP_WS_URL;
|
||||
delete env.T3CODE_DESKTOP_LAN_ACCESS;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -323,32 +305,9 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
|
||||
mode: desktopServerExposureMode,
|
||||
endpointUrl: backendEndpointUrl,
|
||||
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() {
|
||||
return {
|
||||
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
|
||||
@@ -362,19 +321,9 @@ function resolveAdvertisedHostOverride(): string | 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(
|
||||
mode: DesktopServerExposureMode,
|
||||
options?: {
|
||||
readonly persist?: boolean;
|
||||
readonly rejectIfUnavailable?: boolean;
|
||||
},
|
||||
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
|
||||
): Promise<DesktopServerExposureState> {
|
||||
const advertisedHostOverride = resolveAdvertisedHostOverride();
|
||||
const requestedMode = mode;
|
||||
@@ -412,17 +361,6 @@ async function applyDesktopServerExposureMode(
|
||||
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 {
|
||||
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
|
||||
setImmediate(() => {
|
||||
@@ -435,7 +373,6 @@ function relaunchDesktopApp(reason: string): void {
|
||||
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
})
|
||||
.then(() => desktopSshEnvironmentBridge.dispose().catch(() => undefined))
|
||||
.finally(() => {
|
||||
restoreStdIoCapture?.();
|
||||
if (isDevelopment) {
|
||||
@@ -692,22 +629,6 @@ let updateInstallInFlight = false;
|
||||
let updaterConfigured = false;
|
||||
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 {
|
||||
if (updateInstallInFlight) return "install";
|
||||
if (updateDownloadInFlight) return "download";
|
||||
@@ -1259,10 +1180,7 @@ async function checkForUpdates(reason: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadAvailableUpdate(): Promise<{
|
||||
accepted: boolean;
|
||||
completed: boolean;
|
||||
}> {
|
||||
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
|
||||
return { accepted: false, completed: false };
|
||||
}
|
||||
@@ -1284,10 +1202,7 @@ async function downloadAvailableUpdate(): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
async function installDownloadedUpdate(): Promise<{
|
||||
accepted: boolean;
|
||||
completed: boolean;
|
||||
}> {
|
||||
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
|
||||
return { accepted: false, completed: false };
|
||||
}
|
||||
@@ -1487,8 +1402,6 @@ function startBackend(): void {
|
||||
t3Home: BASE_DIR,
|
||||
host: backendBindHost,
|
||||
desktopBootstrapToken: backendBootstrapToken,
|
||||
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
|
||||
tailscaleServePort: desktopSettings.tailscaleServePort,
|
||||
...(backendObservabilitySettings.otlpTracesUrl
|
||||
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
|
||||
: {}),
|
||||
@@ -1734,8 +1647,6 @@ function registerIpcHandlers(): void {
|
||||
},
|
||||
);
|
||||
|
||||
desktopSshEnvironmentBridge.registerIpcHandlers(ipcMain);
|
||||
|
||||
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
|
||||
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
|
||||
|
||||
@@ -1758,31 +1669,6 @@ function registerIpcHandlers(): void {
|
||||
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.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
@@ -2073,10 +1959,7 @@ function createWindow(): BrowserWindow {
|
||||
const externalUrl = getSafeExternalUrl(params.linkURL);
|
||||
if (externalUrl) {
|
||||
menuTemplate.push(
|
||||
{
|
||||
label: "Copy Link",
|
||||
click: () => clipboard.writeText(params.linkURL),
|
||||
},
|
||||
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
|
||||
{ type: "separator" },
|
||||
);
|
||||
}
|
||||
@@ -2136,9 +2019,6 @@ function createWindow(): BrowserWindow {
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
desktopSshEnvironmentBridge.cancelPendingPasswordPrompts(
|
||||
"SSH authentication was cancelled because the app window closed.",
|
||||
);
|
||||
if (mainWindow === window) {
|
||||
mainWindow = null;
|
||||
}
|
||||
@@ -2230,7 +2110,6 @@ app.on("before-quit", () => {
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
|
||||
restoreStdIoCapture?.();
|
||||
});
|
||||
|
||||
@@ -2280,7 +2159,6 @@ if (process.platform !== "win32") {
|
||||
clearUpdatePollTimer();
|
||||
cancelBackendReadinessWait();
|
||||
stopBackend();
|
||||
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
});
|
||||
@@ -2291,7 +2169,6 @@ if (process.platform !== "win32") {
|
||||
writeDesktopLogHeader("SIGTERM received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
|
||||
restoreStdIoCapture?.();
|
||||
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 SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-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 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", {
|
||||
getAppBranding: () => {
|
||||
@@ -79,39 +51,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
|
||||
removeSavedEnvironmentSecret: (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),
|
||||
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),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveDesktopCoreAdvertisedEndpoints,
|
||||
resolveDesktopServerExposure,
|
||||
resolveLanAdvertisedHost,
|
||||
} from "./serverExposure.ts";
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
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", () => {
|
||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
||||
expect(
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
DesktopServerExposureMode,
|
||||
} from "@t3tools/contracts";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
@@ -21,26 +13,6 @@ export interface DesktopServerExposure {
|
||||
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 normalized = value?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||
@@ -49,14 +21,6 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
|
||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||
!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(
|
||||
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
||||
explicitHost: string | undefined,
|
||||
@@ -114,75 +78,3 @@ export function resolveDesktopServerExposure(input: {
|
||||
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;
|
||||
}
|
||||
@@ -331,6 +331,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
|
||||
@@ -506,7 +506,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||
|
||||
@@ -515,7 +514,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(fullDiff.includes("README.md"), true);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.21",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -19,6 +19,7 @@
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"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"
|
||||
@@ -29,7 +30,7 @@
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
@@ -39,7 +40,6 @@
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
|
||||
@@ -48,7 +48,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
@@ -69,14 +68,9 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
@@ -86,13 +80,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
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()),
|
||||
@@ -111,7 +102,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
@@ -123,7 +113,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
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 () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
@@ -214,13 +139,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
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()),
|
||||
|
||||
@@ -24,7 +24,6 @@ const make = Effect.gen(function* () {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -132,7 +131,6 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
|
||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -159,7 +157,6 @@ const make = Effect.gen(function* () {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace ?? true,
|
||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||
|
||||
return {
|
||||
|
||||
@@ -114,7 +114,6 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
@@ -122,80 +121,5 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
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>");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -259,20 +259,10 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
];
|
||||
|
||||
const result = yield* vcs.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: diffArgs,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ export interface DiffCheckpointsInput {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
|
||||
@@ -46,8 +46,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -89,8 +87,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -112,8 +108,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(true),
|
||||
logWebSocketEvents: Option.some(true),
|
||||
tailscaleServeEnabled: Option.some(true),
|
||||
tailscaleServePort: Option.some(8443),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
@@ -155,8 +149,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -169,8 +161,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
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(),
|
||||
autoBootstrapProjectFromCwd: Option.some(false),
|
||||
logWebSocketEvents: Option.some(false),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -224,8 +212,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -243,8 +229,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
});
|
||||
@@ -262,8 +246,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -299,8 +281,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
||||
}),
|
||||
@@ -325,8 +305,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -368,8 +346,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: false,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
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(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
@@ -425,8 +399,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -460,8 +432,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -493,8 +463,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -517,8 +485,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
{
|
||||
@@ -556,8 +522,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./cli.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
@@ -75,8 +76,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
} satisfies ServerConfigShape;
|
||||
});
|
||||
|
||||
@@ -315,8 +314,8 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const addedProject = readModel.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
|
||||
@@ -78,8 +78,6 @@ const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
desktopBootstrapToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optional(PortSchema),
|
||||
otlpTracesUrl: 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.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({
|
||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||
@@ -187,14 +174,6 @@ const EnvServerConfig = Config.all({
|
||||
Config.option,
|
||||
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 {
|
||||
@@ -208,8 +187,6 @@ interface CliServerFlags {
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
readonly tailscaleServeEnabled: Option.Option<boolean>;
|
||||
readonly tailscaleServePort: Option.Option<number>;
|
||||
}
|
||||
|
||||
interface CliAuthLocationFlags {
|
||||
@@ -256,8 +233,6 @@ export const resolveServerConfig = (
|
||||
bootstrapFd: flags.bootstrapFd ?? Option.none(),
|
||||
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
|
||||
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
|
||||
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
|
||||
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
|
||||
} satisfies CliServerFlags;
|
||||
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
@@ -348,22 +323,6 @@ export const resolveServerConfig = (
|
||||
),
|
||||
() => 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 host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
@@ -406,8 +365,6 @@ export const resolveServerConfig = (
|
||||
desktopBootstrapToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
tailscaleServePort,
|
||||
};
|
||||
|
||||
return config;
|
||||
@@ -429,8 +386,6 @@ const resolveCliAuthConfig = (
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
cliLogLevel,
|
||||
);
|
||||
@@ -811,8 +766,6 @@ const sharedServerCommandFlags = {
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
tailscaleServeEnabled: tailscaleServeFlag,
|
||||
tailscaleServePort: tailscaleServePortFlag,
|
||||
} as const;
|
||||
|
||||
const authLocationFlags = sharedServerLocationFlags;
|
||||
|
||||
@@ -65,8 +65,6 @@ export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
}
|
||||
|
||||
export const deriveServerPaths = Effect.fn(function* (
|
||||
@@ -160,8 +158,6 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -30,8 +30,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -5,7 +5,6 @@ import { spawnSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { expect } from "vitest";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
@@ -14,10 +13,9 @@ import type {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
|
||||
import { type GitManagerShape } from "./GitManager.ts";
|
||||
import {
|
||||
GitHubCliError,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
GitHubCli,
|
||||
@@ -57,16 +55,6 @@ interface FakeGhScenario {
|
||||
failWith?: GitHubCliError;
|
||||
}
|
||||
|
||||
function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
@@ -402,15 +390,24 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
? scenario.prListByHeadSelector?.[headSelector]
|
||||
: undefined;
|
||||
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") {
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
(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") {
|
||||
@@ -422,8 +419,8 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
headRefName: "feature/pull-request",
|
||||
state: "open",
|
||||
};
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
JSON.stringify({
|
||||
...pullRequest,
|
||||
...(pullRequest.headRepositoryNameWithOwner
|
||||
@@ -441,8 +438,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
: {}),
|
||||
}) + "\n",
|
||||
),
|
||||
);
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "checkout") {
|
||||
@@ -464,7 +464,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
runGitSyncForFakeGh(input.cwd, ["checkout", "-b", headBranch]);
|
||||
}
|
||||
}
|
||||
return fakeGhOutput("");
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
},
|
||||
catch: (error) =>
|
||||
isGitHubCliError(error)
|
||||
@@ -491,17 +497,26 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(
|
||||
fakeGhOutput(
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
JSON.stringify({
|
||||
nameWithOwner: repository,
|
||||
url: cloneUrls.url,
|
||||
sshUrl: cloneUrls.sshUrl,
|
||||
}) + "\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(
|
||||
@@ -580,13 +595,6 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "createRepository",
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
@@ -652,10 +660,8 @@ function makeManager(input?: {
|
||||
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)),
|
||||
@@ -889,7 +895,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
@@ -919,7 +924,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
@@ -1682,41 +1686,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", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -2463,113 +2432,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", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -3194,6 +3056,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect.objectContaining({
|
||||
kind: "hook_finished",
|
||||
hookName: "pre-commit",
|
||||
exitCode: 0,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "action_finished",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Array as Arr,
|
||||
@@ -39,10 +40,6 @@ import {
|
||||
sanitizeBranchFragment,
|
||||
sanitizeFeatureBranchName,
|
||||
} from "@t3tools/shared/git";
|
||||
import {
|
||||
getChangeRequestTerminologyForKind,
|
||||
type ChangeRequestTerminology,
|
||||
} from "@t3tools/shared/sourceControl";
|
||||
|
||||
import { GitManagerError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
|
||||
@@ -357,14 +354,13 @@ function withDescription(title: string, description: string | undefined) {
|
||||
|
||||
function summarizeGitActionResult(
|
||||
result: Pick<GitRunStackedActionResult, "commit" | "push" | "pr">,
|
||||
terms: ChangeRequestTerminology,
|
||||
): {
|
||||
title: string;
|
||||
description?: string;
|
||||
} {
|
||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -489,6 +485,14 @@ function normalizePullRequestReference(reference: string): string {
|
||||
return hashNumber?.[1] ?? trimmed;
|
||||
}
|
||||
|
||||
function canonicalizeExistingPath(value: string): string {
|
||||
try {
|
||||
return realpathSync.native(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function toResolvedPullRequest(pr: {
|
||||
number: number;
|
||||
title: string;
|
||||
@@ -568,22 +572,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
localBranch = pullRequest.headBranch,
|
||||
) {
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
@@ -604,11 +592,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
url: remoteUrl,
|
||||
});
|
||||
|
||||
yield* gitCore.fetchRemoteTrackingBranch({
|
||||
cwd,
|
||||
remoteName,
|
||||
remoteBranch: pullRequest.headBranch,
|
||||
});
|
||||
yield* gitCore.setBranchUpstream({
|
||||
cwd,
|
||||
branch: localBranch,
|
||||
@@ -697,9 +680,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
const canonicalizeExistingPath = (value: string) =>
|
||||
fileSystem.realPath(value).pipe(Effect.catch(() => Effect.succeed(value)));
|
||||
const normalizeStatusCacheKey = canonicalizeExistingPath;
|
||||
const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
|
||||
const nonRepositoryStatusDetails = {
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
@@ -711,7 +692,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
} satisfies GitStatusDetails;
|
||||
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
@@ -724,6 +704,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
: null;
|
||||
|
||||
return {
|
||||
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
|
||||
isRepo: details.isRepo,
|
||||
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
|
||||
hasPrimaryRemote: details.hasOriginRemote,
|
||||
@@ -738,9 +719,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateLocalStatusResultCache = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),
|
||||
);
|
||||
Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
.statusDetails(cwd)
|
||||
@@ -770,7 +749,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
aheadOfDefaultCount: details.aheadOfDefaultCount,
|
||||
pr,
|
||||
} satisfies VcsStatusRemoteResult;
|
||||
});
|
||||
@@ -779,9 +757,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
||||
normalizeStatusCacheKey(cwd).pipe(
|
||||
Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),
|
||||
);
|
||||
Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
|
||||
|
||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||
gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
@@ -966,11 +942,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
cwd: string,
|
||||
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
|
||||
) {
|
||||
const terms = yield* sourceControlProvider(cwd).pipe(
|
||||
Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
|
||||
Effect.catch(() => Effect.succeed(getChangeRequestTerminologyForKind("unknown"))),
|
||||
);
|
||||
const summary = summarizeGitActionResult(result, terms);
|
||||
const summary = summarizeGitActionResult(result);
|
||||
let latestOpenPr: PullRequestInfo | null = null;
|
||||
let currentBranchIsDefault = false;
|
||||
let finalBranchContext: {
|
||||
@@ -1035,7 +1007,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
result.pr.status === "opened_existing")
|
||||
? {
|
||||
kind: "open_pr" as const,
|
||||
label: `View ${terms.shortLabel}`,
|
||||
label: "View PR",
|
||||
url: openPr.url,
|
||||
}
|
||||
: (result.action === "push" || result.action === "commit_push") &&
|
||||
@@ -1043,7 +1015,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
!currentBranchIsDefault
|
||||
? {
|
||||
kind: "run_action" as const,
|
||||
label: `Create ${terms.shortLabel}`,
|
||||
label: "Create PR",
|
||||
action: { kind: "create_pr" as const },
|
||||
}
|
||||
: {
|
||||
@@ -1251,8 +1223,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
fallbackBranch: string | null,
|
||||
emit: GitActionProgressEmitter,
|
||||
) {
|
||||
const provider = yield* sourceControlProvider(cwd);
|
||||
const terms = getChangeRequestTerminologyForKind(provider.kind);
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
@@ -1289,7 +1259,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: `Generating ${terms.shortLabel} content...`,
|
||||
label: "Generating PR content...",
|
||||
});
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
||||
|
||||
@@ -1314,9 +1284,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
yield* emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: `Creating ${terms.singular}...`,
|
||||
label: "Creating pull request...",
|
||||
});
|
||||
yield* provider
|
||||
yield* (yield* sourceControlProvider(cwd))
|
||||
.createChangeRequest({
|
||||
cwd,
|
||||
baseRefName: baseBranch,
|
||||
@@ -1347,13 +1317,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
});
|
||||
|
||||
const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(localStatusResultCache, cacheKey);
|
||||
return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||
});
|
||||
const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
|
||||
function* (input) {
|
||||
const cacheKey = yield* normalizeStatusCacheKey(input.cwd);
|
||||
return yield* Cache.get(remoteStatusResultCache, cacheKey);
|
||||
return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
|
||||
},
|
||||
);
|
||||
const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
|
||||
@@ -1413,7 +1381,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
};
|
||||
return yield* Effect.gen(function* () {
|
||||
const normalizedReference = normalizePullRequestReference(input.reference);
|
||||
const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);
|
||||
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
|
||||
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: normalizedReference,
|
||||
@@ -1463,35 +1431,33 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
const localPullRequestBranch =
|
||||
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
|
||||
|
||||
const findLocalHeadBranch = Effect.fn("findLocalHeadBranch")(function* (cwd: string) {
|
||||
const result = yield* gitCore.listRefs({ cwd });
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
const findLocalHeadBranch = (cwd: string) =>
|
||||
gitCore.listRefs({ cwd }).pipe(
|
||||
Effect.map((result) => {
|
||||
const localBranch = result.refs.find(
|
||||
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
|
||||
);
|
||||
if (localBranch) {
|
||||
return localBranch;
|
||||
}
|
||||
if (localPullRequestBranch === pullRequest.headBranch) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
result.refs.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 existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
|
||||
? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||
? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
|
||||
: null;
|
||||
if (
|
||||
existingBranchBeforeFetch?.worktreePath &&
|
||||
@@ -1519,7 +1485,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);
|
||||
const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath
|
||||
? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||
? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)
|
||||
: null;
|
||||
if (
|
||||
existingBranchAfterFetch?.worktreePath &&
|
||||
@@ -1616,6 +1582,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
"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) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
@@ -1679,12 +1651,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
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
|
||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||
@@ -1722,7 +1688,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
.emit({
|
||||
kind: "phase_started",
|
||||
phase: "pr",
|
||||
label: `Preparing ${changeRequestTerms?.shortLabel ?? "PR"}...`,
|
||||
label: "Preparing PR...",
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||
|
||||
@@ -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),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { Context, Effect, Layer } from "effect";
|
||||
import {
|
||||
GitManagerError,
|
||||
GitCommandError,
|
||||
type VcsDriverKind,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
import { mergeGitStatusParts } from "@t3tools/shared/git";
|
||||
|
||||
export interface GitWorkflowServiceShape {
|
||||
readonly status: (
|
||||
@@ -65,6 +67,7 @@ export interface GitWorkflowServiceShape {
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly initRepo: (input: { readonly cwd: string }) => Effect.Effect<void, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
@@ -91,41 +94,17 @@ const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =
|
||||
detail,
|
||||
});
|
||||
|
||||
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
|
||||
return {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
|
||||
kind,
|
||||
isRepo,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: emptyWorkingTree,
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
@@ -180,60 +159,6 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -242,27 +167,60 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
(input: Input) =>
|
||||
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
|
||||
|
||||
const localStatus: GitWorkflowServiceShape["localStatus"] = Effect.fn(
|
||||
"GitWorkflowService.localStatus",
|
||||
)(function* (input) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd: input.cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
"GitWorkflowService.localStatus",
|
||||
input.cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return nonGitLocalStatus("unknown", false);
|
||||
}
|
||||
if (handle.kind === "git") {
|
||||
return yield* gitManager.localStatus(input);
|
||||
}
|
||||
return nonGitLocalStatus(handle.kind, true);
|
||||
});
|
||||
|
||||
const remoteStatus: GitWorkflowServiceShape["remoteStatus"] = Effect.fn(
|
||||
"GitWorkflowService.remoteStatus",
|
||||
)(function* (input) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd: input.cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
"GitWorkflowService.remoteStatus",
|
||||
input.cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle?.kind === "git") {
|
||||
return yield* gitManager.remoteStatus(input);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const status: GitWorkflowServiceShape["status"] = Effect.fn("GitWorkflowService.status")(
|
||||
function* (input) {
|
||||
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
|
||||
return mergeGitStatusParts(local, remote);
|
||||
},
|
||||
);
|
||||
|
||||
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),
|
||||
),
|
||||
),
|
||||
status,
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
||||
invalidateStatus: gitManager.invalidateStatus,
|
||||
@@ -283,10 +241,8 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
gitManager.preparePullRequestThread,
|
||||
),
|
||||
listRefs: (input) =>
|
||||
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
|
||||
),
|
||||
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.andThen(git.listRefs(input)),
|
||||
),
|
||||
createWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
@@ -304,6 +260,7 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
||||
),
|
||||
initRepo: (input) => git.initRepo(input),
|
||||
renameBranch: (input) =>
|
||||
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
|
||||
Effect.andThen(git.renameBranch(input)),
|
||||
|
||||
File renamed without changes.
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
}).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* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
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 persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
|
||||
+280
-72
@@ -13,12 +13,14 @@ import {
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
|
||||
MAX_WHEN_EXPRESSION_DEPTH,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
type ServerRemoveKeybindingInput,
|
||||
type ServerUpsertKeybindingInput,
|
||||
THREAD_JUMP_KEYBINDING_COMMANDS,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import type { Mutable } from "effect/Types";
|
||||
import {
|
||||
Array,
|
||||
Cache,
|
||||
@@ -46,20 +48,278 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
} from "@t3tools/shared/keybindings";
|
||||
|
||||
export {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
};
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
| { type: "not" }
|
||||
| { type: "and" }
|
||||
| { 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(
|
||||
Schema.decodeTo(
|
||||
@@ -126,25 +386,6 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
|
||||
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 {
|
||||
const modifiers: string[] = [];
|
||||
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 KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
@@ -280,14 +523,7 @@ export interface KeybindingsShape {
|
||||
* oldest entries when needed.
|
||||
*/
|
||||
readonly upsertKeybindingRule: (
|
||||
input: ServerUpsertKeybindingInput,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
|
||||
/**
|
||||
* Remove a single persisted keybinding rule by exact key/command/when match.
|
||||
*/
|
||||
readonly removeKeybindingRule: (
|
||||
input: ServerRemoveKeybindingInput,
|
||||
rule: KeybindingRule,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
}
|
||||
|
||||
@@ -644,19 +880,12 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
upsertKeybindingRule: (input) =>
|
||||
upsertKeybindingRule: (rule) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const rule = keybindingRuleFromUpsertInput(input);
|
||||
const replaceTarget = replaceTargetFromUpsertInput(input);
|
||||
const nextConfig = [
|
||||
...customConfig.filter((entry) => {
|
||||
if (replaceTarget) {
|
||||
return !isSameKeybindingRule(entry, replaceTarget);
|
||||
}
|
||||
return !isSameKeybindingRule(entry, rule);
|
||||
}),
|
||||
...customConfig.filter((entry) => entry.command !== rule.command),
|
||||
rule,
|
||||
];
|
||||
const cappedConfig =
|
||||
@@ -684,27 +913,6 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
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;
|
||||
});
|
||||
|
||||
|
||||
@@ -41,7 +41,6 @@ import {
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
@@ -133,14 +132,7 @@ function createProviderServiceHarness(
|
||||
}
|
||||
|
||||
async function waitForThread(
|
||||
readModel: () => Promise<{
|
||||
readonly threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
readonly latestTurn: { readonly turnId: string } | null;
|
||||
readonly checkpoints: ReadonlyArray<{ readonly checkpointTurnCount: number }>;
|
||||
readonly activities: ReadonlyArray<{ readonly kind: string }>;
|
||||
}>;
|
||||
}>,
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: {
|
||||
latestTurn: { turnId: string } | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
@@ -154,8 +146,8 @@ async function waitForThread(
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const snapshot = await readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -239,7 +231,7 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
|
||||
|
||||
describe("CheckpointReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore | ProjectionSnapshotQuery,
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -287,10 +279,6 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-reactor-test-",
|
||||
@@ -303,6 +291,7 @@ describe("CheckpointReactor", () => {
|
||||
}).pipe(
|
||||
Effect.as({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -316,7 +305,6 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
@@ -335,7 +323,6 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
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 checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
@@ -401,7 +388,6 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
provider,
|
||||
cwd,
|
||||
drain,
|
||||
@@ -458,7 +444,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
@@ -556,7 +542,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
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"));
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
@@ -572,7 +558,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-main" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
@@ -629,7 +615,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
@@ -674,7 +660,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 &&
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
||||
@@ -809,7 +795,7 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
|
||||
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"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
@@ -938,10 +924,7 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.checkpoints.length === 1,
|
||||
);
|
||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||
|
||||
expect(thread.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread.checkpoints).toHaveLength(1);
|
||||
@@ -1123,7 +1106,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"),
|
||||
);
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
@@ -67,7 +66,6 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
@@ -126,26 +124,29 @@ const make = Effect.gen(function* () {
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
): 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 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) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||
};
|
||||
|
||||
const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
|
||||
projectId: ProjectId,
|
||||
) {
|
||||
const project = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(projectId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
return project ? [project] : [];
|
||||
if (thread) {
|
||||
const projectedSession = sessions.find((session) => session.threadId === thread.id);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
@@ -236,7 +237,6 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
@@ -330,7 +330,8 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
@@ -351,11 +352,10 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -406,7 +406,8 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
|
||||
threadId,
|
||||
@@ -427,11 +428,10 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -457,16 +457,16 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -539,16 +539,16 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects,
|
||||
projects: readModel.projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
@@ -586,7 +586,8 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
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) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
ProviderInstanceId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -43,13 +42,9 @@ async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-engine-test-",
|
||||
});
|
||||
const orchestrationLayer = Layer.mergeAll(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
),
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
).pipe(
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
@@ -59,10 +54,8 @@ async function createOrchestrationSystem() {
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
return {
|
||||
engine,
|
||||
readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
|
||||
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
|
||||
dispose: () => runtime.dispose(),
|
||||
};
|
||||
@@ -84,18 +77,15 @@ const hasMetricSnapshot = (
|
||||
);
|
||||
|
||||
describe("OrchestrationEngine", () => {
|
||||
it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
|
||||
let nextSequence = 8;
|
||||
const eventStore: OrchestrationEventStoreShape = {
|
||||
append: (event) =>
|
||||
Effect.sync(() => {
|
||||
const savedEvent = {
|
||||
...event,
|
||||
sequence: nextSequence,
|
||||
} as OrchestrationEvent;
|
||||
nextSequence += 1;
|
||||
return savedEvent;
|
||||
}),
|
||||
it("bootstraps the in-memory read model from persisted projections", async () => {
|
||||
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
|
||||
append: () =>
|
||||
Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "test.append",
|
||||
detail: "append should not be called during bootstrap",
|
||||
}),
|
||||
),
|
||||
readFromSequence: () => Stream.empty,
|
||||
readAll: () =>
|
||||
Stream.fail(
|
||||
@@ -150,27 +140,11 @@ describe("OrchestrationEngine", () => {
|
||||
},
|
||||
],
|
||||
};
|
||||
const commandReadModel = {
|
||||
...projectionSnapshot,
|
||||
threads: projectionSnapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
})),
|
||||
};
|
||||
let fullSnapshotReadCount = 0;
|
||||
|
||||
const layer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.succeed(commandReadModel),
|
||||
getSnapshot: () =>
|
||||
Effect.sync(() => {
|
||||
fullSnapshotReadCount += 1;
|
||||
return projectionSnapshot;
|
||||
}),
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
@@ -178,8 +152,6 @@ describe("OrchestrationEngine", () => {
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
@@ -195,7 +167,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: () => Effect.void,
|
||||
} satisfies OrchestrationProjectionPipelineShape),
|
||||
),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
@@ -203,22 +175,18 @@ describe("OrchestrationEngine", () => {
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const result = await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-bootstrap-thread-update"),
|
||||
threadId: ThreadId.make("thread-bootstrap"),
|
||||
title: "Updated Bootstrap Thread",
|
||||
}),
|
||||
);
|
||||
const readModel = await runtime.runPromise(engine.getReadModel());
|
||||
|
||||
expect(result.sequence).toBe(8);
|
||||
expect(fullSnapshotReadCount).toBe(0);
|
||||
expect(readModel.snapshotSequence).toBe(7);
|
||||
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();
|
||||
});
|
||||
|
||||
it("persists deterministic read models for repeated snapshot reads", async () => {
|
||||
it("returns deterministic read models for repeated reads", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
@@ -272,8 +240,8 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const readModelA = await system.readModel();
|
||||
const readModelB = await system.readModel();
|
||||
const readModelA = await system.run(engine.getReadModel());
|
||||
const readModelB = await system.run(engine.getReadModel());
|
||||
expect(readModelB).toEqual(readModelA);
|
||||
await system.dispose();
|
||||
});
|
||||
@@ -324,8 +292,9 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
||||
?.archivedAt,
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).not.toBeNull();
|
||||
|
||||
await system.run(
|
||||
@@ -336,8 +305,9 @@ describe("OrchestrationEngine", () => {
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
(await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
|
||||
?.archivedAt,
|
||||
(await system.run(engine.getReadModel())).threads.find(
|
||||
(thread) => thread.id === "thread-archive",
|
||||
)?.archivedAt,
|
||||
).toBeNull();
|
||||
|
||||
await system.dispose();
|
||||
@@ -603,7 +573,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",
|
||||
);
|
||||
expect(thread?.checkpoints).toEqual([
|
||||
@@ -731,15 +701,7 @@ describe("OrchestrationEngine", () => {
|
||||
);
|
||||
|
||||
expect(result.sequence).toBe(2);
|
||||
const eventsAfterRetry = await runtime.runPromise(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(eventsAfterRetry.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
@@ -839,6 +801,7 @@ describe("OrchestrationEngine", () => {
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
|
||||
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
|
||||
expect(retryResult.sequence).toBe(4);
|
||||
@@ -861,7 +824,7 @@ describe("OrchestrationEngine", () => {
|
||||
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 =
|
||||
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
||||
? A
|
||||
@@ -893,7 +856,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailProjection &&
|
||||
event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
|
||||
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
|
||||
) {
|
||||
shouldFailProjection = false;
|
||||
return Effect.fail(
|
||||
@@ -956,22 +919,20 @@ describe("OrchestrationEngine", () => {
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-sync-fail"),
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
title: "sync-after-failed-projection",
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("projection failed");
|
||||
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive-sync-retry"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("already archived");
|
||||
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
|
||||
const updatedThread = readModelAfterFailure.threads.find(
|
||||
(thread) => thread.id === "thread-sync",
|
||||
);
|
||||
expect(readModelAfterFailure.snapshotSequence).toBe(3);
|
||||
expect(updatedThread?.title).toBe("sync-after-failed-projection");
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
@@ -34,7 +34,6 @@ import {
|
||||
OrchestrationCommandInvariantError,
|
||||
OrchestrationCommandPreviouslyRejectedError,
|
||||
type OrchestrationDispatchError,
|
||||
type OrchestrationProjectorDecodeError,
|
||||
} from "../Errors.ts";
|
||||
import { decideOrchestrationCommand } from "../decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||
@@ -78,25 +77,13 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
let commandReadModel = createEmptyReadModel(new Date().toISOString());
|
||||
let readModel = createEmptyReadModel(new Date().toISOString());
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
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 dispatchStartSequence = commandReadModel.snapshotSequence;
|
||||
const dispatchStartSequence = readModel.snapshotSequence;
|
||||
const processingStartedAtMs = Date.now();
|
||||
const aggregateRef = commandToAggregateRef(envelope.command);
|
||||
const baseMetricAttributes = {
|
||||
@@ -111,7 +98,11 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
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) {
|
||||
yield* PubSub.publish(eventPubSub, persistedEvent);
|
||||
@@ -144,18 +135,18 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
const eventBase = yield* decideOrchestrationCommand({
|
||||
command: envelope.command,
|
||||
readModel: commandReadModel,
|
||||
readModel,
|
||||
});
|
||||
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
|
||||
const committedCommand = yield* sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const committedEvents: OrchestrationEvent[] = [];
|
||||
let nextCommandReadModel = commandReadModel;
|
||||
let nextReadModel = readModel;
|
||||
|
||||
for (const nextEvent of eventBases) {
|
||||
const savedEvent = yield* eventStore.append(nextEvent);
|
||||
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
|
||||
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
|
||||
yield* projectionPipeline.projectEvent(savedEvent);
|
||||
committedEvents.push(savedEvent);
|
||||
}
|
||||
@@ -181,7 +172,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
return {
|
||||
committedEvents,
|
||||
lastSequence: lastSavedEvent.sequence,
|
||||
nextCommandReadModel,
|
||||
nextReadModel,
|
||||
} 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()) {
|
||||
yield* PubSub.publish(eventPubSub, event);
|
||||
if (index === 0) {
|
||||
@@ -251,7 +242,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
).pipe(
|
||||
Effect.annotateLogs({
|
||||
commandId: envelope.command.commandId,
|
||||
snapshotSequence: commandReadModel.snapshotSequence,
|
||||
snapshotSequence: readModel.snapshotSequence,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -264,7 +255,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
aggregateKind: aggregateRef.aggregateKind,
|
||||
aggregateId: aggregateRef.aggregateId,
|
||||
acceptedAt: new Date().toISOString(),
|
||||
resultSequence: commandReadModel.snapshotSequence,
|
||||
resultSequence: readModel.snapshotSequence,
|
||||
status: "rejected",
|
||||
error: error.message,
|
||||
})
|
||||
@@ -279,14 +270,17 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
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) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive);
|
||||
|
||||
@@ -298,6 +292,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
getReadModel,
|
||||
readEvents,
|
||||
dispatch,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
|
||||
@@ -739,31 +739,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
if (Option.isNone(existingRow)) {
|
||||
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({
|
||||
...existingRow.value,
|
||||
latestTurnId,
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
|
||||
@@ -12,7 +12,6 @@ import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
@@ -1030,378 +1029,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));
|
||||
},
|
||||
);
|
||||
@@ -219,20 +219,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) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -244,37 +230,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
|
||||
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({
|
||||
Request: Schema.Void,
|
||||
@@ -380,6 +335,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_thread_activities
|
||||
ORDER BY
|
||||
thread_id ASC,
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
@@ -433,46 +389,18 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
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.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
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
state,
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -666,6 +594,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
@@ -963,9 +892,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
|
||||
projectRows,
|
||||
{ includeDeleted: true },
|
||||
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 projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
@@ -1023,199 +958,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"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
@@ -1244,7 +986,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listActiveLatestTurnRows(undefined).pipe(
|
||||
listLatestTurnRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",
|
||||
@@ -1288,7 +1030,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
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(
|
||||
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
|
||||
);
|
||||
@@ -1346,19 +1097,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"] = () =>
|
||||
readProjectionCounts(undefined).pipe(
|
||||
Effect.mapError(
|
||||
@@ -1638,7 +1376,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
}
|
||||
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) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
@@ -1676,10 +1422,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
getCommandReadModel,
|
||||
getSnapshot,
|
||||
getShellSnapshot,
|
||||
getSnapshotSequence,
|
||||
getCounts,
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
|
||||
@@ -45,7 +45,6 @@ import {
|
||||
} from "./ProviderCommandReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
@@ -80,7 +79,7 @@ async function waitFor(
|
||||
|
||||
describe("ProviderCommandReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderCommandReactor | ProjectionSnapshotQuery,
|
||||
OrchestrationEngineService | ProviderCommandReactor,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -241,6 +240,7 @@ describe("ProviderCommandReactor", () => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "renamed-branch",
|
||||
@@ -319,13 +319,8 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService)({
|
||||
@@ -354,7 +349,6 @@ describe("ProviderCommandReactor", () => {
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
@@ -389,7 +383,6 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -439,7 +432,7 @@ describe("ProviderCommandReactor", () => {
|
||||
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"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -484,13 +477,13 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.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"));
|
||||
expect(thread?.title).toBe("Generated title");
|
||||
});
|
||||
@@ -530,7 +523,7 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
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"));
|
||||
expect(thread?.title).toBe("Keep this custom title");
|
||||
});
|
||||
@@ -574,14 +567,14 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1);
|
||||
await waitFor(async () => {
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
return (
|
||||
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
|
||||
"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"));
|
||||
expect(thread?.title).toBe("Reconnect spinner resume bug");
|
||||
});
|
||||
@@ -910,7 +903,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"));
|
||||
expect(thread?.session?.providerName).toBe("claudeAgent");
|
||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("claudeAgent"));
|
||||
@@ -1022,7 +1015,7 @@ describe("ProviderCommandReactor", () => {
|
||||
resumeCursor: { opaque: "resume-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"));
|
||||
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
|
||||
});
|
||||
@@ -1213,7 +1206,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
@@ -1247,7 +1240,7 @@ describe("ProviderCommandReactor", () => {
|
||||
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"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
@@ -1350,7 +1343,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
@@ -1360,7 +1353,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
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"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
@@ -1412,7 +1405,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1424,7 +1417,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
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"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
@@ -1483,7 +1476,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1493,7 +1486,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.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"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -1647,7 +1640,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
@@ -1657,7 +1650,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.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"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
@@ -1818,7 +1811,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
@@ -1826,7 +1819,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"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -1927,7 +1920,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some(
|
||||
@@ -1935,7 +1928,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"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -1991,7 +1984,7 @@ describe("ProviderCommandReactor", () => {
|
||||
);
|
||||
|
||||
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"));
|
||||
expect(thread?.session).not.toBeNull();
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
ProviderDriverKind,
|
||||
type ProjectId,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
@@ -23,7 +22,6 @@ import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
@@ -169,7 +167,6 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
@@ -270,16 +267,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) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
return readModel.threads.find((entry) => entry.id === threadId);
|
||||
});
|
||||
|
||||
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
|
||||
@@ -289,7 +279,8 @@ const make = Effect.gen(function* () {
|
||||
readonly modelSelection?: ModelSelection;
|
||||
},
|
||||
) {
|
||||
const thread = yield* resolveThread(threadId);
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
@@ -384,10 +375,9 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
}
|
||||
const project = yield* resolveProject(thread.projectId);
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: project ? [project] : [],
|
||||
projects: readModel.projects,
|
||||
});
|
||||
|
||||
const startProviderSession = (input?: {
|
||||
@@ -692,11 +682,10 @@ const make = Effect.gen(function* () {
|
||||
const isFirstUserMessageTurn =
|
||||
thread.messages.filter((entry) => entry.role === "user").length === 1;
|
||||
if (isFirstUserMessageTurn) {
|
||||
const project = yield* resolveProject(thread.projectId);
|
||||
const generationCwd =
|
||||
resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: project ? [project] : [],
|
||||
projects: (yield* orchestrationEngine.getReadModel()).projects,
|
||||
}) ?? process.cwd();
|
||||
const generationInput = {
|
||||
messageText: message.text,
|
||||
@@ -830,16 +819,20 @@ const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
Effect.gen(function* () {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: isUnknownPendingApprovalRequestError(cause)
|
||||
? stalePendingRequestDetail("approval", event.payload.requestId)
|
||||
: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
|
||||
if (!isUnknownPendingApprovalRequestError(cause)) return;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -36,9 +36,11 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -152,23 +154,16 @@ function createProviderServiceHarness() {
|
||||
};
|
||||
}
|
||||
|
||||
type ProviderRuntimeTestReadModel = OrchestrationReadModel;
|
||||
type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
async function waitForThread(
|
||||
readModel: () => Promise<ProviderRuntimeTestReadModel>,
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: ProviderRuntimeTestThread) => boolean,
|
||||
timeoutMs = 2000,
|
||||
threadId: ThreadId = asThreadId("thread-1"),
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<ProviderRuntimeTestThread> => {
|
||||
const snapshot = await readModel();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === threadId);
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -181,9 +176,16 @@ async function waitForThread(
|
||||
return poll();
|
||||
}
|
||||
|
||||
type ProviderRuntimeTestReadModel = OrchestrationReadModel;
|
||||
type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number];
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery,
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -221,13 +223,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
|
||||
Layer.provide(RepositoryIdentityResolverLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
@@ -236,7 +233,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
|
||||
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
|
||||
@@ -303,7 +299,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
return {
|
||||
engine,
|
||||
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
|
||||
emit: provider.emit,
|
||||
setProviderSession: provider.setSession,
|
||||
drain,
|
||||
@@ -324,7 +319,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1",
|
||||
);
|
||||
|
||||
@@ -342,7 +337,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -369,7 +364,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
let thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) => entry.session?.status === "running" && entry.session?.activeTurnId === null,
|
||||
);
|
||||
expect(thread.session?.status).toBe("running");
|
||||
@@ -388,7 +383,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -409,7 +404,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "stopped" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -430,7 +425,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -454,7 +449,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-midturn-lifecycle",
|
||||
@@ -476,7 +471,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
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"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
|
||||
@@ -492,7 +487,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -529,7 +524,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-claude-placeholder",
|
||||
@@ -546,7 +541,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -565,7 +560,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary",
|
||||
);
|
||||
@@ -581,7 +576,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
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"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||
@@ -597,7 +592,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -616,7 +611,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-guarded-main",
|
||||
@@ -633,7 +628,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
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"));
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||
@@ -649,7 +644,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
@@ -698,7 +693,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-1" && !message.streaming,
|
||||
@@ -730,7 +725,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-no-delta" && !message.streaming,
|
||||
@@ -769,7 +764,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
|
||||
),
|
||||
@@ -824,7 +819,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
|
||||
),
|
||||
@@ -866,7 +861,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
|
||||
),
|
||||
@@ -899,7 +894,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-1:turn:turn-plan-final",
|
||||
@@ -1014,7 +1009,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1055,7 +1050,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
const sourceThreadBeforeStart = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1081,7 +1076,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadAfterStart = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1163,7 +1158,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
|
||||
2_000,
|
||||
@@ -1183,7 +1178,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1234,7 +1229,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
@@ -1345,7 +1340,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
@@ -1406,7 +1401,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await harness.readModel();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
@@ -1432,7 +1427,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer",
|
||||
);
|
||||
@@ -1471,7 +1466,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-1:turn:turn-plan-buffer",
|
||||
@@ -1497,7 +1492,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered",
|
||||
);
|
||||
@@ -1517,7 +1512,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
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"));
|
||||
expect(
|
||||
midThread?.messages.some(
|
||||
@@ -1539,7 +1534,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered" && !message.streaming,
|
||||
@@ -1565,7 +1560,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-flush",
|
||||
@@ -1598,7 +1593,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-flush" &&
|
||||
@@ -1625,7 +1620,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
|
||||
@@ -1664,7 +1659,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-user-input-flush" &&
|
||||
@@ -1693,7 +1688,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
|
||||
@@ -1726,7 +1721,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
),
|
||||
@@ -1755,7 +1750,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-append",
|
||||
@@ -1788,7 +1783,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append" &&
|
||||
@@ -1824,7 +1819,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append:segment:1" &&
|
||||
@@ -1887,7 +1882,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-request-segment",
|
||||
@@ -1920,7 +1915,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.readModel, (entry) =>
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment" &&
|
||||
@@ -1956,7 +1951,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1" &&
|
||||
@@ -2009,7 +2004,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-streaming-mode"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-mode",
|
||||
@@ -2029,7 +2024,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const liveThread = await waitForThread(harness.readModel, (entry) =>
|
||||
const liveThread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-mode" &&
|
||||
@@ -2057,7 +2052,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const finalThread = await waitForThread(harness.readModel, (entry) =>
|
||||
const finalThread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||
@@ -2084,7 +2079,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
turnId: asTurnId("turn-buffer-spill"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffer-spill",
|
||||
@@ -2117,7 +2112,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||
@@ -2145,7 +2140,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-complete-dedup",
|
||||
@@ -2190,7 +2185,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "ready" &&
|
||||
thread.session?.activeTurnId === null &&
|
||||
@@ -2248,7 +2243,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
@@ -2258,7 +2253,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
),
|
||||
);
|
||||
|
||||
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"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
@@ -2300,7 +2295,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-3" &&
|
||||
@@ -2326,7 +2321,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
@@ -2371,7 +2366,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "running" &&
|
||||
entry.session?.activeTurnId === "turn-warning" &&
|
||||
@@ -2420,7 +2415,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
@@ -2513,7 +2508,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.title === "Renamed by provider" &&
|
||||
entry.activities.some(
|
||||
@@ -2600,7 +2595,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2652,7 +2647,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2702,7 +2697,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
@@ -2737,7 +2732,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
|
||||
),
|
||||
@@ -2807,7 +2802,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed",
|
||||
@@ -2898,7 +2893,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested",
|
||||
@@ -2957,7 +2952,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-after-failure" &&
|
||||
|
||||
@@ -4,16 +4,12 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -23,9 +19,9 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
type ProviderRuntimeIngestionShape,
|
||||
@@ -81,82 +77,6 @@ function sameId(left: string | null | undefined, right: string | null | undefine
|
||||
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 {
|
||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||
}
|
||||
@@ -602,7 +522,6 @@ function runtimeEventToActivities(
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
@@ -634,16 +553,20 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
|
||||
});
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadShellById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return false;
|
||||
}
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return false;
|
||||
}
|
||||
return isGitRepository(workspaceCwd);
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>
|
||||
@@ -994,7 +917,7 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
||||
const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
@@ -1147,7 +1070,8 @@ const make = Effect.gen(function* () {
|
||||
implementationThreadId: ThreadId,
|
||||
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);
|
||||
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
|
||||
return;
|
||||
@@ -1172,19 +1096,10 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
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;
|
||||
|
||||
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 eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
@@ -1362,7 +1277,6 @@ const make = Effect.gen(function* () {
|
||||
? toTurnId(event.turnId)
|
||||
: undefined;
|
||||
if (pauseForUserTurnId) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
@@ -1393,11 +1307,10 @@ const make = Effect.gen(function* () {
|
||||
event.type === "request.opened"
|
||||
? "assistant-delta-finalize-on-request-opened"
|
||||
: "assistant-delta-finalize-on-user-input-requested",
|
||||
hasProjectedMessage:
|
||||
detailedThread !== null &&
|
||||
hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {
|
||||
streamingOnly: true,
|
||||
}),
|
||||
hasProjectedMessage: thread.messages.some(
|
||||
(entry) =>
|
||||
entry.role === "assistant" && entry.turnId === pauseForUserTurnId && entry.streaming,
|
||||
),
|
||||
flushedMessageIds,
|
||||
});
|
||||
}
|
||||
@@ -1426,19 +1339,21 @@ const make = Effect.gen(function* () {
|
||||
: undefined;
|
||||
|
||||
if (assistantCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const activeAssistantMessageId = turnId
|
||||
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
||||
: Option.none<MessageId>();
|
||||
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(
|
||||
activeAssistantMessageId,
|
||||
() => assistantCompletion.messageId,
|
||||
);
|
||||
const existingAssistantMessage = findMessageById(messages, assistantMessageId);
|
||||
const existingAssistantMessage = thread.messages.find(
|
||||
(entry) => entry.id === assistantMessageId,
|
||||
);
|
||||
const shouldApplyFallbackCompletionText =
|
||||
!existingAssistantMessage || existingAssistantMessage.text.length === 0;
|
||||
|
||||
@@ -1478,11 +1393,10 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (proposedPlanCompletion) {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: detailedThread?.proposedPlans ?? [],
|
||||
threadProposedPlans: thread.proposedPlans,
|
||||
planId: proposedPlanCompletion.planId,
|
||||
...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),
|
||||
fallbackMarkdown: proposedPlanCompletion.planMarkdown,
|
||||
@@ -1491,9 +1405,6 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const messages = detailedThread?.messages ?? [];
|
||||
const proposedPlans = detailedThread?.proposedPlans ?? [];
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);
|
||||
@@ -1508,7 +1419,9 @@ const make = Effect.gen(function* () {
|
||||
createdAt: now,
|
||||
commandTag: "assistant-complete-finalize",
|
||||
finalDeltaCommandTag: "assistant-delta-finalize-fallback",
|
||||
hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,
|
||||
hasProjectedMessage: thread.messages.some(
|
||||
(entry) => entry.id === assistantMessageId,
|
||||
),
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
@@ -1518,7 +1431,7 @@ const make = Effect.gen(function* () {
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
threadProposedPlans: proposedPlans,
|
||||
threadProposedPlans: thread.proposedPlans,
|
||||
planId: proposedPlanIdForTurn(thread.id, turnId),
|
||||
turnId,
|
||||
updatedAt: now,
|
||||
@@ -1570,24 +1483,21 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (event.type === "turn.diff.updated") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
const checkpointContext = turnId
|
||||
? yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(thread.id)
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
: undefined;
|
||||
const workspaceCwd =
|
||||
checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;
|
||||
if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {
|
||||
if (turnId && (yield* isGitRepoForThread(thread.id))) {
|
||||
// Skip if a checkpoint already exists for this turn. A real
|
||||
// (non-placeholder) capture from CheckpointReactor should not
|
||||
// be clobbered, and dispatching a duplicate placeholder for the
|
||||
// same turnId would produce an unstable checkpointTurnCount.
|
||||
if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {
|
||||
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
|
||||
// Already tracked; no-op.
|
||||
} else {
|
||||
const assistantMessageId = MessageId.make(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
|
||||
);
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
(max, c) => Math.max(max, c.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
||||
@@ -1598,7 +1508,7 @@ const make = Effect.gen(function* () {
|
||||
status: "missing",
|
||||
files: [],
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,
|
||||
checkpointTurnCount: maxTurnCount + 1,
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
*
|
||||
* @module OrchestrationEngineService
|
||||
*/
|
||||
import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } 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.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
@@ -59,7 +70,7 @@ export interface OrchestrationEngineShape {
|
||||
* ```ts
|
||||
* const program = Effect.gen(function* () {
|
||||
* const engine = yield* OrchestrationEngineService
|
||||
* return yield* engine.dispatch(command)
|
||||
* return yield* engine.getReadModel()
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
|
||||
@@ -28,10 +28,6 @@ export interface ProjectionSnapshotCounts {
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
export interface ProjectionSnapshotSequence {
|
||||
readonly snapshotSequence: number;
|
||||
}
|
||||
|
||||
export interface ProjectionThreadCheckpointContext {
|
||||
readonly threadId: ThreadId;
|
||||
readonly projectId: ProjectId;
|
||||
@@ -44,15 +40,6 @@ export interface ProjectionThreadCheckpointContext {
|
||||
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
@@ -72,15 +59,6 @@ export interface ProjectionSnapshotQueryShape {
|
||||
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.
|
||||
*/
|
||||
|
||||
@@ -41,7 +41,6 @@ import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingAppro
|
||||
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.
|
||||
@@ -82,7 +81,6 @@ export const migrationEntries = [
|
||||
[26, "CanonicalizeModelSelectionOptions", Migration0026],
|
||||
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
|
||||
[28, "ProjectionThreadSessionInstanceId", Migration0028],
|
||||
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
-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)
|
||||
`;
|
||||
});
|
||||
@@ -1,52 +1,53 @@
|
||||
import { ProjectId, type OrchestrationProject } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
|
||||
|
||||
const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
|
||||
Effect.succeed(
|
||||
workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
|
||||
),
|
||||
getProjectShellById: (projectId) =>
|
||||
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
});
|
||||
const emptySnapshot = (
|
||||
scripts: OrchestrationReadModel["projects"][number]["scripts"],
|
||||
): OrchestrationReadModel =>
|
||||
({
|
||||
snapshotSequence: 1,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [],
|
||||
providerSessions: [],
|
||||
providerStatuses: [],
|
||||
pendingApprovals: [],
|
||||
latestTurnByThreadId: {},
|
||||
}) as unknown as OrchestrationReadModel;
|
||||
|
||||
describe("ProjectSetupScriptRunner", () => {
|
||||
it("returns no-script when no setup script exists", async () => {
|
||||
const open = vi.fn();
|
||||
const write = vi.fn();
|
||||
const project = makeProject([]);
|
||||
const runner = await Effect.runPromise(
|
||||
Effect.service(ProjectSetupScriptRunner).pipe(
|
||||
Effect.provide(
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.succeed(emptySnapshot([])),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die(new Error("unused")),
|
||||
streamDomainEvents: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
@@ -92,20 +93,29 @@ describe("ProjectSetupScriptRunner", () => {
|
||||
}),
|
||||
);
|
||||
const write = vi.fn(() => Effect.void);
|
||||
const project = makeProject([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
const runner = await Effect.runPromise(
|
||||
Effect.service(ProjectSetupScriptRunner).pipe(
|
||||
Effect.provide(
|
||||
ProjectSetupScriptRunnerLive.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
getReadModel: () =>
|
||||
Effect.succeed(
|
||||
emptySnapshot([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]),
|
||||
),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.die(new Error("unused")),
|
||||
streamDomainEvents: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(TerminalManager, {
|
||||
open,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { ProjectId } from "@t3tools/contracts";
|
||||
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import {
|
||||
type ProjectSetupScriptRunnerShape,
|
||||
@@ -10,21 +9,18 @@ import {
|
||||
} from "../Services/ProjectSetupScriptRunner.ts";
|
||||
|
||||
const makeProjectSetupScriptRunner = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
|
||||
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const project =
|
||||
(input.projectId
|
||||
? yield* projectionSnapshotQuery
|
||||
.getProjectShellById(ProjectId.make(input.projectId))
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
? readModel.projects.find((entry) => entry.id === input.projectId)
|
||||
: null) ??
|
||||
(input.projectCwd
|
||||
? yield* projectionSnapshotQuery
|
||||
.getActiveProjectByWorkspaceRoot(input.projectCwd)
|
||||
.pipe(Effect.map(Option.getOrUndefined))
|
||||
? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
|
||||
: null) ??
|
||||
null;
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
@@ -35,43 +34,15 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.local/bin/claude") ||
|
||||
normalized.endsWith("/.local/bin/claude.exe") ||
|
||||
normalized.includes("/.local/share/claude/")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@anthropic-ai/claude-code",
|
||||
homebrewFormula: "claude-code",
|
||||
nativeUpdate: {
|
||||
executable: "claude",
|
||||
args: ["update"],
|
||||
lockKey: "claude-native",
|
||||
isCommandPath: isClaudeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -104,7 +75,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -112,10 +82,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
instanceId,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
@@ -155,17 +121,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
@@ -36,11 +35,6 @@ import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import {
|
||||
codexContinuationIdentity,
|
||||
materializeCodexShadowHome,
|
||||
@@ -49,12 +43,6 @@ import {
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
homebrewFormula: "codex",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Services the driver needs to materialize an instance. Surfaced as the
|
||||
@@ -64,7 +52,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
export type CodexDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -102,7 +89,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
@@ -129,10 +115,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
enabled,
|
||||
homePath: homeLayout.effectiveHomePath ?? "",
|
||||
} satisfies CodexSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
|
||||
// channels at construction time — their failure modes are all on the
|
||||
@@ -156,17 +138,11 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const snapshot = yield* makeManagedServerProvider<CodexSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -35,28 +34,13 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
}),
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -90,7 +74,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -104,10 +87,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeCursorAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
@@ -124,7 +103,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<CursorSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
@@ -139,10 +117,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
settings,
|
||||
environment: processEnv,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
@@ -35,40 +34,13 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.opencode/bin/opencode") ||
|
||||
normalized.endsWith("/.opencode/bin/opencode.exe")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "opencode-ai",
|
||||
homebrewFormula: "anomalyco/tap/opencode",
|
||||
nativeUpdate: {
|
||||
executable: "opencode",
|
||||
args: ["upgrade"],
|
||||
lockKey: "opencode-native",
|
||||
isCommandPath: isOpenCodeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
@@ -102,7 +74,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -116,10 +87,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
@@ -135,17 +102,11 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -2873,7 +2873,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
pathToClaudeCodeExecutable: claudeBinaryPath,
|
||||
systemPrompt: { type: "preset", preset: "claude_code" },
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
|
||||
// the published `Options["effort"]` union currently stops at `max`.
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
|
||||
@@ -12,7 +12,6 @@ import type {
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
@@ -30,10 +29,6 @@ import {
|
||||
type CommandResult,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("cursor");
|
||||
@@ -1221,67 +1216,42 @@ export const enrichCursorSnapshot = (input: {
|
||||
readonly settings: CursorSettings;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
const enrichVersionAdvisory = enrichProviderSnapshotWithVersionAdvisory(
|
||||
snapshot,
|
||||
input.maintenanceCapabilities,
|
||||
).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor version advisory enrichment failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(snapshot)),
|
||||
),
|
||||
);
|
||||
if (
|
||||
!settings.enabled ||
|
||||
snapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(snapshot)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return enrichVersionAdvisory.pipe(
|
||||
Effect.flatMap((baseSnapshot) => {
|
||||
if (
|
||||
!settings.enabled ||
|
||||
baseSnapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(baseSnapshot)
|
||||
) {
|
||||
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return discoverCursorModelCapabilitiesViaAcp(
|
||||
settings,
|
||||
baseSnapshot.models,
|
||||
input.environment,
|
||||
).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...baseSnapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
);
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...snapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: baseSnapshot.models.map((model) => model.slug),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: snapshot.models.map((model) => model.slug),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { Cause, Data, Effect } from "effect";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
nonEmptyTrimmed,
|
||||
|
||||
@@ -14,7 +14,6 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -112,10 +111,6 @@ const makeFakeInstance = (
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
|
||||
refresh: Effect.succeed({} as unknown as ServerProvider),
|
||||
streamChanges: Stream.empty,
|
||||
|
||||
@@ -34,7 +34,6 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
@@ -45,13 +44,6 @@ import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -97,7 +89,6 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
@@ -234,7 +225,6 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
@@ -27,17 +26,13 @@ import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistr
|
||||
import {
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
mergeProviderSnapshots,
|
||||
ProviderRegistryLive,
|
||||
selectProvidersByKind,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
|
||||
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
@@ -51,13 +46,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -258,7 +246,7 @@ function makeMutableServerSettingsService(
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), TestHttpClientLive))(
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
"ProviderRegistry",
|
||||
(it) => {
|
||||
describe("checkCodexProviderStatus", () => {
|
||||
@@ -512,182 +500,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
]);
|
||||
});
|
||||
|
||||
it("persists merged provider snapshots for the providers that were refreshed", () => {
|
||||
const previousProviders = [
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
driver: ProviderDriverKind.make("cursor"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
booleanDescriptor("fastMode", "Fast Mode"),
|
||||
booleanDescriptor("thinking", "Thinking"),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
const refreshedCursor = {
|
||||
...previousProviders[0],
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
|
||||
const persistedProviders = selectProvidersByKind(
|
||||
mergedProviders,
|
||||
new Set([ProviderDriverKind.make("cursor")]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(persistedProviders, [
|
||||
{
|
||||
...refreshedCursor,
|
||||
models: [...previousProviders[0].models],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("persists the merged snapshot when a live update has empty models", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorDriver = ProviderDriverKind.make("cursor");
|
||||
const cursorInstanceId = ProviderInstanceId.make("cursor");
|
||||
const initialProvider = {
|
||||
instanceId: cursorInstanceId,
|
||||
driver: cursorDriver,
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...initialProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
const changes = yield* PubSub.unbounded<ServerProvider>();
|
||||
const instance = {
|
||||
instanceId: cursorInstanceId,
|
||||
driverKind: cursorDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: cursorDriver,
|
||||
continuationKey: "cursor:instance:cursor",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cursorDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(refreshedProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === cursorInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
});
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: cursorInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
|
||||
...initialProvider.models,
|
||||
]);
|
||||
yield* PubSub.publish(changes, refreshedProvider);
|
||||
|
||||
let cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
|
||||
attempt += 1
|
||||
) {
|
||||
yield* Effect.sleep("10 millis");
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider, {
|
||||
...refreshedProvider,
|
||||
models: [...initialProvider.models],
|
||||
});
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
@@ -715,10 +527,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(cachedProvider),
|
||||
refresh: Effect.die(new Error("simulated refresh failure")),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -804,10 +612,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: provider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(provider),
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -944,7 +748,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
@@ -1029,7 +832,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// `it.live` does not inherit layers from the outer `it.layer`
|
||||
@@ -1134,7 +936,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -1185,7 +986,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -44,7 +43,6 @@ import {
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
const loadProviders = (
|
||||
@@ -61,12 +59,6 @@ const loadProviders = (
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
@@ -104,30 +96,6 @@ export const mergeProviderSnapshot = (
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
@@ -259,9 +227,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
@@ -299,21 +264,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
@@ -322,24 +272,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
for (const provider of nextProviders) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
@@ -349,16 +290,13 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
@@ -380,45 +318,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
@@ -466,18 +365,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
@@ -585,15 +472,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
@@ -677,8 +555,6 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
|
||||
@@ -9,7 +9,10 @@ import {
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Option, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
@@ -89,10 +92,6 @@ function makeReadModel(
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: thread.session,
|
||||
@@ -164,6 +163,13 @@ describe("ProviderSessionReaper", () => {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const orchestrationEngine: OrchestrationEngineShape = {
|
||||
getReadModel: () => Effect.succeed(input.readModel),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => unsupported(),
|
||||
streamDomainEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
@@ -177,27 +183,7 @@ describe("ProviderSessionReaper", () => {
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.readModel.threads.find((thread) => thread.id === threadId)
|
||||
? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Duration, Effect, Layer, Option, Schedule } from "effect";
|
||||
import { Duration, Effect, Layer, Schedule } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
@@ -20,7 +20,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
@@ -29,6 +29,8 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
|
||||
const sweep = Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
|
||||
const bindings = yield* directory.listBindings();
|
||||
const now = Date.now();
|
||||
let reapedCount = 0;
|
||||
@@ -53,9 +55,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =
|
||||
continue;
|
||||
}
|
||||
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(binding.threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const thread = threadsById.get(binding.threadId);
|
||||
if (thread?.session?.activeTurnId != null) {
|
||||
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
|
||||
threadId: binding.threadId,
|
||||
|
||||
@@ -6,17 +6,9 @@
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ServerProvider,
|
||||
ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ProviderInstanceId, ProviderDriverKind, ServerProvider } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
@@ -47,27 +39,6 @@ export interface ProviderRegistryShape {
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance.
|
||||
* This state is never persisted to disk. Today only update actions are
|
||||
* projected onto `ServerProvider.updateState`; install/auth actions can
|
||||
* extend this action map without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates — one emission per aggregated
|
||||
* change. The array contains the full current state.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export interface ServerProviderShape {
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
|
||||
@@ -20,20 +20,6 @@ interface TestSettings {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
const maintenanceCapabilities = {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
packageName: "@openai/codex",
|
||||
update: {
|
||||
command: "npm install -g @openai/codex@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
} as const;
|
||||
|
||||
const initialSnapshot: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
@@ -104,7 +90,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -146,7 +131,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseInitialCheck = yield* Deferred.make<void>();
|
||||
const releaseSettingsCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Ref.get(settingsRef),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -188,7 +172,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseEnrichment = yield* Deferred.make<void>();
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -229,7 +212,6 @@ describe("makeManagedServerProvider", () => {
|
||||
const secondCallbackReady = yield* Deferred.make<void>();
|
||||
const allowFirstRefresh = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
|
||||
@@ -13,7 +13,6 @@ interface ProviderSnapshotState {
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
@@ -144,7 +143,6 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
);
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
|
||||
@@ -1,487 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { Effect, Random } from "effect";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
createProviderVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* (name: string) {
|
||||
const id = yield* Random.nextUUIDv4;
|
||||
return path.join(os.tmpdir(), `${name}-${id}`);
|
||||
});
|
||||
const isNativeTestCommandPath =
|
||||
(expectedPathSegment: string) =>
|
||||
(commandPath: string): boolean =>
|
||||
normalizeCommandPath(commandPath).includes(expectedPathSegment);
|
||||
const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("packageTool"),
|
||||
npmPackageName: "@example/package-tool",
|
||||
homebrewFormula: "package-tool",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("nativePackageTool"),
|
||||
npmPackageName: "@example/native-package-tool",
|
||||
homebrewFormula: "native-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "native-package-tool",
|
||||
args: ["update"],
|
||||
lockKey: "native-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
|
||||
},
|
||||
});
|
||||
const scopedPackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("scopedPackageTool"),
|
||||
npmPackageName: "@example/scoped-package-tool",
|
||||
homebrewFormula: "example/tap/scoped-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "scoped-package-tool",
|
||||
args: ["upgrade"],
|
||||
lockKey: "scoped-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.scoped-package-tool/bin/scoped-package-tool"),
|
||||
},
|
||||
});
|
||||
const staticToolUpdate = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
updateExecutable: "static-tool",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "static-tool",
|
||||
}),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
describe("providerMaintenance", () => {
|
||||
it("marks providers with unknown current versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks providers with unknown latest versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
message: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks installed providers behind latest when a newer provider version is available", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("nativePackageTool"),
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
maintenanceCapabilities: nativePackageToolUpdate.resolve(),
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
updateCommand: "npm install -g @example/native-package-tool@latest",
|
||||
canUpdate: true,
|
||||
message: "Install the update now or review provider settings.",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps update commands owned by provider maintenance capabilities", () => {
|
||||
expect(staticToolUpdate.resolve()).toEqual({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
update: {
|
||||
command: "static-tool update",
|
||||
|
||||
executable: "static-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "static-tool",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to vite-plus updates when the resolved binary lives in vite-plus global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-vite-plus-capabilities");
|
||||
const vitePlusBinDir = path.join(tempDir, ".vite-plus", "bin");
|
||||
mkdirSync(vitePlusBinDir, { recursive: true });
|
||||
const packageToolPath = path.join(vitePlusBinDir, "package-tool");
|
||||
writeFileSync(packageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(packageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: vitePlusBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "vp i -g @example/package-tool",
|
||||
|
||||
executable: "vp",
|
||||
|
||||
args: ["i", "-g", "@example/package-tool"],
|
||||
|
||||
lockKey: "vite-plus-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to bun updates when the resolved binary lives in bun's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-bun-capabilities");
|
||||
const bunBinDir = path.join(tempDir, ".bun", "bin");
|
||||
mkdirSync(bunBinDir, { recursive: true });
|
||||
writeFileSync(path.join(bunBinDir, "native-package-tool.exe"), "MZ");
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: bunBinDir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "bun i -g @example/native-package-tool@latest",
|
||||
|
||||
executable: "bun",
|
||||
|
||||
args: ["i", "-g", "@example/native-package-tool@latest"],
|
||||
|
||||
lockKey: "bun-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to pnpm updates when the resolved binary lives in pnpm's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
|
||||
const pnpmHomeDir = path.join(tempDir, ".local", "share", "pnpm");
|
||||
mkdirSync(pnpmHomeDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(pnpmHomeDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: pnpmHomeDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/scoped-package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/scoped-package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "brew upgrade package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches native-package-tool to native updates when the binary resolves through the native installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-native-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".local", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const nativePackageToolPath = path.join(nativeBinDir, "native-package-tool");
|
||||
writeFileSync(nativePackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(nativePackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "native-package-tool update",
|
||||
|
||||
executable: "native-package-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "native-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches scoped-package-tool to native upgrades when the binary resolves through the standalone installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-scoped-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".scoped-package-tool", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(nativeBinDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "scoped-package-tool upgrade",
|
||||
|
||||
executable: "scoped-package-tool",
|
||||
|
||||
args: ["upgrade"],
|
||||
|
||||
lockKey: "scoped-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches native-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade native-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "native-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("switches scoped-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade example/tap/scoped-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "example/tap/scoped-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps npm updates for binaries symlinked into npm's global node_modules tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-npm-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
"lib",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "npm install -g @example/package-tool@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses Effect FileSystem realPath when detecting pnpm global symlinks", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-realpath-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
".local",
|
||||
"share",
|
||||
"pnpm",
|
||||
"global",
|
||||
"5",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("disables one-click updates for explicit custom binary paths it cannot safely map", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "C:\\Tools\\package-tool\\package-tool.exe",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,472 +0,0 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderVersionAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import { DateTime, Effect, FileSystem, Option, Schema } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import { compareCliVersions } from "./cliVersion.ts";
|
||||
|
||||
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
|
||||
const LATEST_VERSION_TIMEOUT_MS = 4_000;
|
||||
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
|
||||
|
||||
export interface ProviderMaintenanceCapabilities {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly update: ProviderMaintenanceCommandAction | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCommandAction {
|
||||
readonly command: string;
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilityResolutionOptions {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly realCommandPath?: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilitiesResolver {
|
||||
readonly resolve: (
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
) => ProviderMaintenanceCapabilities;
|
||||
}
|
||||
|
||||
export interface PackageManagedProviderMaintenanceDefinition {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly npmPackageName: string;
|
||||
readonly homebrewFormula: string | null;
|
||||
readonly nativeUpdate: {
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
readonly isCommandPath: (commandPath: string) => boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface LatestVersionCacheEntry {
|
||||
readonly expiresAt: number;
|
||||
readonly version: string | null;
|
||||
}
|
||||
|
||||
const latestVersionCache = new Map<string, LatestVersionCacheEntry>();
|
||||
const NpmLatestVersionResponse = Schema.Struct({
|
||||
version: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export function clearLatestProviderVersionCacheForTests(): void {
|
||||
latestVersionCache.clear();
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function makeProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly updateExecutable: string | null;
|
||||
readonly updateArgs: ReadonlyArray<string>;
|
||||
readonly updateLockKey: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
const update =
|
||||
input.updateExecutable === null || input.updateLockKey === null
|
||||
? null
|
||||
: {
|
||||
command: [input.updateExecutable, ...input.updateArgs].join(" "),
|
||||
executable: input.updateExecutable,
|
||||
args: input.updateArgs,
|
||||
lockKey: input.updateLockKey,
|
||||
};
|
||||
return {
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
update,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeManualOnlyProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
updateExecutable: null,
|
||||
updateArgs: [],
|
||||
updateLockKey: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeNpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeBunGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "bun-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makePnpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "pnpm",
|
||||
updateArgs: ["add", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "pnpm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeVitePlusGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", definition.npmPackageName],
|
||||
updateLockKey: "vite-plus-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeHomebrewProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
if (!definition.homebrewFormula) {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "brew",
|
||||
updateArgs: ["upgrade", definition.homebrewFormula],
|
||||
updateLockKey: "homebrew",
|
||||
});
|
||||
}
|
||||
|
||||
function makeNativeProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities | null {
|
||||
if (!definition.nativeUpdate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: definition.nativeUpdate.executable,
|
||||
updateArgs: definition.nativeUpdate.args,
|
||||
updateLockKey: definition.nativeUpdate.lockKey,
|
||||
});
|
||||
}
|
||||
|
||||
export function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
}
|
||||
|
||||
export function normalizeCommandPath(commandPath: string): string {
|
||||
return commandPath.replaceAll("\\", "/").toLowerCase();
|
||||
}
|
||||
|
||||
function isBunGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.bun/bin/");
|
||||
}
|
||||
|
||||
function isVitePlusGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
|
||||
}
|
||||
|
||||
function isPnpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/.local/share/pnpm/") ||
|
||||
normalized.includes("/library/pnpm/") ||
|
||||
normalized.includes("/local/share/pnpm/") ||
|
||||
normalized.includes("/appdata/local/pnpm/") ||
|
||||
normalized.includes("/pnpm/global/")
|
||||
);
|
||||
}
|
||||
|
||||
function isNpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/node_modules/.bin/") ||
|
||||
normalized.includes("/lib/node_modules/") ||
|
||||
normalized.includes("/npm/node_modules/")
|
||||
);
|
||||
}
|
||||
|
||||
function isHomebrewCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/opt/homebrew/cellar/") ||
|
||||
normalized.includes("/usr/local/cellar/") ||
|
||||
normalized.includes("/homebrew/cellar/") ||
|
||||
normalized.includes("/opt/homebrew/caskroom/") ||
|
||||
normalized.includes("/usr/local/caskroom/") ||
|
||||
normalized.includes("/homebrew/caskroom/") ||
|
||||
normalized.startsWith("/opt/homebrew/bin/") ||
|
||||
normalized.startsWith("/usr/local/bin/")
|
||||
);
|
||||
}
|
||||
|
||||
export function resolvePackageManagedProviderMaintenance(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
|
||||
if (resolvedCommandPath) {
|
||||
const commandPaths = [
|
||||
resolvedCommandPath,
|
||||
...(options?.realCommandPath ? [options.realCommandPath] : []),
|
||||
];
|
||||
|
||||
const nativeUpdate = definition.nativeUpdate;
|
||||
if (
|
||||
nativeUpdate &&
|
||||
commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))
|
||||
) {
|
||||
return (
|
||||
makeNativeProviderMaintenanceCapabilities(definition) ??
|
||||
makeNpmGlobalProviderMaintenanceCapabilities(definition)
|
||||
);
|
||||
}
|
||||
if (commandPaths.some(isVitePlusGlobalCommandPath)) {
|
||||
return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isBunGlobalCommandPath)) {
|
||||
return makeBunGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isPnpmGlobalCommandPath)) {
|
||||
return makePnpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isNpmGlobalCommandPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isHomebrewCommandPath)) {
|
||||
return makeHomebrewProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPathSeparator(binaryPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
export function makePackageManagedProviderMaintenanceResolver(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeStaticProviderMaintenanceResolver(
|
||||
capabilities: ProviderMaintenanceCapabilities,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: () => capabilities,
|
||||
};
|
||||
}
|
||||
|
||||
function makeManualProviderMaintenanceCapabilities(
|
||||
provider: ProviderDriverKind,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
"resolveProviderMaintenanceCapabilitiesEffect",
|
||||
)(function* (
|
||||
resolver: ProviderMaintenanceCapabilitiesResolver,
|
||||
options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, "realCommandPath">,
|
||||
) {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
if (!resolvedCommandPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCommandPath = yield* fileSystem
|
||||
.realPath(resolvedCommandPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(resolvedCommandPath)));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
realCommandPath,
|
||||
});
|
||||
});
|
||||
|
||||
function deriveVersionAdvisory(input: {
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion: string | null;
|
||||
}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
|
||||
if (!input.currentVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (!input.latestVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
|
||||
return {
|
||||
status: "behind_latest",
|
||||
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
|
||||
};
|
||||
}
|
||||
return { status: "current", message: null };
|
||||
}
|
||||
|
||||
export function createProviderVersionAdvisory(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion?: string | null;
|
||||
readonly checkedAt?: string | null;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
|
||||
}): ServerProviderVersionAdvisory {
|
||||
const capabilities =
|
||||
input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
|
||||
const latestVersion = input.latestVersion ?? null;
|
||||
const advisory = deriveVersionAdvisory({
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
});
|
||||
|
||||
return {
|
||||
status: advisory.status,
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
updateCommand: capabilities.update?.command ?? null,
|
||||
canUpdate: capabilities.update !== null,
|
||||
checkedAt: input.checkedAt ?? null,
|
||||
message: advisory.message,
|
||||
};
|
||||
}
|
||||
|
||||
const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const request = HttpClientRequest.get(
|
||||
`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
|
||||
).pipe(HttpClientRequest.setHeader("accept", "application/json"));
|
||||
const response = yield* client.execute(request).pipe(
|
||||
Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
if (Option.isNone(response)) {
|
||||
return null;
|
||||
}
|
||||
const httpResponse = response.value;
|
||||
if (httpResponse.status < 200 || httpResponse.status >= 300) {
|
||||
return null;
|
||||
}
|
||||
const payload = yield* httpResponse.json.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return payload ? nonEmptyString(payload.version) : null;
|
||||
});
|
||||
|
||||
export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
) {
|
||||
const packageName = maintenanceCapabilities.packageName;
|
||||
if (!packageName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cached = latestVersionCache.get(packageName);
|
||||
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.version;
|
||||
}
|
||||
|
||||
const version = yield* fetchNpmLatestVersion(packageName);
|
||||
latestVersionCache.set(packageName, {
|
||||
expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
|
||||
version,
|
||||
});
|
||||
return version;
|
||||
});
|
||||
|
||||
export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
|
||||
"enrichProviderSnapshotWithVersionAdvisory",
|
||||
)(function* (snapshot: ServerProvider, maintenanceCapabilities?: ProviderMaintenanceCapabilities) {
|
||||
const capabilities =
|
||||
maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
|
||||
if (!snapshot.enabled || !snapshot.installed || !snapshot.version) {
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
checkedAt: snapshot.checkedAt,
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const latestVersion = yield* resolveLatestProviderVersion(capabilities);
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
latestVersion,
|
||||
checkedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
import { Effect, Ref } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
export interface ProviderMaintenanceCommandCoordinatorShape<E> {
|
||||
readonly withCommandLock: <A, R>(input: {
|
||||
readonly targetKey: string;
|
||||
readonly lockKey: string;
|
||||
readonly onQueued?: Effect.Effect<void, E, R>;
|
||||
readonly run: Effect.Effect<A, E, R>;
|
||||
}) => Effect.Effect<A, E, R>;
|
||||
}
|
||||
|
||||
export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
|
||||
"makeProviderMaintenanceCommandCoordinator",
|
||||
)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {
|
||||
const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());
|
||||
|
||||
const acquireTarget = Effect.fn("acquireTarget")(function* (targetKey: string) {
|
||||
return yield* Ref.modify(runningTargetsRef, (runningTargets) => {
|
||||
if (runningTargets.has(targetKey)) {
|
||||
return [false, runningTargets] as const;
|
||||
}
|
||||
const next = new Set(runningTargets);
|
||||
next.add(targetKey);
|
||||
return [true, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const releaseTarget = (targetKey: string) =>
|
||||
Ref.update(runningTargetsRef, (runningTargets) => {
|
||||
const next = new Set(runningTargets);
|
||||
next.delete(targetKey);
|
||||
return next;
|
||||
});
|
||||
|
||||
const getLock = Effect.fn("getProviderMaintenanceCommandLock")(function* (lockKey: string) {
|
||||
const existing = (yield* Ref.get(locksRef)).get(lockKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const lock = yield* Semaphore.make(1);
|
||||
return yield* Ref.modify(locksRef, (locks) => {
|
||||
const current = locks.get(lockKey);
|
||||
if (current) {
|
||||
return [current, locks] as const;
|
||||
}
|
||||
const next = new Map(locks);
|
||||
next.set(lockKey, lock);
|
||||
return [lock, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({
|
||||
targetKey,
|
||||
lockKey,
|
||||
onQueued,
|
||||
run,
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const acquired = yield* acquireTarget(targetKey);
|
||||
if (!acquired) {
|
||||
return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const lock = yield* getLock(lockKey);
|
||||
if (onQueued) {
|
||||
yield* onQueued;
|
||||
}
|
||||
return yield* lock.withPermits(1)(run);
|
||||
}).pipe(Effect.ensuring(releaseTarget(targetKey)));
|
||||
});
|
||||
|
||||
return {
|
||||
withCommandLock,
|
||||
} satisfies ProviderMaintenanceCommandCoordinatorShape<E>;
|
||||
});
|
||||
@@ -1,640 +0,0 @@
|
||||
import { afterEach, describe, it, assert } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServerProviderUpdateError } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Exit, Fiber, Layer, Ref, Schema, Sink, Stream } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
|
||||
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
|
||||
if (provider === CURSOR_DRIVER) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
});
|
||||
}
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
const baseProvider: ServerProvider = {
|
||||
instanceId: CODEX_INSTANCE_ID,
|
||||
driver: CODEX_DRIVER,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const baseCursorProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: CURSOR_INSTANCE_ID,
|
||||
driver: CURSOR_DRIVER,
|
||||
};
|
||||
|
||||
const baseOpenCodeProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: OPENCODE_INSTANCE_ID,
|
||||
driver: OPENCODE_DRIVER,
|
||||
};
|
||||
|
||||
const latestVersionHttpClient = (version: string) =>
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ version }, { headers: { "content-type": "application/json" } }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: result.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
},
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeRegistry(
|
||||
initialProviders: ServerProvider | ReadonlyArray<ServerProvider> = baseProvider,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
Array.isArray(initialProviders) ? initialProviders : [initialProviders],
|
||||
);
|
||||
const updateStatesRef = yield* Ref.make<ReadonlyArray<ServerProviderUpdateState>>([]);
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn(
|
||||
"providerMaintenanceRunner.test.setProviderMaintenanceActionState",
|
||||
)(function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
const updateState = input.state;
|
||||
if (updateState) {
|
||||
yield* Ref.update(updateStatesRef, (states) => [...states, updateState]);
|
||||
}
|
||||
return yield* Ref.updateAndGet(providersRef, (providers) =>
|
||||
providers.map((candidate) => {
|
||||
if (candidate.instanceId !== input.instanceId) {
|
||||
return candidate;
|
||||
}
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = candidate;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
updateState,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const registry: ProviderRegistryShape = {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: () => Ref.get(providersRef),
|
||||
refreshInstance: () => Ref.get(providersRef),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(lifecycleFor(provider)),
|
||||
setProviderMaintenanceActionState,
|
||||
streamChanges: Stream.empty,
|
||||
};
|
||||
|
||||
return {
|
||||
registry,
|
||||
updateStatesRef,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const makeTestRunner = (registry: ProviderRegistryShape) =>
|
||||
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
|
||||
Effect.provide(
|
||||
ProviderMaintenanceRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ProviderRegistry, registry)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("providerMaintenanceRunner", () => {
|
||||
it.effect("runs the allowlisted provider update command and records success", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry, updateStatesRef } = yield* makeRegistry(baseCursorProvider);
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CURSOR_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "agent",
|
||||
args: ["update"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(updateStatesRef)).map((state) => state.status),
|
||||
["queued", "running", "succeeded"],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("uses the resolved provider capabilities when choosing the update executable", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.0.14",
|
||||
latestVersion: "2.1.123",
|
||||
updateCommand: "bun i -g @anthropic-ai/claude-code@latest",
|
||||
canUpdate: true,
|
||||
checkedAt: "2026-04-30T12:00:00.000Z",
|
||||
message: "Update available.",
|
||||
},
|
||||
});
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: () =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: CODEX_DRIVER,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "bun-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "bun",
|
||||
args: ["i", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"runs update commands through Effect ChildProcess when no test runner is injected",
|
||||
() => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const runner = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* runner.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "npm",
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("updates a single provider instance without touching sibling instances", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const personalInstanceId = ProviderInstanceId.make("codex_personal");
|
||||
const workInstanceId = ProviderInstanceId.make("codex_work");
|
||||
const refreshedInstanceIds: Array<ProviderInstanceId> = [];
|
||||
const { registry } = yield* makeRegistry([
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: personalInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: workInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex-instance-test",
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", "@openai/codex"],
|
||||
updateLockKey: "vite-plus-global",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => assert.strictEqual(instanceId, personalInstanceId))),
|
||||
),
|
||||
refreshInstance: (instanceId) =>
|
||||
registry.refreshInstance(instanceId).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
refreshedInstanceIds.push(instanceId);
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider({
|
||||
provider: CODEX_DRIVER,
|
||||
instanceId: personalInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "vp",
|
||||
args: ["i", "-g", "@openai/codex"],
|
||||
},
|
||||
]);
|
||||
assert.deepStrictEqual(refreshedInstanceIds, [personalInstanceId]);
|
||||
assert.strictEqual(result.providers[0]?.instanceId, personalInstanceId);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.strictEqual(result.providers[1]?.instanceId, workInstanceId);
|
||||
assert.strictEqual(result.providers[1]?.updateState, undefined);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.124.0-alpha.3"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("records command failure output in provider update state", () =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
const updateState = result.providers[0]?.updateState;
|
||||
|
||||
assert.strictEqual(updateState?.status, "failed");
|
||||
assert.strictEqual(updateState?.message, "Update command exited with code 1.");
|
||||
assert.include(updateState?.output ?? "", "permission denied");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stderr: "permission denied", code: 1 })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks successful commands as unchanged when the refreshed provider is still outdated",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
installed: true,
|
||||
version: "0.1.0",
|
||||
});
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged");
|
||||
assert.include(result.providers[0]?.updateState?.message ?? "", "still detects");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("9.9.9"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("prevents concurrent updates for the same provider", () => {
|
||||
const startedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const started = new Promise<void>((resolve) => {
|
||||
startedLatch.resolve = resolve;
|
||||
});
|
||||
const release = new Promise<void>((resolve) => {
|
||||
releaseLatch.resolve = resolve;
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => started);
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isFailure(second), true);
|
||||
if (Exit.isFailure(second)) {
|
||||
const error = Cause.squash(second.cause);
|
||||
assert.strictEqual(Schema.is(ServerProviderUpdateError)(error), true);
|
||||
if (Schema.is(ServerProviderUpdateError)(error)) {
|
||||
assert.include(error.reason, "already running");
|
||||
}
|
||||
}
|
||||
|
||||
releaseLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => {
|
||||
startedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => release).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("serializes different providers that share the same update lock key", () => {
|
||||
const firstStartedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseFirstLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const firstStarted = new Promise<void>((resolve) => {
|
||||
firstStartedLatch.resolve = resolve;
|
||||
});
|
||||
const releaseFirst = new Promise<void>((resolve) => {
|
||||
releaseFirstLatch.resolve = resolve;
|
||||
});
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry([baseProvider, baseOpenCodeProvider]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => firstStarted);
|
||||
|
||||
const second = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped);
|
||||
let providersWhileQueued: ReadonlyArray<ServerProvider> = [];
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
providersWhileQueued = yield* registry.getProviders;
|
||||
const queuedStatus = providersWhileQueued.find(
|
||||
(provider) => provider.instanceId === OPENCODE_INSTANCE_ID,
|
||||
)?.updateState?.status;
|
||||
if (queuedStatus === "queued") {
|
||||
break;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
assert.strictEqual(
|
||||
providersWhileQueued.find((provider) => provider.instanceId === OPENCODE_INSTANCE_ID)
|
||||
?.updateState?.status,
|
||||
"queued",
|
||||
);
|
||||
|
||||
releaseFirstLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
assert.deepStrictEqual(calls, [
|
||||
"install -g @openai/codex@latest",
|
||||
"install -g opencode-ai@latest",
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
if (calls.length === 1) {
|
||||
firstStartedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => releaseFirst).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts arbitrary driver-provided update lock keys", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "unknown-lock-key",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"releases the running-provider marker when interrupted after queuing but before the lock run starts",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
let blockQueuedState = true;
|
||||
const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const queuedStateWritten = new Promise<void>((resolve) => {
|
||||
queuedStateWrittenLatch.resolve = resolve;
|
||||
});
|
||||
const releaseQueuedState = new Promise<void>((resolve) => {
|
||||
releaseQueuedStateLatch.resolve = resolve;
|
||||
});
|
||||
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
setProviderMaintenanceActionState: Effect.fn(
|
||||
"providerMaintenanceRunner.test.blockQueuedState",
|
||||
)(function* (input) {
|
||||
const providers = yield* registry.setProviderMaintenanceActionState(input);
|
||||
if (input.state?.status === "queued" && blockQueuedState) {
|
||||
queuedStateWrittenLatch.resolve();
|
||||
yield* Effect.promise(() => releaseQueuedState);
|
||||
}
|
||||
return providers;
|
||||
}),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => queuedStateWritten);
|
||||
blockQueuedState = false;
|
||||
|
||||
yield* Fiber.interrupt(first);
|
||||
releaseQueuedStateLatch.resolve();
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isSuccess(second), true);
|
||||
if (Exit.isSuccess(second)) {
|
||||
assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,395 +0,0 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ServerProviderUpdateError,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdatedPayload,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Context, DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
|
||||
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
const UPDATE_TIMEOUT_MS = 5 * 60_000;
|
||||
const UPDATE_OUTPUT_MAX_BYTES = 10_000;
|
||||
|
||||
export interface ProviderMaintenanceCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number | null;
|
||||
readonly timedOut: boolean;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceRunnerShape {
|
||||
readonly updateProvider: (
|
||||
target:
|
||||
| ProviderDriverKind
|
||||
| {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId?: ProviderInstanceId | undefined;
|
||||
},
|
||||
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
|
||||
}
|
||||
|
||||
export class ProviderMaintenanceRunner extends Context.Service<
|
||||
ProviderMaintenanceRunner,
|
||||
ProviderMaintenanceRunnerShape
|
||||
>()("t3/provider/ProviderMaintenanceRunner") {}
|
||||
|
||||
interface VerifiedProviderRefresh {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly verifiedProviders: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
|
||||
function* (input: {
|
||||
readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
|
||||
function* () {
|
||||
const child = yield* input.spawner
|
||||
.spawn(ChildProcess.make(input.command, [...input.args]))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(`Failed to run update command ${input.command}: ${cause.message}`),
|
||||
),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(cause instanceof Error ? cause.message : "Update command failed to run."),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
exitCode: Number(exitCode),
|
||||
timedOut: false,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProviderMaintenanceCommandResult;
|
||||
},
|
||||
);
|
||||
|
||||
return yield* collectCommandResult().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
|
||||
Effect.map((result) =>
|
||||
Option.match(result, {
|
||||
onSome: (value) => value,
|
||||
onNone: () =>
|
||||
({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: null,
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}) satisfies ProviderMaintenanceCommandResult,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
function trimNullable(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function truncateText(value: string, maxLength: number): string {
|
||||
return value.length <= maxLength ? value : value.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
|
||||
const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
|
||||
if (!output) {
|
||||
return null;
|
||||
}
|
||||
return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
|
||||
}
|
||||
|
||||
function failureMessage(result: ProviderMaintenanceCommandResult): string {
|
||||
if (result.timedOut) {
|
||||
return "Update timed out.";
|
||||
}
|
||||
if (result.exitCode !== null && result.exitCode !== 0) {
|
||||
return `Update command exited with code ${result.exitCode}.`;
|
||||
}
|
||||
return "Update command failed.";
|
||||
}
|
||||
|
||||
function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
|
||||
return provider?.versionAdvisory?.status === "behind_latest";
|
||||
}
|
||||
|
||||
function makeUpdateState(input: {
|
||||
readonly status: ServerProviderUpdateState["status"];
|
||||
readonly startedAt: string | null;
|
||||
readonly finishedAt: string | null;
|
||||
readonly message: string | null;
|
||||
readonly output?: string | null;
|
||||
}): ServerProviderUpdateState {
|
||||
return {
|
||||
status: input.status,
|
||||
startedAt: input.startedAt,
|
||||
finishedAt: input.finishedAt,
|
||||
message: input.message,
|
||||
output: input.output ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
|
||||
runProviderMaintenanceCommandWithSpawner({
|
||||
spawner,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
|
||||
makeAlreadyRunningError: () =>
|
||||
new ServerProviderUpdateError({
|
||||
provider: ProviderDriverKind.make("unknown"),
|
||||
reason: "An update is already running for this provider.",
|
||||
}),
|
||||
});
|
||||
|
||||
const verifyRefreshedProvider = (
|
||||
provider: ProviderDriverKind,
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<VerifiedProviderRefresh> =>
|
||||
providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) =>
|
||||
providers
|
||||
.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
)
|
||||
.map((candidate) => candidate.instanceId),
|
||||
),
|
||||
Effect.flatMap((instanceIds) =>
|
||||
instanceIds.length === 0
|
||||
? providerRegistry.refreshInstance(instanceId)
|
||||
: Effect.forEach(
|
||||
instanceIds,
|
||||
(instanceId) => providerRegistry.refreshInstance(instanceId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(providerRegistry.getProviders)),
|
||||
),
|
||||
Effect.flatMap((providers) => {
|
||||
const refreshedProviders = providers.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
);
|
||||
if (refreshedProviders.length === 0) {
|
||||
return Effect.succeed<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: [],
|
||||
});
|
||||
}
|
||||
return Effect.forEach(
|
||||
refreshedProviders,
|
||||
(refreshedProvider) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(
|
||||
refreshedProvider,
|
||||
maintenanceCapabilities,
|
||||
).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(
|
||||
Effect.map(
|
||||
(verifiedProviders): VerifiedProviderRefresh => ({
|
||||
providers,
|
||||
verifiedProviders,
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Provider post-update version verification failed", {
|
||||
provider,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(
|
||||
Effect.as<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: refreshedProviders,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
|
||||
"ProviderMaintenanceRunner.updateProvider",
|
||||
)(function* (target) {
|
||||
const provider = typeof target === "string" ? target : target.provider;
|
||||
const instanceId =
|
||||
typeof target === "string"
|
||||
? defaultInstanceIdForDriver(provider)
|
||||
: (target.instanceId ?? defaultInstanceIdForDriver(provider));
|
||||
const targetKey = `instance:${instanceId}`;
|
||||
const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
);
|
||||
const update = capabilities.update;
|
||||
if (!update) {
|
||||
return yield* new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: "This provider does not support one-click updates.",
|
||||
});
|
||||
}
|
||||
|
||||
const setUpdateState = (state: ServerProviderUpdateState | null) =>
|
||||
providerRegistry.setProviderMaintenanceActionState({
|
||||
instanceId,
|
||||
action: "update",
|
||||
state,
|
||||
});
|
||||
const setQueuedState = setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
message: "Waiting for another provider update to finish.",
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
|
||||
function* () {
|
||||
const finish = (state: ServerProviderUpdateState) =>
|
||||
setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
|
||||
const startedAtRef = yield* Ref.make<string | null>(null);
|
||||
|
||||
const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
|
||||
function* () {
|
||||
const startedAt = yield* nowIso;
|
||||
yield* Ref.set(startedAtRef, startedAt);
|
||||
yield* setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "running",
|
||||
startedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* runMaintenanceCommand(update.executable, update.args);
|
||||
const finishedAt = yield* nowIso;
|
||||
if (result.timedOut || result.exitCode !== 0) {
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: failureMessage(result),
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const { verifiedProviders } = yield* verifyRefreshedProvider(
|
||||
provider,
|
||||
capabilities,
|
||||
instanceId,
|
||||
);
|
||||
const couldNotVerify = verifiedProviders.length === 0;
|
||||
const stillOutdated =
|
||||
couldNotVerify ||
|
||||
verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: stillOutdated ? "unchanged" : "succeeded",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: couldNotVerify
|
||||
? "Update command completed, but T3 Code could not verify the provider version."
|
||||
: stillOutdated
|
||||
? "Update command completed, but T3 Code still detects an outdated provider version."
|
||||
: "Provider updated.",
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
|
||||
function* (cause: Cause.Cause<unknown>) {
|
||||
const failure = Cause.squash(cause);
|
||||
const startedAt = yield* Ref.get(startedAtRef);
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt: yield* nowIso,
|
||||
message: failure instanceof Error ? failure.message : "Update command failed.",
|
||||
output: null,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
|
||||
},
|
||||
);
|
||||
|
||||
return yield* commandCoordinator
|
||||
.withCommandLock({
|
||||
targetKey,
|
||||
lockKey: update.lockKey,
|
||||
onQueued: setQueuedState,
|
||||
run: runProviderUpdate(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(ServerProviderUpdateError)(error)
|
||||
? new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: error.reason,
|
||||
})
|
||||
: error,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return ProviderMaintenanceRunner.of({
|
||||
updateProvider,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderMaintenanceRunner, make());
|
||||
@@ -12,8 +12,6 @@ import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
|
||||
@@ -184,7 +182,6 @@ export function buildBooleanOptionDescriptor(input: {
|
||||
}
|
||||
|
||||
export function buildServerProvider(input: {
|
||||
driver?: ProviderDriverKind;
|
||||
presentation: ServerProviderPresentation;
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
@@ -193,13 +190,6 @@ export function buildServerProvider(input: {
|
||||
skills?: ReadonlyArray<ServerProviderSkill>;
|
||||
probe: ProviderProbeResult;
|
||||
}): ServerProviderDraft {
|
||||
const versionAdvisory = input.driver
|
||||
? createProviderVersionAdvisory({
|
||||
driver: input.driver,
|
||||
currentVersion: input.probe.version,
|
||||
checkedAt: input.checkedAt,
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
@@ -216,11 +206,16 @@ export function buildServerProvider(input: {
|
||||
models: input.models,
|
||||
slashCommands: [...(input.slashCommands ?? [])],
|
||||
skills: [...(input.skills ?? [])],
|
||||
...(versionAdvisory ? { versionAdvisory } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const collectStreamAsString = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, E> =>
|
||||
collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
);
|
||||
@@ -140,10 +140,8 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) => {
|
||||
const { updateState: _updateState, ...cacheableProvider } = input.provider;
|
||||
return writeFileStringAtomically({
|
||||
}) =>
|
||||
writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
|
||||
contents: `${JSON.stringify(input.provider, null, 2)}\n`,
|
||||
});
|
||||
};
|
||||
+39
-116
@@ -75,12 +75,10 @@ import {
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import { PersistenceSqlError } from "./persistence/Errors.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "./provider/Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
|
||||
@@ -106,12 +104,18 @@ import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriver from "./vcs/VcsDriver.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import type { VcsDriverShape } from "./vcs/VcsDriver.ts";
|
||||
import {
|
||||
VcsStatusBroadcaster,
|
||||
type VcsStatusBroadcasterShape,
|
||||
layer as VcsStatusBroadcasterLayer,
|
||||
} from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import {
|
||||
VcsDriverRegistry,
|
||||
type VcsDriverRegistryShape,
|
||||
type VcsDriverHandle,
|
||||
} from "./vcs/VcsDriverRegistry.ts";
|
||||
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
|
||||
@@ -208,8 +212,10 @@ const browserOtlpTracingLayer = Layer.mergeAll(
|
||||
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
|
||||
);
|
||||
|
||||
const makeAuthTestLayer = () =>
|
||||
ServerAuthLive.pipe(Layer.provide(SqlitePersistenceMemory), Layer.provide(ServerSecretStoreLive));
|
||||
const authTestLayer = ServerAuthLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
);
|
||||
|
||||
const makeBrowserOtlpPayload = (spanName: string) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -319,12 +325,11 @@ const buildAppUnderTest = (options?: {
|
||||
providerRegistry?: Partial<ProviderRegistryShape>;
|
||||
serverSettings?: Partial<ServerSettingsShape>;
|
||||
open?: Partial<OpenShape>;
|
||||
vcsDriver?: Partial<VcsDriver.VcsDriverShape>;
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>;
|
||||
vcsDriver?: Partial<VcsDriverShape>;
|
||||
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
|
||||
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
gitManager?: Partial<GitManagerShape>;
|
||||
sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
|
||||
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
|
||||
terminalManager?: Partial<TerminalManagerShape>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngineShape>;
|
||||
@@ -367,12 +372,10 @@ const buildAppUnderTest = (options?: {
|
||||
desktopBootstrapToken: defaultDesktopBootstrapToken,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
...options?.config,
|
||||
};
|
||||
const layerConfig = Layer.succeed(ServerConfig, config);
|
||||
const defaultVcsDriver: VcsDriver.VcsDriverShape = {
|
||||
const defaultVcsDriver: VcsDriverShape = {
|
||||
capabilities: {
|
||||
kind: "git",
|
||||
supportsWorktrees: true,
|
||||
@@ -411,11 +414,9 @@ const buildAppUnderTest = (options?: {
|
||||
},
|
||||
}),
|
||||
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
|
||||
initRepository: () => Effect.void,
|
||||
...options?.layers?.vcsDriver,
|
||||
};
|
||||
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
get: () => Effect.succeed(defaultVcsDriver),
|
||||
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry)({
|
||||
detect: (input) =>
|
||||
defaultVcsDriver.detectRepository(input.cwd).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
@@ -444,7 +445,7 @@ const buildAppUnderTest = (options?: {
|
||||
kind: repository.kind,
|
||||
repository,
|
||||
driver: defaultVcsDriver,
|
||||
} satisfies VcsDriverRegistry.VcsDriverHandle)
|
||||
} satisfies VcsDriverHandle)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
@@ -486,19 +487,16 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
ProjectFaviconResolverLive,
|
||||
);
|
||||
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
|
||||
const gitWorkflowLayer = GitWorkflowServiceLayer.pipe(
|
||||
Layer.provideMerge(vcsDriverRegistryLayer),
|
||||
Layer.provideMerge(gitVcsDriverLayer),
|
||||
Layer.provideMerge(gitManagerLayer),
|
||||
);
|
||||
const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
|
||||
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
|
||||
? Layer.mock(VcsStatusBroadcaster)({
|
||||
...options.layers.vcsStatusBroadcaster,
|
||||
})
|
||||
: VcsStatusBroadcaster.layer.pipe(Layer.provide(gitWorkflowLayer));
|
||||
: VcsStatusBroadcasterLayer.pipe(Layer.provide(gitWorkflowLayer));
|
||||
|
||||
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
|
||||
disableListenLog: true,
|
||||
@@ -518,12 +516,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
refresh: () => Effect.succeed([]),
|
||||
refreshInstance: () => Effect.succeed([]),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }),
|
||||
),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.providerRegistry,
|
||||
}),
|
||||
@@ -546,12 +538,6 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
|
||||
...options?.layers?.sourceControlRepositoryService,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectSetupScriptRunner)({
|
||||
@@ -566,6 +552,7 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(OrchestrationEngineService)({
|
||||
getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 0 }),
|
||||
streamDomainEvents: Stream.empty,
|
||||
@@ -574,7 +561,6 @@ const buildAppUnderTest = (options?: {
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getCommandReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
@@ -583,7 +569,6 @@ const buildAppUnderTest = (options?: {
|
||||
threads: [],
|
||||
updatedAt: new Date(0).toISOString(),
|
||||
}),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
@@ -651,7 +636,7 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.repositoryIdentityResolver,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeAuthTestLayer()),
|
||||
Layer.provideMerge(authTestLayer),
|
||||
Layer.provide(workspaceAndProjectServicesLayer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(layerConfig),
|
||||
@@ -1918,42 +1903,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc server.removeKeybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const rule: KeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
};
|
||||
const resolved: ResolvedKeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
keybindings: {
|
||||
removeKeybindingRule: () => Effect.succeed([resolved]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)),
|
||||
);
|
||||
|
||||
assert.deepEqual(response.issues, []);
|
||||
assert.deepEqual(response.keybindings, [resolved]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -2055,7 +2004,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.deepEqual(second, {
|
||||
version: 1,
|
||||
type: "keybindingsUpdated",
|
||||
payload: { keybindings: [], issues: [] },
|
||||
payload: { issues: [] },
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
@@ -2424,6 +2373,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2440,6 +2390,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
status: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2552,9 +2503,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
removeWorktree: () => Effect.void,
|
||||
createRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
switchRef: (input) => Effect.succeed({ refName: input.refName }),
|
||||
},
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
initRepo: () => Effect.void,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -2696,6 +2645,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2717,6 +2667,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2773,6 +2724,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -2794,6 +2746,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
statusCalls += 1;
|
||||
return {
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -2845,6 +2798,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
@@ -2882,15 +2836,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
localStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git",
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -2958,9 +2910,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
vcsDriver: {
|
||||
isInsideWorkTree: () => Effect.succeed(true),
|
||||
},
|
||||
gitManager: {
|
||||
invalidateLocalStatus: () => Effect.void,
|
||||
invalidateRemoteStatus: () => Effect.void,
|
||||
@@ -2970,6 +2919,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.andThen(
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "feature/demo",
|
||||
@@ -3144,34 +3094,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc orchestration shell snapshot errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionError = new PersistenceSqlError({
|
||||
operation: "ProjectionSnapshotQuery.getShellSnapshot:test",
|
||||
detail: "failed to read projection shell snapshot",
|
||||
});
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
projectionSnapshotQuery: {
|
||||
getShellSnapshot: () => Effect.fail(projectionError),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(Stream.runCollect),
|
||||
).pipe(Effect.result),
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
|
||||
assertTrue(result.failure.cause instanceof Error);
|
||||
assert.include(result.failure.cause.message, projectionError.message);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("enriches replayed project events with repository identity metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const repositoryIdentity = {
|
||||
@@ -3664,6 +3586,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const refreshStatus = vi.fn((_: string) =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
kind: "git" as const,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: "t3code/bootstrap-refName",
|
||||
|
||||
@@ -25,10 +25,7 @@ import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReap
|
||||
import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
|
||||
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
|
||||
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
|
||||
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
|
||||
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
|
||||
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
|
||||
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
|
||||
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
|
||||
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
|
||||
@@ -52,11 +49,9 @@ import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
|
||||
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
|
||||
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
|
||||
@@ -85,7 +80,6 @@ import {
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http.ts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -165,18 +159,15 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProjectConfig.layer),
|
||||
);
|
||||
|
||||
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
|
||||
),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
);
|
||||
|
||||
const GitManagerLayerLive = GitManager.layer.pipe(
|
||||
Layer.provideMerge(ProjectSetupScriptRunnerLive),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(
|
||||
SourceControlProviderRegistry.layer.pipe(
|
||||
Layer.provide(GitHubCli.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(TextGeneration.layer),
|
||||
);
|
||||
|
||||
@@ -190,17 +181,10 @@ const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
);
|
||||
|
||||
const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
Layer.provideMerge(GitWorkflowLayerLive),
|
||||
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
|
||||
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
|
||||
);
|
||||
|
||||
@@ -240,7 +224,6 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
|
||||
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(VcsLayerLive),
|
||||
Layer.provideMerge(ProviderRuntimeLayerLive),
|
||||
@@ -341,57 +324,6 @@ export const makeServerLayer = Layer.unwrap(
|
||||
() => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
|
||||
),
|
||||
);
|
||||
const tailscaleServeLayer = config.tailscaleServeEnabled
|
||||
? Layer.effectDiscard(
|
||||
Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* HttpServer.HttpServer;
|
||||
const address = server.address;
|
||||
if (typeof address === "string" || !("port" in address)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const localPort = address.port;
|
||||
return yield* ensureTailscaleServe({
|
||||
localPort,
|
||||
servePort: config.tailscaleServePort,
|
||||
localHost: "127.0.0.1",
|
||||
}).pipe(
|
||||
Effect.as({ localPort, servePort: config.tailscaleServePort }),
|
||||
Effect.tap(() =>
|
||||
Effect.logInfo("Tailscale Serve configured", {
|
||||
localPort,
|
||||
servePort: config.tailscaleServePort,
|
||||
}),
|
||||
),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to configure Tailscale Serve", {
|
||||
cause,
|
||||
localPort,
|
||||
servePort: config.tailscaleServePort,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
(configured) =>
|
||||
configured
|
||||
? disableTailscaleServe({ servePort: configured.servePort }).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.logInfo("Tailscale Serve disabled", {
|
||||
servePort: configured.servePort,
|
||||
}),
|
||||
),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Failed to disable Tailscale Serve", {
|
||||
cause,
|
||||
servePort: configured.servePort,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
)
|
||||
: Layer.empty;
|
||||
|
||||
const serverApplicationLayer = Layer.mergeAll(
|
||||
HttpRouter.serve(makeRoutesLayer, {
|
||||
@@ -399,7 +331,6 @@ export const makeServerLayer = Layer.unwrap(
|
||||
}),
|
||||
httpListeningLayer,
|
||||
runtimeStateLayer,
|
||||
tailscaleServeLayer,
|
||||
);
|
||||
|
||||
return serverApplicationLayer.pipe(
|
||||
|
||||
@@ -77,10 +77,8 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
|
||||
|
||||
yield* launchStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () =>
|
||||
Deferred.await(releaseCounts).pipe(
|
||||
Effect.as({
|
||||
@@ -131,10 +129,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () =>
|
||||
Effect.succeed(
|
||||
@@ -156,6 +152,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
@@ -183,10 +180,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
@@ -196,6 +191,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
getReadModel: () => Effect.die("unused"),
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
|
||||
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const mockRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
|
||||
|
||||
const supportLayer = Layer.mergeAll(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: mockRun,
|
||||
}),
|
||||
NodeServices.layer,
|
||||
);
|
||||
const layer = Layer.mergeAll(AzureDevOpsCli.layer.pipe(Layer.provide(supportLayer)), supportLayer);
|
||||
|
||||
afterEach(() => {
|
||||
mockRun.mockReset();
|
||||
});
|
||||
|
||||
describe("AzureDevOpsCli.layer", () => {
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
pullRequestId: 42,
|
||||
title: "Add Azure provider",
|
||||
sourceRefName: "refs/heads/feature/source-control",
|
||||
targetRefName: "refs/heads/main",
|
||||
status: "active",
|
||||
creationDate: "2026-01-02T00:00:00.000Z",
|
||||
closedDate: null,
|
||||
_links: {
|
||||
web: {
|
||||
href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const result = yield* az.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
|
||||
assert.strictEqual(result.number, 42);
|
||||
assert.strictEqual(result.title, "Add Azure provider");
|
||||
assert.strictEqual(result.baseRefName, "main");
|
||||
assert.strictEqual(result.headRefName, "feature/source-control");
|
||||
assert.strictEqual(result.state, "open");
|
||||
assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
|
||||
assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0], {
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"show",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
"42",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("lists pull requests with Azure status and source branch arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify([
|
||||
{
|
||||
pullRequestId: 7,
|
||||
title: "Merged work",
|
||||
sourceRefName: "refs/heads/feature/merged",
|
||||
targetRefName: "refs/heads/main",
|
||||
status: "completed",
|
||||
closedDate: "2026-01-03T00:00:00.000Z",
|
||||
_links: {
|
||||
web: {
|
||||
href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/7",
|
||||
},
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const result = yield* az.listPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "origin:feature/merged",
|
||||
state: "merged",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.strictEqual(result[0]?.state, "merged");
|
||||
expect(mockRun).toHaveBeenCalledWith({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"list",
|
||||
"--detect",
|
||||
"true",
|
||||
"--source-branch",
|
||||
"feature/merged",
|
||||
"--status",
|
||||
"completed",
|
||||
"--top",
|
||||
"10",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
name: "repo",
|
||||
webUrl: "https://dev.azure.com/acme/project/_git/repo",
|
||||
remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
|
||||
sshUrl: "[email protected]:v3/acme/project/repo",
|
||||
project: {
|
||||
name: "project",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const result = yield* az.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "repo",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "project/repo",
|
||||
url: "https://dev.azure.com/acme/project/_git/repo",
|
||||
sshUrl: "[email protected]:v3/acme/project/repo",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("creates repositories through Azure Repos", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
name: "repo",
|
||||
webUrl: "https://dev.azure.com/acme/project/_git/repo",
|
||||
remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
|
||||
sshUrl: "[email protected]:v3/acme/project/repo",
|
||||
project: {
|
||||
name: "project",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const result = yield* az.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "project/repo",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "project/repo",
|
||||
url: "https://dev.azure.com/acme/project/_git/repo",
|
||||
sshUrl: "[email protected]:v3/acme/project/repo",
|
||||
});
|
||||
expect(mockRun).toHaveBeenCalledWith({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
args: [
|
||||
"repos",
|
||||
"create",
|
||||
"--detect",
|
||||
"true",
|
||||
"--name",
|
||||
"repo",
|
||||
"--project",
|
||||
"project",
|
||||
"--only-show-errors",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("creates pull requests using the body file as the Azure description", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const bodyFile = `/tmp/t3code-azure-devops-cli-${Date.now()}.md`;
|
||||
yield* fileSystem.writeFileString(bodyFile, "Generated body");
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
yield* az.createPullRequest({
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile,
|
||||
});
|
||||
|
||||
expect(mockRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
args: expect.arrayContaining(["--description", `@${bodyFile}`]),
|
||||
}),
|
||||
);
|
||||
expect(mockRun.mock.calls[0]?.[0].args).not.toContain("--output");
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("does not force JSON output on checkout side-effect commands", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
yield* az.checkoutPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
expect(mockRun).toHaveBeenCalledWith({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"checkout",
|
||||
"--only-show-errors",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
"42",
|
||||
"--remote-name",
|
||||
"origin",
|
||||
],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,429 +0,0 @@
|
||||
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsPullRequests from "./azureDevOpsPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
|
||||
"AzureDevOpsCliError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface AzureDevOpsRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
export interface AzureDevOpsCliShape {
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<VcsProcess.VcsProcessOutput, AzureDevOpsCliError>;
|
||||
|
||||
readonly listPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly state: "open" | "closed" | "merged" | "all";
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<
|
||||
ReadonlyArray<AzureDevOpsPullRequests.NormalizedAzureDevOpsPullRequestRecord>,
|
||||
AzureDevOpsCliError
|
||||
>;
|
||||
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<
|
||||
AzureDevOpsPullRequests.NormalizedAzureDevOpsPullRequestRecord,
|
||||
AzureDevOpsCliError
|
||||
>;
|
||||
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
|
||||
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly target?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, AzureDevOpsCliError>;
|
||||
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, AzureDevOpsCliError>;
|
||||
|
||||
readonly checkoutPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly remoteName?: string;
|
||||
}) => Effect.Effect<void, AzureDevOpsCliError>;
|
||||
}
|
||||
|
||||
export class AzureDevOpsCli extends Context.Service<AzureDevOpsCli, AzureDevOpsCliShape>()(
|
||||
"t3/source-control/AzureDevOpsCli",
|
||||
) {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeAzureDevOpsCliError(
|
||||
operation: "execute",
|
||||
error: VcsError | unknown,
|
||||
): AzureDevOpsCliError {
|
||||
const text = errorText(error);
|
||||
const lower = text.toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: az") || lower.includes("enoent")) {
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail:
|
||||
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("pull request") &&
|
||||
(lower.includes("not found") || lower.includes("does not exist"))
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: text,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeChangeRequestId(reference: string): string {
|
||||
const trimmed = reference.trim().replace(/^#/, "");
|
||||
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
|
||||
return urlMatch?.[1] ?? trimmed;
|
||||
}
|
||||
|
||||
function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return "active";
|
||||
case "closed":
|
||||
return "abandoned";
|
||||
case "merged":
|
||||
return "completed";
|
||||
case "all":
|
||||
return "all";
|
||||
}
|
||||
}
|
||||
|
||||
const RawAzureDevOpsRepositorySchema = Schema.Struct({
|
||||
name: TrimmedNonEmptyString,
|
||||
webUrl: TrimmedNonEmptyString,
|
||||
remoteUrl: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
project: Schema.optional(
|
||||
Schema.Struct({
|
||||
name: TrimmedNonEmptyString,
|
||||
}),
|
||||
),
|
||||
defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
function normalizeDefaultBranch(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
|
||||
): AzureDevOpsRepositoryCloneUrls {
|
||||
const projectName = raw.project?.name.trim();
|
||||
return {
|
||||
nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
|
||||
url: raw.remoteUrl,
|
||||
sshUrl: raw.sshUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function parseRepositorySpecifier(repository: string): {
|
||||
readonly project: string | null;
|
||||
readonly name: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
return {
|
||||
project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
|
||||
name: parts.at(-1) ?? repository.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeAzureDevOpsJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new AzureDevOpsCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeAzureDevOpsCli")(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const execute: AzureDevOpsCliShape["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeAzureDevOpsCliError("execute", error)));
|
||||
|
||||
const executeJson = (input: Parameters<AzureDevOpsCliShape["execute"]>[0]) =>
|
||||
execute({
|
||||
...input,
|
||||
args: [...input.args, "--only-show-errors", "--output", "json"],
|
||||
});
|
||||
|
||||
return AzureDevOpsCli.of({
|
||||
execute,
|
||||
listPullRequests: (input) =>
|
||||
executeJson({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"list",
|
||||
"--detect",
|
||||
"true",
|
||||
"--source-branch",
|
||||
SourceControlProvider.sourceBranch(input),
|
||||
"--status",
|
||||
toAzureStatus(input.state),
|
||||
"--top",
|
||||
String(input.limit ?? 20),
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: Effect.sync(() =>
|
||||
AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestListJson(raw),
|
||||
).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
operation: "listPullRequests",
|
||||
detail: `Azure DevOps CLI returned invalid PR list JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
executeJson({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"show",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
normalizeChangeRequestId(input.reference),
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.sync(() => AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `Azure DevOps CLI returned invalid pull request JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
executeJson({
|
||||
cwd: input.cwd,
|
||||
args: ["repos", "show", "--detect", "true", "--repository", input.repository],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) => {
|
||||
const repository = parseRepositorySpecifier(input.repository);
|
||||
// Azure Repos access is governed by project/organization permissions.
|
||||
// `az repos create` does not expose a per-repository visibility flag, so
|
||||
// the generic source-control visibility input is intentionally not
|
||||
// translated into CLI args for this provider.
|
||||
return executeJson({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"create",
|
||||
"--detect",
|
||||
"true",
|
||||
"--name",
|
||||
repository.name,
|
||||
...(repository.project ? ["--project", repository.project] : []),
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"createRepository",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
},
|
||||
createPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"create",
|
||||
"--only-show-errors",
|
||||
"--detect",
|
||||
"true",
|
||||
"--target-branch",
|
||||
input.target?.refName ?? input.baseBranch,
|
||||
"--source-branch",
|
||||
SourceControlProvider.sourceBranch(input),
|
||||
"--title",
|
||||
input.title,
|
||||
"--description",
|
||||
`@${input.bodyFile}`,
|
||||
],
|
||||
}).pipe(Effect.asVoid),
|
||||
getDefaultBranch: (input) =>
|
||||
executeJson({
|
||||
cwd: input.cwd,
|
||||
args: ["repos", "show", "--detect", "true"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getDefaultBranch",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"repos",
|
||||
"pr",
|
||||
"checkout",
|
||||
"--only-show-errors",
|
||||
"--detect",
|
||||
"true",
|
||||
"--id",
|
||||
normalizeChangeRequestId(input.reference),
|
||||
"--remote-name",
|
||||
input.remoteName ?? "origin",
|
||||
],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(AzureDevOpsCli, make());
|
||||
@@ -1,91 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
|
||||
|
||||
function makeProvider(azure: Partial<AzureDevOpsCli.AzureDevOpsCliShape>) {
|
||||
return AzureDevOpsSourceControlProvider.make().pipe(
|
||||
Effect.provide(Layer.mock(AzureDevOpsCli.AzureDevOpsCli)(azure)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("maps Azure DevOps PR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
getPullRequest: () =>
|
||||
Effect.succeed({
|
||||
number: 42,
|
||||
title: "Add Azure provider",
|
||||
url: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
}),
|
||||
});
|
||||
|
||||
const changeRequest = yield* provider.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequest, {
|
||||
provider: "azure-devops",
|
||||
number: 42,
|
||||
title: "Add Azure provider",
|
||||
url: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates Azure DevOps PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<AzureDevOpsCli.AzureDevOpsCliShape["createPullRequest"]>[0] | null =
|
||||
null;
|
||||
const provider = yield* makeProvider({
|
||||
createPullRequest: (input) => {
|
||||
createInput = input;
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.createChangeRequest({
|
||||
cwd: "/repo",
|
||||
baseRefName: "main",
|
||||
headSelector: "feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(createInput, {
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses Azure CLI repository detection for default branch lookup", () =>
|
||||
Effect.gen(function* () {
|
||||
let cwdInput: string | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
getDefaultBranch: (input) => {
|
||||
cwdInput = input.cwd;
|
||||
return Effect.succeed("main");
|
||||
},
|
||||
});
|
||||
|
||||
const defaultBranch = yield* provider.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
assert.strictEqual(cwdInput, "/repo");
|
||||
}),
|
||||
);
|
||||
@@ -1,144 +0,0 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: AzureDevOpsCli.AzureDevOpsCliError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "azure-devops",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function parseAzureAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
|
||||
const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
|
||||
|
||||
if (input.exitCode !== 0) {
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "unauthenticated",
|
||||
detail:
|
||||
SourceControlProviderDiscovery.firstSafeAuthLine(
|
||||
SourceControlProviderDiscovery.combinedAuthOutput(input),
|
||||
) ?? "Run `az login` to authenticate Azure CLI.",
|
||||
});
|
||||
}
|
||||
|
||||
if (account && account.length > 0) {
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "authenticated",
|
||||
account,
|
||||
host: "dev.azure.com",
|
||||
});
|
||||
}
|
||||
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "unknown",
|
||||
host: "dev.azure.com",
|
||||
detail: "Azure CLI account status could not be parsed.",
|
||||
});
|
||||
}
|
||||
|
||||
export const discovery = {
|
||||
type: "cli",
|
||||
kind: "azure-devops",
|
||||
label: "Azure DevOps",
|
||||
executable: "az",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
|
||||
parseAuth: parseAzureAuth,
|
||||
installHint:
|
||||
"Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.",
|
||||
} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
|
||||
|
||||
function toChangeRequest(summary: {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: ChangeRequest["updatedAt"];
|
||||
}): ChangeRequest {
|
||||
return {
|
||||
provider: "azure-devops",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state,
|
||||
updatedAt: summary.updatedAt,
|
||||
isCrossRepository: false,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeAzureDevOpsSourceControlProvider")(function* () {
|
||||
const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
kind: "azure-devops",
|
||||
listChangeRequests: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
return azure
|
||||
.listPullRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
state: input.state,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
azure.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
return azure
|
||||
.createPullRequest({
|
||||
cwd: input.cwd,
|
||||
baseBranch: input.baseRefName,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
...(input.target ? { target: input.target } : {}),
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
azure
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
azure
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
azure
|
||||
.getDefaultBranch({ cwd: input.cwd })
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
checkoutChangeRequest: (input) =>
|
||||
azure
|
||||
.checkoutPullRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
...(input.context ? { remoteName: input.context.remoteName } : {}),
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
|
||||
@@ -1,604 +0,0 @@
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ConfigProvider, DateTime, Effect, FileSystem, Layer, Option } from "effect";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as BitbucketApi from "./BitbucketApi.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import type * as VcsDriver from "../vcs/VcsDriver.ts";
|
||||
|
||||
const bitbucketPullRequest = {
|
||||
id: 42,
|
||||
title: "Add Bitbucket provider",
|
||||
state: "OPEN",
|
||||
updated_on: "2026-01-02T00:00:00.000Z",
|
||||
links: {
|
||||
html: {
|
||||
href: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
|
||||
},
|
||||
},
|
||||
source: {
|
||||
branch: { name: "feature/source-control" },
|
||||
repository: {
|
||||
full_name: "octocat/t3code",
|
||||
workspace: { slug: "octocat" },
|
||||
},
|
||||
},
|
||||
destination: {
|
||||
branch: { name: "main" },
|
||||
repository: {
|
||||
full_name: "pingdotgg/t3code",
|
||||
workspace: { slug: "pingdotgg" },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const repositoryJson = {
|
||||
full_name: "pingdotgg/t3code",
|
||||
links: {
|
||||
html: { href: "https://bitbucket.org/pingdotgg/t3code" },
|
||||
clone: [
|
||||
{ name: "https", href: "https://bitbucket.org/pingdotgg/t3code.git" },
|
||||
{ name: "ssh", href: "[email protected]:pingdotgg/t3code.git" },
|
||||
],
|
||||
},
|
||||
mainbranch: { name: "main" },
|
||||
};
|
||||
|
||||
function makeLayer(input: {
|
||||
readonly response: (request: HttpClientRequest.HttpClientRequest) => Response;
|
||||
readonly git?: Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
}) {
|
||||
const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, input.response(request))),
|
||||
);
|
||||
const gitMock = {
|
||||
readConfigValue: vi.fn<GitVcsDriver.GitVcsDriverShape["readConfigValue"]>(() =>
|
||||
Effect.succeed<string | null>("[email protected]:pingdotgg/t3code.git"),
|
||||
),
|
||||
resolvePrimaryRemoteName: vi.fn<GitVcsDriver.GitVcsDriverShape["resolvePrimaryRemoteName"]>(
|
||||
() => Effect.succeed("origin"),
|
||||
),
|
||||
ensureRemote: vi.fn<GitVcsDriver.GitVcsDriverShape["ensureRemote"]>(() =>
|
||||
Effect.succeed("octocat"),
|
||||
),
|
||||
fetchRemoteBranch: vi.fn<GitVcsDriver.GitVcsDriverShape["fetchRemoteBranch"]>(
|
||||
() => Effect.void,
|
||||
),
|
||||
fetchRemoteTrackingBranch: vi.fn<GitVcsDriver.GitVcsDriverShape["fetchRemoteTrackingBranch"]>(
|
||||
() => Effect.void,
|
||||
),
|
||||
setBranchUpstream: vi.fn<GitVcsDriver.GitVcsDriverShape["setBranchUpstream"]>(
|
||||
() => Effect.void,
|
||||
),
|
||||
switchRef: vi.fn<GitVcsDriver.GitVcsDriverShape["switchRef"]>((request) =>
|
||||
Effect.succeed({ refName: request.refName }),
|
||||
),
|
||||
listLocalBranchNames: vi.fn<GitVcsDriver.GitVcsDriverShape["listLocalBranchNames"]>(() =>
|
||||
Effect.succeed([]),
|
||||
),
|
||||
};
|
||||
const git = {
|
||||
...gitMock,
|
||||
...input.git,
|
||||
} satisfies Partial<GitVcsDriver.GitVcsDriverShape>;
|
||||
|
||||
const driver = {
|
||||
listRemotes: () =>
|
||||
Effect.succeed({
|
||||
remotes: [
|
||||
{
|
||||
name: "origin",
|
||||
url: "[email protected]:pingdotgg/t3code.git",
|
||||
pushUrl: Option.none(),
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
}),
|
||||
} satisfies Partial<VcsDriver.VcsDriverShape>;
|
||||
|
||||
const layer = BitbucketApi.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) => execute(request)),
|
||||
),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
resolve: () =>
|
||||
Effect.succeed({
|
||||
kind: "git",
|
||||
repository: {
|
||||
kind: "git",
|
||||
rootPath: "/repo",
|
||||
metadataPath: null,
|
||||
freshness: {
|
||||
source: "live-local" as const,
|
||||
observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
|
||||
expiresAt: Option.none(),
|
||||
},
|
||||
},
|
||||
driver: driver as unknown as VcsDriver.VcsDriverShape,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)),
|
||||
Layer.provide(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
|
||||
T3CODE_BITBUCKET_EMAIL: "[email protected]",
|
||||
T3CODE_BITBUCKET_API_TOKEN: "token",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return { execute, git: gitMock, layer };
|
||||
}
|
||||
|
||||
it.effect("parses pull request responses from the Bitbucket REST API", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () =>
|
||||
Response.json({
|
||||
...bitbucketPullRequest,
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const result = yield* bitbucket.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add Bitbucket provider",
|
||||
url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/t3code",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
assert.strictEqual(
|
||||
execute.mock.calls[0]?.[0].url,
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests/42",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("lists pull requests with Bitbucket state and source branch query params", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () =>
|
||||
Response.json({
|
||||
values: [
|
||||
{
|
||||
...bitbucketPullRequest,
|
||||
id: 7,
|
||||
state: "MERGED",
|
||||
source: {
|
||||
branch: { name: "feature/merged" },
|
||||
repository: { full_name: "pingdotgg/t3code" },
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const result = yield* bitbucket.listPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "origin:feature/merged",
|
||||
state: "merged",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.strictEqual(result[0]?.state, "merged");
|
||||
const request = execute.mock.calls[0]?.[0];
|
||||
assert.strictEqual(
|
||||
request?.url,
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
|
||||
);
|
||||
assert.deepStrictEqual(request?.urlParams.params, [
|
||||
["pagelen", "10"],
|
||||
["sort", "-updated_on"],
|
||||
["q", 'source.branch.name = "feature/merged" AND state = "MERGED"'],
|
||||
["state", "MERGED"],
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("lists closed pull requests with both closed Bitbucket states", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () =>
|
||||
Response.json({
|
||||
values: [],
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
yield* bitbucket.listPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/closed",
|
||||
state: "closed",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [
|
||||
["pagelen", "10"],
|
||||
["sort", "-updated_on"],
|
||||
[
|
||||
"q",
|
||||
'source.branch.name = "feature/closed" AND (state = "DECLINED" OR state = "SUPERSEDED")',
|
||||
],
|
||||
["state", "DECLINED"],
|
||||
["state", "SUPERSEDED"],
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("expands all-state pull request listing instead of relying on Bitbucket defaults", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () =>
|
||||
Response.json({
|
||||
values: [],
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
yield* bitbucket.listPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/all",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [
|
||||
["pagelen", "10"],
|
||||
["sort", "-updated_on"],
|
||||
[
|
||||
"q",
|
||||
'source.branch.name = "feature/all" AND (state = "OPEN" OR state = "MERGED" OR state = "DECLINED" OR state = "SUPERSEDED")',
|
||||
],
|
||||
["state", "OPEN"],
|
||||
["state", "MERGED"],
|
||||
["state", "DECLINED"],
|
||||
["state", "SUPERSEDED"],
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("reads repository clone URLs and default branch", () => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
branch: { name: "main" },
|
||||
name: "main",
|
||||
use_mainbranch: true,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const cloneUrls = yield* bitbucket.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "pingdotgg/t3code",
|
||||
});
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.deepStrictEqual(cloneUrls, {
|
||||
nameWithOwner: "pingdotgg/t3code",
|
||||
url: "https://bitbucket.org/pingdotgg/t3code.git",
|
||||
sshUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
});
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"prefers the Bitbucket branching model development branch as the default PR target",
|
||||
() => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
branch: { name: "develop" },
|
||||
name: "develop",
|
||||
use_mainbranch: false,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "develop");
|
||||
assert.deepStrictEqual(
|
||||
execute.mock.calls.map((call) => call[0].url).toSorted(),
|
||||
[
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code",
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model",
|
||||
].toSorted(),
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to the repository main branch when the Bitbucket development branch is invalid",
|
||||
() => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
Response.json(
|
||||
request.url.endsWith("/branching-model")
|
||||
? {
|
||||
development: {
|
||||
name: "develop",
|
||||
use_mainbranch: false,
|
||||
is_valid: false,
|
||||
},
|
||||
}
|
||||
: repositoryJson,
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to the repository main branch when the Bitbucket branching model is unavailable",
|
||||
() => {
|
||||
const { layer } = makeLayer({
|
||||
response: (request) =>
|
||||
request.url.endsWith("/branching-model")
|
||||
? Response.json({ error: { message: "Not found" } }, { status: 404 })
|
||||
: Response.json(repositoryJson),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("creates repositories through the Bitbucket REST API", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () => Response.json(repositoryJson),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const cloneUrls = yield* bitbucket.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "pingdotgg/t3code",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(cloneUrls, {
|
||||
nameWithOwner: "pingdotgg/t3code",
|
||||
url: "https://bitbucket.org/pingdotgg/t3code.git",
|
||||
sshUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
});
|
||||
|
||||
const request = execute.mock.calls[0]?.[0];
|
||||
assert.strictEqual(request?.url, "https://api.test.local/2.0/repositories/pingdotgg/t3code");
|
||||
assert.strictEqual(request?.method, "POST");
|
||||
assert.ok(request);
|
||||
const rawBody = (request.body as { readonly body?: Uint8Array }).body;
|
||||
assert.ok(rawBody);
|
||||
assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
|
||||
scm: "git",
|
||||
is_private: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("creates pull requests using the official REST payload shape", () => {
|
||||
const { execute, layer } = makeLayer({
|
||||
response: () => Response.json(bitbucketPullRequest),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "bitbucket-pr-body-" });
|
||||
yield* fileSystem.writeFileString(bodyFile, "PR body");
|
||||
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
yield* bitbucket.createPullRequest({
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile,
|
||||
});
|
||||
|
||||
const request = execute.mock.calls[0]?.[0];
|
||||
assert.strictEqual(
|
||||
request?.url,
|
||||
"https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
|
||||
);
|
||||
assert.strictEqual(request?.method, "POST");
|
||||
assert.ok(request);
|
||||
const rawBody = (request.body as { readonly body?: Uint8Array }).body;
|
||||
assert.ok(rawBody);
|
||||
assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
|
||||
title: "Provider PR",
|
||||
description: "PR body",
|
||||
source: {
|
||||
branch: { name: "feature/provider" },
|
||||
repository: { full_name: "owner/t3code" },
|
||||
},
|
||||
destination: {
|
||||
branch: { name: "main" },
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(layer), Effect.scoped);
|
||||
});
|
||||
|
||||
it.effect("reports auth status through the Bitbucket REST /user endpoint", () => {
|
||||
const { layer } = makeLayer({
|
||||
response: () => Response.json({ username: "bitbucket-user" }),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const auth = yield* bitbucket.probeAuth;
|
||||
|
||||
assert.deepStrictEqual(auth, {
|
||||
status: "authenticated",
|
||||
account: Option.some("bitbucket-user"),
|
||||
host: Option.some("bitbucket.org"),
|
||||
detail: Option.none(),
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
|
||||
const { git, layer } = makeLayer({
|
||||
response: () =>
|
||||
Response.json({
|
||||
...bitbucketPullRequest,
|
||||
source: {
|
||||
branch: { name: "feature/source-control" },
|
||||
repository: {
|
||||
full_name: "pingdotgg/t3code",
|
||||
workspace: { slug: "pingdotgg" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
yield* bitbucket.checkoutPullRequest({
|
||||
cwd: "/repo",
|
||||
context: {
|
||||
provider: {
|
||||
kind: "bitbucket",
|
||||
name: "Bitbucket",
|
||||
baseUrl: "https://bitbucket.org",
|
||||
},
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:pingdotgg/t3code.git",
|
||||
},
|
||||
reference: "42",
|
||||
force: true,
|
||||
});
|
||||
|
||||
assert.strictEqual(git.ensureRemote.mock.calls.length, 0);
|
||||
assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
remoteName: "origin",
|
||||
remoteBranch: "feature/source-control",
|
||||
localBranch: "feature/source-control",
|
||||
});
|
||||
assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
branch: "feature/source-control",
|
||||
remoteName: "origin",
|
||||
remoteBranch: "feature/source-control",
|
||||
});
|
||||
assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
refName: "feature/source-control",
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("checks out fork pull requests through an ensured fork remote", () => {
|
||||
const { git, layer } = makeLayer({
|
||||
response: (request) => {
|
||||
if (request.url.endsWith("/repositories/octocat/t3code")) {
|
||||
return Response.json({
|
||||
...repositoryJson,
|
||||
full_name: "octocat/t3code",
|
||||
links: {
|
||||
html: { href: "https://bitbucket.org/octocat/t3code" },
|
||||
clone: [
|
||||
{ name: "https", href: "https://bitbucket.org/octocat/t3code.git" },
|
||||
{ name: "ssh", href: "[email protected]:octocat/t3code.git" },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
return Response.json({
|
||||
...bitbucketPullRequest,
|
||||
source: {
|
||||
branch: { name: "main" },
|
||||
repository: {
|
||||
full_name: "octocat/t3code",
|
||||
workspace: { slug: "octocat" },
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
yield* bitbucket.checkoutPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
force: true,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(git.ensureRemote.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
preferredName: "octocat",
|
||||
url: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
remoteName: "octocat",
|
||||
remoteBranch: "main",
|
||||
localBranch: "t3code/pr-42/main",
|
||||
});
|
||||
assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
branch: "t3code/pr-42/main",
|
||||
remoteName: "octocat",
|
||||
remoteBranch: "main",
|
||||
});
|
||||
assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
refName: "t3code/pr-42/main",
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -1,762 +0,0 @@
|
||||
import { Config, Context, Effect, FileSystem, Layer, Option, Schema } from "effect";
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlProviderAuth,
|
||||
type SourceControlRepositoryCloneUrls,
|
||||
type SourceControlRepositoryVisibility,
|
||||
} from "@t3tools/contracts";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { sanitizeBranchFragment } from "@t3tools/shared/git";
|
||||
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
|
||||
|
||||
import * as BitbucketPullRequests from "./bitbucketPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
|
||||
|
||||
const BitbucketApiEnvConfig = Config.all({
|
||||
baseUrl: Config.string("T3CODE_BITBUCKET_API_BASE_URL").pipe(
|
||||
Config.withDefault(DEFAULT_API_BASE_URL),
|
||||
),
|
||||
accessToken: Config.string("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
|
||||
email: Config.string("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
|
||||
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
|
||||
});
|
||||
|
||||
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
|
||||
"BitbucketApiError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
full_name: TrimmedNonEmptyString,
|
||||
links: Schema.Struct({
|
||||
html: Schema.optional(
|
||||
Schema.Struct({
|
||||
href: TrimmedNonEmptyString,
|
||||
}),
|
||||
),
|
||||
clone: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
name: TrimmedNonEmptyString,
|
||||
href: TrimmedNonEmptyString,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
mainbranch: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
name: TrimmedNonEmptyString,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawBitbucketBranchingModelSchema = Schema.Struct({
|
||||
development: Schema.optional(
|
||||
Schema.Struct({
|
||||
branch: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
name: Schema.optional(TrimmedNonEmptyString),
|
||||
}),
|
||||
),
|
||||
),
|
||||
is_valid: Schema.optional(Schema.Boolean),
|
||||
name: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
use_mainbranch: Schema.optional(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const BitbucketUserSchema = Schema.Struct({
|
||||
username: Schema.optional(TrimmedNonEmptyString),
|
||||
display_name: Schema.optional(TrimmedNonEmptyString),
|
||||
account_id: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
export interface BitbucketRepositoryLocator {
|
||||
readonly workspace: string;
|
||||
readonly repoSlug: string;
|
||||
}
|
||||
|
||||
export interface BitbucketApiShape {
|
||||
readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
|
||||
readonly listPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly state: "open" | "closed" | "merged" | "all";
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<
|
||||
ReadonlyArray<BitbucketPullRequests.NormalizedBitbucketPullRequestRecord>,
|
||||
BitbucketApiError
|
||||
>;
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<
|
||||
BitbucketPullRequests.NormalizedBitbucketPullRequestRecord,
|
||||
BitbucketApiError
|
||||
>;
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly target?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, BitbucketApiError>;
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
}) => Effect.Effect<string | null, BitbucketApiError>;
|
||||
readonly checkoutPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, BitbucketApiError>;
|
||||
}
|
||||
|
||||
export class BitbucketApi extends Context.Service<BitbucketApi, BitbucketApiShape>()(
|
||||
"t3/source-control/BitbucketApi",
|
||||
) {}
|
||||
|
||||
function nonEmpty(value: string | undefined): Option.Option<string> {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
|
||||
}
|
||||
|
||||
function normalizeChangeRequestId(reference: string): string {
|
||||
const trimmed = reference.trim().replace(/^#/, "");
|
||||
const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
|
||||
trimmed,
|
||||
);
|
||||
return urlMatch?.[1] ?? trimmed;
|
||||
}
|
||||
|
||||
function sourceWorkspace(input: {
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
}): string | undefined {
|
||||
if (input.source?.owner) return input.source.owner;
|
||||
return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
|
||||
}
|
||||
|
||||
function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return ["OPEN"];
|
||||
case "closed":
|
||||
return ["DECLINED", "SUPERSEDED"];
|
||||
case "merged":
|
||||
return ["MERGED"];
|
||||
case "all":
|
||||
return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
|
||||
}
|
||||
}
|
||||
|
||||
function bitbucketQueryString(filters: ReadonlyArray<string>): string {
|
||||
return filters.join(" AND ");
|
||||
}
|
||||
|
||||
function bitbucketStateFilter(states: ReadonlyArray<string>): string {
|
||||
return states.length === 1
|
||||
? `state = "${states[0]}"`
|
||||
: `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
|
||||
}
|
||||
|
||||
function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
|
||||
const normalized = value.trim().replace(/\.git$/u, "");
|
||||
const parts = normalized.split("/").filter((part) => part.length > 0);
|
||||
if (parts.length < 2) return null;
|
||||
const workspace = parts.at(-2);
|
||||
const repoSlug = parts.at(-1);
|
||||
return workspace && repoSlug ? { workspace, repoSlug } : null;
|
||||
}
|
||||
|
||||
function requireRepositoryLocator(
|
||||
operation: string,
|
||||
repository: string,
|
||||
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
|
||||
const locator = parseBitbucketRepositorySlug(repository);
|
||||
return locator
|
||||
? Effect.succeed(locator)
|
||||
: Effect.fail(
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Bitbucket repositories must be specified as workspace/repository.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
|
||||
const trimmed = remoteUrl.trim();
|
||||
if (trimmed.startsWith("git@")) {
|
||||
const pathStart = trimmed.indexOf(":");
|
||||
return pathStart < 0 ? null : parseBitbucketRepositorySlug(trimmed.slice(pathStart + 1));
|
||||
}
|
||||
|
||||
try {
|
||||
return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: typeof RawBitbucketRepositorySchema.Type,
|
||||
): SourceControlRepositoryCloneUrls {
|
||||
const httpClone =
|
||||
raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
|
||||
raw.links.html?.href;
|
||||
const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
|
||||
|
||||
return {
|
||||
nameWithOwner: raw.full_name,
|
||||
url: httpClone ?? raw.links.html?.href ?? raw.full_name,
|
||||
sshUrl: sshClone ?? httpClone ?? raw.full_name,
|
||||
};
|
||||
}
|
||||
|
||||
function defaultChangeRequestTargetBranch(input: {
|
||||
readonly repository: typeof RawBitbucketRepositorySchema.Type;
|
||||
readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
|
||||
}): string | null {
|
||||
const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
|
||||
const development = input.branchingModel?.development;
|
||||
if (!development || development.use_mainbranch === true || development.is_valid === false) {
|
||||
return repositoryMainBranch;
|
||||
}
|
||||
|
||||
const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
|
||||
if (developmentBranch.length === 0 || developmentBranch === "null") {
|
||||
return repositoryMainBranch;
|
||||
}
|
||||
|
||||
return developmentBranch;
|
||||
}
|
||||
|
||||
function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
|
||||
const trimmed = originRemoteUrl?.trim() ?? "";
|
||||
return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
|
||||
}
|
||||
|
||||
function selectCloneUrl(input: {
|
||||
readonly cloneUrls: SourceControlRepositoryCloneUrls;
|
||||
readonly originRemoteUrl: string | null;
|
||||
}): string {
|
||||
return shouldPreferSshRemote(input.originRemoteUrl)
|
||||
? input.cloneUrls.sshUrl
|
||||
: input.cloneUrls.url;
|
||||
}
|
||||
|
||||
function checkoutBranchName(input: {
|
||||
readonly pullRequestId: number;
|
||||
readonly headBranch: string;
|
||||
readonly isCrossRepository: boolean;
|
||||
}): string {
|
||||
if (!input.isCrossRepository) {
|
||||
return input.headBranch;
|
||||
}
|
||||
|
||||
return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
|
||||
}
|
||||
|
||||
function repositoryNameWithOwner(
|
||||
repository: Schema.Schema.Type<
|
||||
typeof BitbucketPullRequests.BitbucketPullRequestSchema
|
||||
>["source"]["repository"],
|
||||
): string | null {
|
||||
const fullName = repository?.full_name?.trim() ?? "";
|
||||
return fullName.length > 0 ? fullName : null;
|
||||
}
|
||||
|
||||
function repositoryOwnerName(repositoryName: string): string {
|
||||
return repositoryName.split("/")[0]?.trim() || "bitbucket";
|
||||
}
|
||||
|
||||
function authFromConfig(
|
||||
config: Config.Success<typeof BitbucketApiEnvConfig>,
|
||||
): SourceControlProviderAuth {
|
||||
if (Option.isSome(config.accessToken)) {
|
||||
return {
|
||||
status: "unknown",
|
||||
account: Option.none(),
|
||||
host: Option.some("bitbucket.org"),
|
||||
detail: Option.some("Bitbucket access token is configured."),
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
|
||||
return {
|
||||
status: "unknown",
|
||||
account: config.email,
|
||||
host: Option.some("bitbucket.org"),
|
||||
detail: Option.some("Bitbucket API token is configured."),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "unauthenticated",
|
||||
account: Option.none(),
|
||||
host: Option.some("bitbucket.org"),
|
||||
detail: Option.some(
|
||||
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function requestError(operation: string, cause: unknown): BitbucketApiError {
|
||||
return new BitbucketApiError({
|
||||
operation,
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function isBitbucketApiError(cause: unknown): cause is BitbucketApiError {
|
||||
return Schema.is(BitbucketApiError)(cause);
|
||||
}
|
||||
|
||||
function responseError(
|
||||
operation: string,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
Effect.catch(() => Effect.succeed("")),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
status: response.status,
|
||||
detail:
|
||||
body.trim().length > 0
|
||||
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
|
||||
: `Bitbucket returned HTTP ${response.status}.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeBitbucketApi")(function* () {
|
||||
const config = yield* BitbucketApiEnvConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
|
||||
|
||||
const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
|
||||
|
||||
const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
|
||||
if (Option.isSome(config.accessToken)) {
|
||||
return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
|
||||
}
|
||||
if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
|
||||
return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
|
||||
}
|
||||
return request;
|
||||
};
|
||||
|
||||
const decodeResponse = <S extends Schema.Top>(
|
||||
operation: string,
|
||||
schema: S,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": (success) =>
|
||||
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Bitbucket returned invalid JSON for the requested resource.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
orElse: (failed) => responseError(operation, failed),
|
||||
})(response);
|
||||
|
||||
const executeJson = <S extends Schema.Top>(
|
||||
operation: string,
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
schema: S,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
|
||||
Effect.mapError((cause) => requestError(operation, cause)),
|
||||
Effect.flatMap((response) => decodeResponse(operation, schema, response)),
|
||||
);
|
||||
|
||||
const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly repository?: string;
|
||||
}) {
|
||||
const fromRepository =
|
||||
input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;
|
||||
if (fromRepository) return fromRepository;
|
||||
|
||||
const fromContext =
|
||||
input.context?.provider.kind === "bitbucket"
|
||||
? parseBitbucketRemoteUrl(input.context.remoteUrl)
|
||||
: null;
|
||||
if (fromContext) return fromContext;
|
||||
|
||||
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to list remotes for ${input.cwd}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
for (const remote of remotes.remotes) {
|
||||
if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
|
||||
const parsed = parseBitbucketRemoteUrl(remote.url);
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
|
||||
return yield* new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
|
||||
});
|
||||
});
|
||||
|
||||
const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
|
||||
executeJson(
|
||||
"getRepository",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
|
||||
),
|
||||
),
|
||||
RawBitbucketRepositorySchema,
|
||||
);
|
||||
|
||||
const getRepository = (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly repository?: string;
|
||||
}) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
|
||||
|
||||
const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
|
||||
executeJson(
|
||||
"getBranchingModel",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
|
||||
),
|
||||
),
|
||||
RawBitbucketBranchingModelSchema,
|
||||
);
|
||||
|
||||
const getRawPullRequestFromRepository = (
|
||||
repository: BitbucketRepositoryLocator,
|
||||
reference: string,
|
||||
) =>
|
||||
executeJson(
|
||||
"getPullRequest",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
|
||||
),
|
||||
),
|
||||
BitbucketPullRequests.BitbucketPullRequestSchema,
|
||||
);
|
||||
|
||||
const getRawPullRequest = (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly reference: string;
|
||||
}) =>
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
|
||||
);
|
||||
|
||||
const readConfigValueNullable = (cwd: string, key: string) =>
|
||||
git.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
|
||||
const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly context?: SourceControlProvider.SourceControlProviderContext;
|
||||
readonly destinationRepository: BitbucketRepositoryLocator;
|
||||
readonly sourceRepositoryName: string;
|
||||
readonly isCrossRepository: boolean;
|
||||
}) {
|
||||
if (
|
||||
input.context?.provider.kind === "bitbucket" &&
|
||||
!input.isCrossRepository &&
|
||||
parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
|
||||
) {
|
||||
return input.context.remoteName;
|
||||
}
|
||||
|
||||
if (!input.isCrossRepository) {
|
||||
const remoteName = yield* git
|
||||
.resolvePrimaryRemoteName(input.cwd)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (remoteName) return remoteName;
|
||||
}
|
||||
|
||||
const cloneUrls = yield* getRepository({
|
||||
cwd: input.cwd,
|
||||
repository: input.sourceRepositoryName,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
}).pipe(Effect.map(normalizeRepositoryCloneUrls));
|
||||
const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
|
||||
return yield* git.ensureRemote({
|
||||
cwd: input.cwd,
|
||||
preferredName: input.isCrossRepository
|
||||
? repositoryOwnerName(input.sourceRepositoryName)
|
||||
: input.destinationRepository.workspace,
|
||||
url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
|
||||
});
|
||||
});
|
||||
|
||||
return BitbucketApi.of({
|
||||
probeAuth: executeJson(
|
||||
"probeAuth",
|
||||
HttpClientRequest.get(apiUrl("/user")),
|
||||
BitbucketUserSchema,
|
||||
).pipe(
|
||||
Effect.map((user) => ({
|
||||
status: "authenticated" as const,
|
||||
account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
|
||||
host: Option.some("bitbucket.org"),
|
||||
detail: Option.none<string>(),
|
||||
})),
|
||||
Effect.catch(() => Effect.succeed(authFromConfig(config))),
|
||||
),
|
||||
listPullRequests: (input) =>
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((repository) => {
|
||||
const states = toBitbucketStates(input.state);
|
||||
const query: Record<string, string | ReadonlyArray<string>> = {
|
||||
pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
|
||||
sort: "-updated_on",
|
||||
q: bitbucketQueryString([
|
||||
`source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
|
||||
bitbucketStateFilter(states),
|
||||
]),
|
||||
state: states,
|
||||
};
|
||||
|
||||
return executeJson(
|
||||
"listPullRequests",
|
||||
HttpClientRequest.get(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
|
||||
),
|
||||
{ urlParams: query },
|
||||
),
|
||||
BitbucketPullRequests.BitbucketPullRequestListSchema,
|
||||
);
|
||||
}),
|
||||
Effect.map((list) =>
|
||||
list.values.map(BitbucketPullRequests.normalizeBitbucketPullRequestRecord),
|
||||
),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
getRawPullRequest(input).pipe(
|
||||
Effect.map(BitbucketPullRequests.normalizeBitbucketPullRequestRecord),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
|
||||
createRepository: (input) =>
|
||||
requireRepositoryLocator("createRepository", input.repository).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"createRepository",
|
||||
HttpClientRequest.post(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
|
||||
),
|
||||
).pipe(
|
||||
HttpClientRequest.bodyJsonUnsafe({
|
||||
scm: "git",
|
||||
is_private: input.visibility === "private",
|
||||
}),
|
||||
),
|
||||
RawBitbucketRepositorySchema,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* resolveRepository(input);
|
||||
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketApiError({
|
||||
operation: "createPullRequest",
|
||||
detail: `Failed to read pull request body file ${input.bodyFile}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const sourceOwner = sourceWorkspace(input);
|
||||
const body = {
|
||||
title: input.title,
|
||||
description,
|
||||
source: {
|
||||
branch: {
|
||||
name: SourceControlProvider.sourceBranch(input),
|
||||
},
|
||||
...(sourceOwner
|
||||
? {
|
||||
repository: {
|
||||
full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
destination: {
|
||||
branch: {
|
||||
name: input.target?.refName ?? input.baseBranch,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
yield* executeJson(
|
||||
"createPullRequest",
|
||||
HttpClientRequest.post(
|
||||
apiUrl(
|
||||
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
|
||||
),
|
||||
).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
|
||||
BitbucketPullRequests.BitbucketPullRequestSchema,
|
||||
);
|
||||
}),
|
||||
getDefaultBranch: (input) =>
|
||||
resolveRepository(input).pipe(
|
||||
Effect.flatMap((locator) =>
|
||||
Effect.all(
|
||||
{
|
||||
repository: getRepositoryFromLocator(locator),
|
||||
branchingModel: getBranchingModelFromLocator(locator).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed<typeof RawBitbucketBranchingModelSchema.Type | null>(null),
|
||||
),
|
||||
),
|
||||
},
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.map(defaultChangeRequestTargetBranch),
|
||||
),
|
||||
// Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
|
||||
// an official checkout CLI. This provider-local path uses GitVcsDriver as a
|
||||
// narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
|
||||
// as the source-control provider model: if we support non-Git-compatible
|
||||
// hosting providers or native JJ/Sapling checkout flows, move this into a
|
||||
// VCS-specific change-request checkout capability.
|
||||
checkoutPullRequest: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const destinationRepository = yield* resolveRepository(input);
|
||||
const pullRequest = yield* getRawPullRequestFromRepository(
|
||||
destinationRepository,
|
||||
input.reference,
|
||||
);
|
||||
const destinationRepositoryName =
|
||||
repositoryNameWithOwner(pullRequest.destination.repository) ??
|
||||
`${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
|
||||
const sourceRepositoryName =
|
||||
repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
|
||||
const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
|
||||
const remoteName = yield* resolveCheckoutRemote({
|
||||
cwd: input.cwd,
|
||||
destinationRepository,
|
||||
sourceRepositoryName,
|
||||
isCrossRepository,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
});
|
||||
const remoteBranch = pullRequest.source.branch.name;
|
||||
const localBranch = checkoutBranchName({
|
||||
pullRequestId: pullRequest.id,
|
||||
headBranch: remoteBranch,
|
||||
isCrossRepository,
|
||||
});
|
||||
const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
|
||||
const localBranchExists = localBranchNames.includes(localBranch);
|
||||
|
||||
if (input.force === true || !localBranchExists) {
|
||||
yield* git.fetchRemoteBranch({
|
||||
cwd: input.cwd,
|
||||
remoteName,
|
||||
remoteBranch,
|
||||
localBranch,
|
||||
});
|
||||
} else {
|
||||
yield* git.fetchRemoteTrackingBranch({
|
||||
cwd: input.cwd,
|
||||
remoteName,
|
||||
remoteBranch,
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.setBranchUpstream({
|
||||
cwd: input.cwd,
|
||||
branch: localBranch,
|
||||
remoteName,
|
||||
remoteBranch,
|
||||
});
|
||||
yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isBitbucketApiError(cause)
|
||||
? cause
|
||||
: new BitbucketApiError({
|
||||
operation: "checkoutPullRequest",
|
||||
detail: cause instanceof Error ? cause.message : String(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BitbucketApi, make());
|
||||
@@ -1,126 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import * as BitbucketApi from "./BitbucketApi.ts";
|
||||
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
|
||||
|
||||
function makeProvider(bitbucket: Partial<BitbucketApi.BitbucketApiShape>) {
|
||||
return BitbucketSourceControlProvider.make().pipe(
|
||||
Effect.provide(Layer.mock(BitbucketApi.BitbucketApi)(bitbucket)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("maps Bitbucket PR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
getPullRequest: () =>
|
||||
Effect.succeed({
|
||||
number: 42,
|
||||
title: "Add Bitbucket provider",
|
||||
url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
}),
|
||||
});
|
||||
|
||||
const changeRequest = yield* provider.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequest, {
|
||||
provider: "bitbucket",
|
||||
number: 42,
|
||||
title: "Add Bitbucket provider",
|
||||
url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists Bitbucket PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<BitbucketApi.BitbucketApiShape["listPullRequests"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
listPullRequests: (input) => {
|
||||
listInput = input;
|
||||
return Effect.succeed([]);
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(listInput, {
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates Bitbucket PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<BitbucketApi.BitbucketApiShape["createPullRequest"]>[0] | null =
|
||||
null;
|
||||
const provider = yield* makeProvider({
|
||||
createPullRequest: (input) => {
|
||||
createInput = input;
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.createChangeRequest({
|
||||
cwd: "/repo",
|
||||
baseRefName: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider PR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(createInput, {
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
source: {
|
||||
owner: "owner",
|
||||
refName: "feature/provider",
|
||||
},
|
||||
title: "Provider PR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses Bitbucket API repository detection for default branch lookup", () =>
|
||||
Effect.gen(function* () {
|
||||
let cwdInput: string | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
getDefaultBranch: (input) => {
|
||||
cwdInput = input.cwd;
|
||||
return Effect.succeed("main");
|
||||
},
|
||||
});
|
||||
|
||||
const defaultBranch = yield* provider.getDefaultBranch({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(defaultBranch, "main");
|
||||
assert.strictEqual(cwdInput, "/repo");
|
||||
}),
|
||||
);
|
||||
@@ -1,126 +0,0 @@
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import * as BitbucketApi from "./BitbucketApi.ts";
|
||||
import * as BitbucketPullRequests from "./bitbucketPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import type * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: BitbucketApi.BitbucketApiError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "bitbucket",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(
|
||||
summary: BitbucketPullRequests.NormalizedBitbucketPullRequestRecord,
|
||||
): ChangeRequest {
|
||||
return {
|
||||
provider: "bitbucket",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state,
|
||||
updatedAt: summary.updatedAt ?? Option.none(),
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
...(summary.headRepositoryNameWithOwner !== undefined
|
||||
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
|
||||
: {}),
|
||||
...(summary.headRepositoryOwnerLogin !== undefined
|
||||
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeBitbucketSourceControlProvider")(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
kind: "bitbucket",
|
||||
listChangeRequests: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
return bitbucket
|
||||
.listPullRequests({
|
||||
cwd: input.cwd,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
state: input.state,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
bitbucket.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
return bitbucket
|
||||
.createPullRequest({
|
||||
cwd: input.cwd,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
baseBranch: input.baseRefName,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
...(input.target ? { target: input.target } : {}),
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
bitbucket
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
bitbucket
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
bitbucket
|
||||
.getDefaultBranch({
|
||||
cwd: input.cwd,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
checkoutChangeRequest: (input) =>
|
||||
bitbucket
|
||||
.checkoutPullRequest({
|
||||
cwd: input.cwd,
|
||||
...(input.context ? { context: input.context } : {}),
|
||||
reference: input.reference,
|
||||
...(input.force !== undefined ? { force: input.force } : {}),
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
|
||||
|
||||
export const makeDiscovery = Effect.fn("makeBitbucketSourceControlProviderDiscovery")(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
|
||||
return {
|
||||
type: "api",
|
||||
kind: "bitbucket",
|
||||
label: "Bitbucket",
|
||||
installHint:
|
||||
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN on the server (use a Bitbucket API token with pull request and repository scopes).",
|
||||
probeAuth: bitbucket.probeAuth,
|
||||
} satisfies SourceControlProviderDiscovery.SourceControlApiDiscoverySpec;
|
||||
});
|
||||
@@ -1,63 +1,53 @@
|
||||
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, type VcsError } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
vi.mock("../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
|
||||
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const mockRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
|
||||
|
||||
const layer = GitHubCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: mockRun,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const mockedRunProcess = vi.mocked(runProcess);
|
||||
const layer = it.layer(GitHubCli.layer);
|
||||
|
||||
afterEach(() => {
|
||||
mockRun.mockReset();
|
||||
mockedRunProcess.mockReset();
|
||||
});
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
layer("GitHubCli.layer", (it) => {
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
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",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
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 gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -71,51 +61,51 @@ describe("GitHubCli.layer", () => {
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
expect(mockRun).toHaveBeenCalledWith({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: [
|
||||
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||
"gh",
|
||||
[
|
||||
"pr",
|
||||
"view",
|
||||
"#42",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
expect.objectContaining({ cwd: "/repo" }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
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 ",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
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 gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -129,44 +119,46 @@ describe("GitHubCli.layer", () => {
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
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: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
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 gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
@@ -179,27 +171,29 @@ describe("GitHubCli.layer", () => {
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
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 gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
@@ -207,85 +201,26 @@ describe("GitHubCli.layer", () => {
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("creates repositories and parses clone URLs from create output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
"✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
expect(mockRun).toHaveBeenNthCalledWith(1, {
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: ["repo", "create", "octocat/codething-mvp", "--private"],
|
||||
cwd: "/repo",
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("falls back to constructed URLs when create output omits a URL", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const result = yield* gh.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/codething-mvp",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/codething-mvp",
|
||||
url: "https://github.com/octocat/codething-mvp",
|
||||
sshUrl: "[email protected]:octocat/codething-mvp.git",
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the pull request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
}),
|
||||
mockedRunProcess.mockRejectedValueOnce(
|
||||
new Error(
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
),
|
||||
);
|
||||
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const error = yield* gh
|
||||
.getPullRequest({
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Pull request not found"), true);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,26 +1,17 @@
|
||||
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
import { GitHubCliError, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
|
||||
import type { ProcessRunResult } from "../processRunner.ts";
|
||||
import { runProcess } from "../processRunner.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../git/githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
@@ -44,7 +35,7 @@ export interface GitHubCliShape {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
|
||||
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
@@ -62,12 +53,6 @@ export interface GitHubCliShape {
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
|
||||
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
@@ -91,61 +76,53 @@ export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/source-control/GitHubCli",
|
||||
) {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
return String(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,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeGitHubCliError(
|
||||
operation: "execute" | "stdout",
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const text = errorText(error);
|
||||
const lower = text.toLowerCase();
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
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.",
|
||||
detail: `GitHub CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: text,
|
||||
detail: "GitHub CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -166,43 +143,6 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `gh repo create` prints the canonical URL of the new repository on stdout
|
||||
* (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
|
||||
* follow-up `gh repo view`, which can race GitHub's GraphQL eventual
|
||||
* consistency window and falsely report the just-created repo as missing.
|
||||
*/
|
||||
function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
stdout: string,
|
||||
repository: string,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
const fallbackHost = "github.com";
|
||||
const match = stdout.match(/https?:\/\/[^\s]+/);
|
||||
if (match) {
|
||||
const cleaned = match[0].replace(/\.git$/, "");
|
||||
try {
|
||||
const parsed = new URL(cleaned);
|
||||
const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
if (segments.length === 2) {
|
||||
const nameWithOwner = `${segments[0]}/${segments[1]}`;
|
||||
return {
|
||||
nameWithOwner,
|
||||
url: `${parsed.origin}/${nameWithOwner}`,
|
||||
sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the input-derived defaults below.
|
||||
}
|
||||
}
|
||||
return {
|
||||
nameWithOwner: repository,
|
||||
url: `https://${fallbackHost}/${repository}`,
|
||||
sshUrl: `git@${fallbackHost}:${repository}.git`,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitHubJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
@@ -221,19 +161,16 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
export const make = Effect.sync(() => {
|
||||
const execute: GitHubCliShape["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitHubCliError("execute", error)));
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -257,13 +194,13 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
: 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: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -289,13 +226,13 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestJson(raw)).pipe(
|
||||
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: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -324,15 +261,6 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "create", input.repository, `--${input.visibility}`],
|
||||
}).pipe(
|
||||
Effect.map((result) =>
|
||||
deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
|
||||
),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
@@ -367,4 +295,4 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitHubCli, make());
|
||||
export const layer = Layer.effect(GitHubCli, make);
|
||||
@@ -1,23 +1,19 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
|
||||
const processResult = (stdout: string): VcsProcess.VcsProcessOutput => ({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
const processResult = (stdout: string) => ({
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
function makeProvider(github: Partial<GitHubCli.GitHubCliShape>) {
|
||||
return GitHubSourceControlProvider.make().pipe(
|
||||
Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
|
||||
);
|
||||
function makeProvider(github: Partial<GitHubCliShape>) {
|
||||
return GitHubSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitHubCli)(github)));
|
||||
}
|
||||
|
||||
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
|
||||
@@ -129,7 +125,7 @@ it.effect("treats empty non-open change request listing output as no results", (
|
||||
|
||||
it.effect("creates GitHub PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<GitHubCli.GitHubCliShape["createPullRequest"]>[0] | null = null;
|
||||
let createInput: Parameters<GitHubCliShape["createPullRequest"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
createPullRequest: (input) => {
|
||||
createInput = input;
|
||||
|
||||
@@ -3,17 +3,14 @@ import {
|
||||
SourceControlProviderError,
|
||||
type ChangeRequest,
|
||||
type ChangeRequestState,
|
||||
type GitHubCliError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "./GitHubCli.ts";
|
||||
import { decodeGitHubPullRequestListJson } from "../git/githubPullRequests.ts";
|
||||
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: GitHubCli.GitHubCliError,
|
||||
): SourceControlProviderError {
|
||||
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation,
|
||||
@@ -22,7 +19,7 @@ function providerError(
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
|
||||
function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "github",
|
||||
number: summary.number,
|
||||
@@ -44,119 +41,75 @@ function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeReq
|
||||
};
|
||||
}
|
||||
|
||||
function parseGitHubAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
|
||||
const output = SourceControlProviderDiscovery.combinedAuthOutput(input);
|
||||
const account = SourceControlProviderDiscovery.matchFirst(output, [
|
||||
/Logged in to .* account\s+([^\s(]+)/iu,
|
||||
/Logged in to .* as\s+([^\s(]+)/iu,
|
||||
]);
|
||||
const host = SourceControlProviderDiscovery.parseCliHost(output);
|
||||
|
||||
if (input.exitCode !== 0) {
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "unauthenticated",
|
||||
host,
|
||||
detail:
|
||||
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
|
||||
"Run `gh auth login` to authenticate GitHub CLI.",
|
||||
});
|
||||
}
|
||||
|
||||
if (account) {
|
||||
return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host });
|
||||
}
|
||||
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "unknown",
|
||||
host,
|
||||
detail:
|
||||
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
|
||||
"GitHub CLI auth status could not be parsed.",
|
||||
});
|
||||
}
|
||||
|
||||
export const discovery = {
|
||||
type: "cli",
|
||||
kind: "github",
|
||||
label: "GitHub",
|
||||
executable: "gh",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseGitHubAuth,
|
||||
installHint:
|
||||
"Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
|
||||
} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
|
||||
|
||||
export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
const github = yield* GitHubCli.GitHubCli;
|
||||
const github = yield* GitHubCli;
|
||||
|
||||
const listChangeRequests: SourceControlProvider.SourceControlProviderShape["listChangeRequests"] =
|
||||
(input) => {
|
||||
if (input.state === "open") {
|
||||
return github
|
||||
.listOpenPullRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
}
|
||||
|
||||
const stateArg: ChangeRequestState | "all" = input.state;
|
||||
const listChangeRequests: SourceControlProviderShape["listChangeRequests"] = (input) => {
|
||||
if (input.state === "open") {
|
||||
return github
|
||||
.execute({
|
||||
.listOpenPullRequests({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headSelector,
|
||||
"--state",
|
||||
stateArg,
|
||||
"--limit",
|
||||
String(input.limit ?? 20),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
headSelector: input.headSelector,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return Effect.succeed([]);
|
||||
}
|
||||
return Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) =>
|
||||
Result.isSuccess(decoded)
|
||||
? Effect.succeed(
|
||||
decoded.success.map((item) => ({
|
||||
...toChangeRequest(item),
|
||||
updatedAt: item.updatedAt,
|
||||
})),
|
||||
)
|
||||
: Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(SourceControlProviderError)(error)
|
||||
? error
|
||||
: providerError("listChangeRequests", error),
|
||||
),
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
const stateArg: ChangeRequestState | "all" = input.state;
|
||||
return github
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headSelector,
|
||||
"--state",
|
||||
stateArg,
|
||||
"--limit",
|
||||
String(input.limit ?? 20),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return Effect.succeed([]);
|
||||
}
|
||||
return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) =>
|
||||
Result.isSuccess(decoded)
|
||||
? Effect.succeed(
|
||||
decoded.success.map((item) => ({
|
||||
...toChangeRequest(item),
|
||||
updatedAt: item.updatedAt,
|
||||
})),
|
||||
)
|
||||
: Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(SourceControlProviderError)(error)
|
||||
? error
|
||||
: providerError("listChangeRequests", error),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
return SourceControlProvider.of({
|
||||
kind: "github",
|
||||
listChangeRequests,
|
||||
getChangeRequest: (input) =>
|
||||
@@ -178,10 +131,6 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
github
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
github
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
github
|
||||
.getDefaultBranch(input)
|
||||
@@ -193,4 +142,4 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
|
||||
export const layer = Layer.effect(SourceControlProvider, make());
|
||||
@@ -1,326 +0,0 @@
|
||||
import { assert, it, afterEach, expect, vi } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
|
||||
const mockedRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
|
||||
const layer = it.layer(
|
||||
GitLabCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: mockedRun,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function processOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
mockedRun.mockReset();
|
||||
});
|
||||
|
||||
layer("GitLabCli.layer", (it) => {
|
||||
it.effect("parses merge request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
iid: 42,
|
||||
title: "Add MR thread creation",
|
||||
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
target_branch: "main",
|
||||
source_branch: "feature/mr-threads",
|
||||
state: "opened",
|
||||
source_project_id: 101,
|
||||
target_project_id: 100,
|
||||
source_project: {
|
||||
path_with_namespace: "octocat/t3code",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add MR thread creation",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/mr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/t3code",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["mr", "view", "42", "--output", "json"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing MR lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify([
|
||||
{
|
||||
iid: 0,
|
||||
title: "invalid",
|
||||
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
|
||||
target_branch: "main",
|
||||
source_branch: "feature/invalid",
|
||||
},
|
||||
{
|
||||
iid: 43,
|
||||
title: " Valid MR ",
|
||||
web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
|
||||
target_branch: " main ",
|
||||
source_branch: " feature/mr-list ",
|
||||
state: "merged",
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.listMergeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/mr-list",
|
||||
state: "all",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid MR",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/mr-list",
|
||||
state: "merged",
|
||||
},
|
||||
]);
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
"feature/mr-list",
|
||||
"--all",
|
||||
"--per-page",
|
||||
"20",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "octocat/t3code",
|
||||
web_url: "https://gitlab.com/octocat/t3code",
|
||||
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
|
||||
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates merge requests through the GitLab API without placing the body in argv", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
yield* glab.createMergeRequest({
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/t3-mr-body.md",
|
||||
});
|
||||
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects/:fullpath/merge_requests",
|
||||
"--raw-field",
|
||||
"source_branch=feature/provider",
|
||||
"--raw-field",
|
||||
"target_branch=main",
|
||||
"--raw-field",
|
||||
"title=Provider MR",
|
||||
"--field",
|
||||
"description=@/tmp/t3-mr-body.md",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates repositories under an explicit namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun
|
||||
.mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
|
||||
.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "octocat/t3code",
|
||||
web_url: "https://gitlab.com/octocat/t3code",
|
||||
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
|
||||
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
const result = yield* glab.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "public",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["api", "namespaces/octocat"],
|
||||
}),
|
||||
);
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
"path=t3code",
|
||||
"--raw-field",
|
||||
"name=t3code",
|
||||
"--raw-field",
|
||||
"visibility=public",
|
||||
"--raw-field",
|
||||
"namespace_id=1234",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
yield* glab.checkoutMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
force: true,
|
||||
});
|
||||
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["mr", "checkout", "42"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the merge request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,442 +0,0 @@
|
||||
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
|
||||
|
||||
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitLabMergeRequests from "./gitLabMergeRequests.ts";
|
||||
import type * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state?: "open" | "closed" | "merged";
|
||||
readonly updatedAt?: Option.Option<DateTime.Utc>;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
export interface GitLabRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
export interface GitLabCliShape {
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
|
||||
|
||||
readonly listMergeRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly state: "open" | "closed" | "merged" | "all";
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
|
||||
|
||||
readonly getMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
|
||||
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly target?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, GitLabCliError>;
|
||||
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, GitLabCliError>;
|
||||
|
||||
readonly checkoutMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, GitLabCliError>;
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
|
||||
"t3/source-control/GitLabCli",
|
||||
) {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "VcsProcessSpawnError"
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI (`glab`) 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("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: `GitLab CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
http_url_to_repo: TrimmedNonEmptyString,
|
||||
ssh_url_to_repo: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const RawGitLabDefaultBranchSchema = Schema.Struct({
|
||||
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
return {
|
||||
nameWithOwner: raw.path_with_namespace,
|
||||
url: raw.web_url,
|
||||
sshUrl: raw.ssh_url_to_repo,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return [];
|
||||
case "closed":
|
||||
return ["--closed"];
|
||||
case "merged":
|
||||
return ["--merged"];
|
||||
case "all":
|
||||
return ["--all"];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHeadSelector(headSelector: string): string {
|
||||
const trimmed = headSelector.trim();
|
||||
const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
|
||||
return ownerBranch?.[1]?.trim() || trimmed;
|
||||
}
|
||||
|
||||
function sourceRefName(input: {
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
}): string {
|
||||
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
|
||||
}
|
||||
|
||||
function sourceProjectIdentifier(
|
||||
source: SourceControlProvider.SourceControlRefSelector | undefined,
|
||||
): string | null {
|
||||
return source?.repository ?? source?.owner ?? null;
|
||||
}
|
||||
|
||||
function toSummaryWithOptionalUpdatedAt(
|
||||
record: GitLabMergeRequestSummary & {
|
||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
||||
},
|
||||
): GitLabMergeRequestSummary {
|
||||
const { updatedAt, ...summary } = record;
|
||||
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
|
||||
}
|
||||
|
||||
function parseRepositoryPath(repository: string): {
|
||||
readonly namespacePath: string | null;
|
||||
readonly projectPath: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const projectPath = parts.at(-1) ?? repository.trim();
|
||||
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
|
||||
return { namespacePath, projectPath };
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitLabCli")(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const execute: GitLabCliShape["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
listMergeRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
sourceRefName(input),
|
||||
...stateArgs(input.state),
|
||||
"--per-page",
|
||||
String(input.limit ?? 20),
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "listMergeRequests",
|
||||
detail: `GitLab CLI returned invalid MR list JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "getMergeRequest",
|
||||
detail: `GitLab CLI returned invalid merge request JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `projects/${encodeURIComponent(input.repository)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) => {
|
||||
const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
|
||||
const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
|
||||
? execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
)
|
||||
: Effect.succeed(null);
|
||||
|
||||
return namespaceId.pipe(
|
||||
Effect.flatMap((resolvedNamespaceId) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
`path=${projectPath}`,
|
||||
"--raw-field",
|
||||
`name=${projectPath}`,
|
||||
"--raw-field",
|
||||
`visibility=${input.visibility}`,
|
||||
...(resolvedNamespaceId === null
|
||||
? []
|
||||
: ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
|
||||
],
|
||||
}),
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
},
|
||||
createMergeRequest: (input) => {
|
||||
const sourceProject = sourceProjectIdentifier(input.source);
|
||||
return execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects/:fullpath/merge_requests",
|
||||
"--raw-field",
|
||||
`source_branch=${sourceRefName(input)}`,
|
||||
"--raw-field",
|
||||
`target_branch=${input.target?.refName ?? input.baseBranch}`,
|
||||
...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
|
||||
"--raw-field",
|
||||
`title=${input.title}`,
|
||||
"--field",
|
||||
`description=@${input.bodyFile}`,
|
||||
],
|
||||
}).pipe(Effect.asVoid);
|
||||
},
|
||||
getDefaultBranch: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", "projects/:fullpath"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitLabCli, make());
|
||||
@@ -1,107 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
|
||||
function makeProvider(gitlab: Partial<GitLabCli.GitLabCliShape>) {
|
||||
return GitLabSourceControlProvider.make().pipe(
|
||||
Effect.provide(Layer.mock(GitLabCli.GitLabCli)(gitlab)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
getMergeRequest: () =>
|
||||
Effect.succeed({
|
||||
number: 42,
|
||||
title: "Add GitLab provider",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
}),
|
||||
});
|
||||
|
||||
const changeRequest = yield* provider.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequest, {
|
||||
provider: "gitlab",
|
||||
number: 42,
|
||||
title: "Add GitLab provider",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<GitLabCli.GitLabCliShape["listMergeRequests"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
listMergeRequests: (input) => {
|
||||
listInput = input;
|
||||
return Effect.succeed([]);
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(listInput, {
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<GitLabCli.GitLabCliShape["createMergeRequest"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
createMergeRequest: (input) => {
|
||||
createInput = input;
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.createChangeRequest({
|
||||
cwd: "/repo",
|
||||
baseRefName: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(createInput, {
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
source: {
|
||||
owner: "owner",
|
||||
refName: "feature/provider",
|
||||
},
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,144 +0,0 @@
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
|
||||
|
||||
function providerError(
|
||||
operation: string,
|
||||
cause: GitLabCli.GitLabCliError,
|
||||
): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "gitlab",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state ?? "open",
|
||||
updatedAt: summary.updatedAt ?? Option.none(),
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
...(summary.headRepositoryNameWithOwner !== undefined
|
||||
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
|
||||
: {}),
|
||||
...(summary.headRepositoryOwnerLogin !== undefined
|
||||
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseGitLabAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
|
||||
const output = SourceControlProviderDiscovery.combinedAuthOutput(input);
|
||||
const account = SourceControlProviderDiscovery.matchFirst(output, [
|
||||
/Logged in to .* as\s+([^\s(]+)/iu,
|
||||
/Logged in to .* account\s+([^\s(]+)/iu,
|
||||
/account:\s*([^\s(]+)/iu,
|
||||
]);
|
||||
const host = SourceControlProviderDiscovery.parseCliHost(output);
|
||||
|
||||
if (input.exitCode !== 0) {
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "unauthenticated",
|
||||
host,
|
||||
detail:
|
||||
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
|
||||
"Run `glab auth login` to authenticate GitLab CLI.",
|
||||
});
|
||||
}
|
||||
|
||||
if (account) {
|
||||
return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host });
|
||||
}
|
||||
|
||||
return SourceControlProviderDiscovery.providerAuth({
|
||||
status: "unknown",
|
||||
host,
|
||||
detail:
|
||||
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
|
||||
"GitLab CLI auth status could not be parsed.",
|
||||
});
|
||||
}
|
||||
|
||||
export const discovery = {
|
||||
type: "cli",
|
||||
kind: "gitlab",
|
||||
label: "GitLab",
|
||||
executable: "glab",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseGitLabAuth,
|
||||
installHint:
|
||||
"Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
|
||||
} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
|
||||
|
||||
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
|
||||
const gitlab = yield* GitLabCli.GitLabCli;
|
||||
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
kind: "gitlab",
|
||||
listChangeRequests: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
return gitlab
|
||||
.listMergeRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
state: input.state,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
gitlab.getMergeRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(input);
|
||||
return gitlab
|
||||
.createMergeRequest({
|
||||
cwd: input.cwd,
|
||||
baseBranch: input.baseRefName,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
...(input.target ? { target: input.target } : {}),
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
gitlab
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
createRepository: (input) =>
|
||||
gitlab
|
||||
.createRepository(input)
|
||||
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
gitlab
|
||||
.getDefaultBranch(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
checkoutChangeRequest: (input) =>
|
||||
gitlab
|
||||
.checkoutMergeRequest(input)
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
|
||||
Loaded 100 of 309 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user