Compare commits

...
Author SHA1 Message Date
Cursor Agent ee9cabf430 fix: prevent mobile composer collapse when portaled floating layers are open
Track open state of CompactComposerControlsMenu and ProviderModelPicker
to set a data-mobile-floating-open attribute on the composer surface.
CSS conditions now include group-data-[mobile-floating-open=true]/composer
so the composer stays expanded while portaled menus/popovers are active.
2026-05-04 17:29:42 +00:00
Julius Marminge 699caa754c Fix mobile composer keyboard focus race
- Replace JS-driven collapse state with a primed mobile focus attribute
- Simplify keyboard expansion flow and update focus sequencing tests
2026-05-04 09:54:51 -07:00
Julius Marminge 34f4646ccf Fix mobile composer focus race on expand
- Extract keyboard expand flow into a helper
- Use flushSync to commit focus state before focusing the editor
- Add a regression test for the expand sequence
2026-05-04 09:36:30 -07:00
91a03e0747 feat(source-control): add Bitbucket & Azure Devops providers (#2473)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-04 00:59:58 -07:00
Julius Marminge d501ebe877 fix version test (#2490) 2026-05-04 05:27:18 +00:00
Julius Marmingeandcodex 3772fa127c feat: Hosted Frontend, Tailscale Integration & SSH Lancher (#2361)
Co-authored-by: codex <[email protected]>
2026-05-03 22:19:15 -07:00
92e340d80c feat(web): collapse mobile composer by default (#1263)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-03 19:48:10 -07:00
174 changed files with 18910 additions and 3427 deletions

No files matched your search

+80
View File
@@ -93,6 +93,8 @@ 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.
@@ -108,6 +110,67 @@ 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.
@@ -151,6 +214,8 @@ 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:
@@ -170,6 +235,8 @@ 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.
@@ -185,6 +252,8 @@ 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:
@@ -227,6 +296,15 @@ 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.
@@ -267,6 +345,8 @@ 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.
+1
View File
@@ -22,3 +22,4 @@ apps/web/src/components/__screenshots__
__screenshots__/
.tanstack
squashfs-root/
.vercel
+350
View File
@@ -0,0 +1,350 @@
# 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`
+76 -1
View File
@@ -22,9 +22,41 @@ 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 address the server is reachable at (e.g. `http://192.168.x.y:3773`).
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.
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.
@@ -47,14 +79,42 @@ 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.
@@ -67,6 +127,20 @@ 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.
@@ -84,4 +158,5 @@ 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.
+4
View File
@@ -15,13 +15,17 @@
"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:",
@@ -72,6 +72,12 @@ 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", () => {
+12 -3
View File
@@ -57,6 +57,12 @@ 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")
);
}
@@ -77,7 +83,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -85,6 +91,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
@@ -134,6 +141,7 @@ export function writeSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
encryptedBearerToken,
}
: record;
@@ -189,7 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -197,7 +205,8 @@ export function writeSavedEnvironmentSecret(input: {
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
+83
View File
@@ -9,6 +9,7 @@ import {
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -35,6 +36,8 @@ 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,
});
@@ -45,12 +48,16 @@ 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,
});
@@ -61,6 +68,8 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -68,6 +77,50 @@ 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,
});
@@ -78,6 +131,8 @@ describe("desktopSettings", () => {
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -85,6 +140,8 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
@@ -103,6 +160,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -121,6 +180,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -140,8 +201,30 @@ 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,
});
});
});
+33
View File
@@ -6,12 +6,18 @@ 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,
};
@@ -35,6 +41,29 @@ 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,
@@ -57,6 +86,8 @@ 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;
};
@@ -72,6 +103,8 @@ 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
+128 -5
View File
@@ -36,11 +36,14 @@ 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";
@@ -55,7 +58,11 @@ import {
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
} from "./serverExposure.ts";
import { DesktopSshEnvironmentBridge, resolveRemoteT3CliPackageSpec } from "./sshEnvironment.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
@@ -76,6 +83,7 @@ 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();
@@ -102,6 +110,8 @@ 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");
@@ -110,6 +120,11 @@ 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(),
@@ -297,6 +312,9 @@ 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;
}
@@ -305,9 +323,32 @@ 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(),
@@ -321,9 +362,19 @@ 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;
@@ -361,6 +412,17 @@ 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(() => {
@@ -373,6 +435,7 @@ function relaunchDesktopApp(reason: string): void {
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
);
})
.then(() => desktopSshEnvironmentBridge.dispose().catch(() => undefined))
.finally(() => {
restoreStdIoCapture?.();
if (isDevelopment) {
@@ -629,6 +692,22 @@ 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";
@@ -1180,7 +1259,10 @@ 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 };
}
@@ -1202,7 +1284,10 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
}
}
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 };
}
@@ -1402,6 +1487,8 @@ function startBackend(): void {
t3Home: BASE_DIR,
host: backendBindHost,
desktopBootstrapToken: backendBootstrapToken,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
@@ -1647,6 +1734,8 @@ function registerIpcHandlers(): void {
},
);
desktopSshEnvironmentBridge.registerIpcHandlers(ipcMain);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
@@ -1669,6 +1758,31 @@ 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;
@@ -1959,7 +2073,10 @@ 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" },
);
}
@@ -2019,6 +2136,9 @@ function createWindow(): BrowserWindow {
}
window.on("closed", () => {
desktopSshEnvironmentBridge.cancelPendingPasswordPrompts(
"SSH authentication was cancelled because the app window closed.",
);
if (mainWindow === window) {
mainWindow = null;
}
@@ -2110,6 +2230,7 @@ app.on("before-quit", () => {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
});
@@ -2159,6 +2280,7 @@ if (process.platform !== "win32") {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
@@ -2169,6 +2291,7 @@ if (process.platform !== "win32") {
writeDesktopLogHeader("SIGTERM received");
clearUpdatePollTimer();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
+59
View File
@@ -22,8 +22,36 @@ 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: () => {
@@ -51,8 +79,39 @@ 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),
+120 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
resolveLanAdvertisedHost,
} from "./serverExposure.ts";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -74,6 +78,121 @@ 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(
+109 -1
View File
@@ -1,5 +1,13 @@
import type { NetworkInterfaceInfo } from "node:os";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
} from "@t3tools/contracts";
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -13,6 +21,26 @@ 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;
@@ -21,6 +49,14 @@ 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,
@@ -78,3 +114,75 @@ 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;
}
+98
View File
@@ -0,0 +1,98 @@
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",
},
]);
});
});
+420
View File
@@ -0,0 +1,420 @@
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."),
);
}
});
}
}
@@ -0,0 +1,122 @@
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.",
},
]);
});
});
@@ -0,0 +1,142 @@
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;
}
+1
View File
@@ -40,6 +40,7 @@
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
+36
View File
@@ -46,6 +46,8 @@ 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(
@@ -87,6 +89,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -108,6 +112,8 @@ 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(
@@ -149,6 +155,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
});
}),
);
@@ -161,6 +169,8 @@ 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"));
@@ -176,6 +186,8 @@ 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(
@@ -212,6 +224,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -229,6 +243,8 @@ 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",
});
@@ -246,6 +262,8 @@ 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(
@@ -281,6 +299,8 @@ 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);
}),
@@ -305,6 +325,8 @@ 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(
@@ -346,6 +368,8 @@ 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"));
@@ -361,6 +385,8 @@ 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(
@@ -399,6 +425,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -432,6 +460,8 @@ 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(
@@ -463,6 +493,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -485,6 +517,8 @@ 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(),
{
@@ -522,6 +556,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
+2
View File
@@ -76,6 +76,8 @@ const makeCliTestServerConfig = (baseDir: string) =>
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
} satisfies ServerConfigShape;
});
+47
View File
@@ -78,6 +78,8 @@ 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),
});
@@ -126,6 +128,17 @@ 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")),
@@ -174,6 +187,14 @@ 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 {
@@ -187,6 +208,8 @@ 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 {
@@ -233,6 +256,8 @@ 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 =
@@ -323,6 +348,22 @@ 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(
@@ -365,6 +406,8 @@ export const resolveServerConfig = (
desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
tailscaleServePort,
};
return config;
@@ -386,6 +429,8 @@ const resolveCliAuthConfig = (
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
cliLogLevel,
);
@@ -766,6 +811,8 @@ const sharedServerCommandFlags = {
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
tailscaleServeEnabled: tailscaleServeFlag,
tailscaleServePort: tailscaleServePortFlag,
} as const;
const authLocationFlags = sharedServerLocationFlags;
+4
View File
@@ -65,6 +65,8 @@ 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* (
@@ -158,6 +160,8 @@ 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,6 +30,8 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
+1
View File
@@ -655,6 +655,7 @@ function makeManager(input?: {
get: () => Effect.succeed(provider),
resolveHandle: () => Effect.succeed({ provider, context: null }),
resolve: () => Effect.succeed(provider),
discover: Effect.succeed([]),
}),
),
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
+18 -19
View File
@@ -1,28 +1,27 @@
import { assert, it } from "@effect/vitest";
import { assert, describe, it, vi } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { describe, vi } from "vitest";
import { GitManager } from "./GitManager.ts";
import { GitWorkflowService, layer as GitWorkflowServiceLayer } from "./GitWorkflowService.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry, type VcsDriverRegistryShape } from "../vcs/VcsDriverRegistry.ts";
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: VcsDriverRegistryShape["detect"] }) {
return GitWorkflowServiceLayer.pipe(
function makeLayer(input: { readonly detect: VcsDriverRegistry.VcsDriverRegistryShape["detect"] }) {
return GitWorkflowService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry)({
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
detect: input.detect,
}),
),
Layer.provide(Layer.mock(GitVcsDriver)({})),
Layer.provide(Layer.mock(GitManager)({})),
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;
const workflow = yield* GitWorkflowService.GitWorkflowService;
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
assert.deepStrictEqual(status, {
@@ -48,7 +47,7 @@ describe("GitWorkflowService", () => {
it.effect("returns an empty full status when no VCS repository is detected", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService;
const workflow = yield* GitWorkflowService.GitWorkflowService;
const status = yield* workflow.status({ cwd: "/not-a-repo" });
assert.deepStrictEqual(status, {
@@ -82,15 +81,15 @@ describe("GitWorkflowService", () => {
const remoteStatus = vi.fn();
const status = vi.fn();
const testLayer = GitWorkflowServiceLayer.pipe(
const testLayer = GitWorkflowService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry)({
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
detect: () => Effect.succeed(null),
}),
),
Layer.provide(Layer.mock(GitVcsDriver)({})),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
Layer.provide(
Layer.mock(GitManager)({
Layer.mock(GitManager.GitManager)({
localStatus,
remoteStatus,
status,
@@ -99,7 +98,7 @@ describe("GitWorkflowService", () => {
);
return Effect.gen(function* () {
const workflow = yield* GitWorkflowService;
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" });
@@ -112,7 +111,7 @@ describe("GitWorkflowService", () => {
it.effect("returns an empty ref list when no VCS repository is detected", () =>
Effect.gen(function* () {
const workflow = yield* GitWorkflowService;
const workflow = yield* GitWorkflowService.GitWorkflowService;
const refs = yield* workflow.listRefs({ cwd: "/not-a-repo" });
assert.deepStrictEqual(refs, {
+13 -277
View File
@@ -13,14 +13,10 @@ import {
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
MAX_WHEN_EXPRESSION_DEPTH,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
THREAD_JUMP_KEYBINDING_COMMANDS,
type ServerConfigIssue,
} from "@t3tools/contracts";
import type { Mutable } from "effect/Types";
import {
Array,
Cache,
@@ -48,278 +44,20 @@ 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";
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 {
DEFAULT_KEYBINDINGS,
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
};
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Schema.decodeTo(
@@ -412,8 +150,6 @@ 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(
+53 -35
View File
@@ -75,6 +75,7 @@ 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,
@@ -104,23 +105,12 @@ 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 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 VcsProvisioningServiceLayer } from "./vcs/VcsProvisioningService.ts";
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
import {
SourceControlRepositoryService,
type SourceControlRepositoryServiceShape,
} from "./sourceControl/SourceControlRepositoryService.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 { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
@@ -217,10 +207,8 @@ const browserOtlpTracingLayer = Layer.mergeAll(
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
);
const authTestLayer = ServerAuthLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStoreLive),
);
const makeAuthTestLayer = () =>
ServerAuthLive.pipe(Layer.provide(SqlitePersistenceMemory), Layer.provide(ServerSecretStoreLive));
const makeBrowserOtlpPayload = (spanName: string) =>
Effect.gen(function* () {
@@ -330,12 +318,12 @@ const buildAppUnderTest = (options?: {
providerRegistry?: Partial<ProviderRegistryShape>;
serverSettings?: Partial<ServerSettingsShape>;
open?: Partial<OpenShape>;
vcsDriver?: Partial<VcsDriverShape>;
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
vcsDriver?: Partial<VcsDriver.VcsDriverShape>;
vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>;
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
gitManager?: Partial<GitManagerShape>;
sourceControlRepositoryService?: Partial<SourceControlRepositoryServiceShape>;
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>;
vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>;
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
terminalManager?: Partial<TerminalManagerShape>;
orchestrationEngine?: Partial<OrchestrationEngineShape>;
@@ -378,10 +366,12 @@ const buildAppUnderTest = (options?: {
desktopBootstrapToken: defaultDesktopBootstrapToken,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
...options?.config,
};
const layerConfig = Layer.succeed(ServerConfig, config);
const defaultVcsDriver: VcsDriverShape = {
const defaultVcsDriver: VcsDriver.VcsDriverShape = {
capabilities: {
kind: "git",
supportsWorktrees: true,
@@ -423,7 +413,7 @@ const buildAppUnderTest = (options?: {
initRepository: () => Effect.void,
...options?.layers?.vcsDriver,
};
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry)({
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
get: () => Effect.succeed(defaultVcsDriver),
detect: (input) =>
defaultVcsDriver.detectRepository(input.cwd).pipe(
@@ -453,7 +443,7 @@ const buildAppUnderTest = (options?: {
kind: repository.kind,
repository,
driver: defaultVcsDriver,
} satisfies VcsDriverHandle)
} satisfies VcsDriverRegistry.VcsDriverHandle)
: null,
),
),
@@ -495,19 +485,19 @@ const buildAppUnderTest = (options?: {
),
ProjectFaviconResolverLive,
);
const gitWorkflowLayer = GitWorkflowServiceLayer.pipe(
const gitWorkflowLayer = GitWorkflowService.layer.pipe(
Layer.provideMerge(vcsDriverRegistryLayer),
Layer.provideMerge(gitVcsDriverLayer),
Layer.provideMerge(gitManagerLayer),
);
const vcsProvisioningLayer = VcsProvisioningServiceLayer.pipe(
const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(
Layer.provide(vcsDriverRegistryLayer),
);
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
? Layer.mock(VcsStatusBroadcaster)({
? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
...options.layers.vcsStatusBroadcaster,
})
: VcsStatusBroadcasterLayer.pipe(Layer.provide(gitWorkflowLayer));
: VcsStatusBroadcaster.layer.pipe(Layer.provide(gitWorkflowLayer));
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
disableListenLog: true,
@@ -551,7 +541,7 @@ const buildAppUnderTest = (options?: {
Layer.provide(gitWorkflowLayer),
Layer.provide(vcsProvisioningLayer),
Layer.provide(
Layer.mock(SourceControlRepositoryService)({
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
...options?.layers?.sourceControlRepositoryService,
}),
),
@@ -653,7 +643,7 @@ const buildAppUnderTest = (options?: {
...options?.layers?.repositoryIdentityResolver,
}),
),
Layer.provideMerge(authTestLayer),
Layer.provideMerge(makeAuthTestLayer()),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(layerConfig),
@@ -2021,7 +2011,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.deepEqual(second, {
version: 1,
type: "keybindingsUpdated",
payload: { issues: [] },
payload: { keybindings: [], issues: [] },
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -3110,6 +3100,34 @@ 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 = {
+60 -1
View File
@@ -25,6 +25,8 @@ 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";
@@ -83,6 +85,7 @@ 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* () {
@@ -163,7 +166,10 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
);
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
Layer.provide(
Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
@@ -234,6 +240,7 @@ 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),
@@ -334,6 +341,57 @@ 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, {
@@ -341,6 +399,7 @@ export const makeServerLayer = Layer.unwrap(
}),
httpListeningLayer,
runtimeStateLayer,
tailscaleServeLayer,
);
return serverApplicationLayer.pipe(
@@ -0,0 +1,288 @@
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)),
);
});
@@ -0,0 +1,429 @@
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());
@@ -0,0 +1,91 @@
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");
}),
);
@@ -0,0 +1,144 @@
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());
@@ -0,0 +1,513 @@
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: () => Response.json(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("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));
});
@@ -0,0 +1,703 @@
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 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: Schema.Schema.Type<typeof RawBitbucketRepositorySchema>,
): 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 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 getRepository = (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly repository?: string;
}) =>
resolveRepository(input).pipe(
Effect.flatMap((repository) =>
executeJson(
"getRepository",
HttpClientRequest.get(
apiUrl(
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
),
),
RawBitbucketRepositorySchema,
),
),
);
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) =>
getRepository(input).pipe(Effect.map((repository) => repository.mainbranch?.name ?? null)),
// 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());
@@ -0,0 +1,126 @@
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");
}),
);
@@ -0,0 +1,126 @@
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,13 +1,12 @@
import { assert, it } from "@effect/vitest";
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 { afterEach, describe, expect, vi } from "vitest";
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
const processOutput = (stdout: string): VcsProcessOutput => ({
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
@@ -15,11 +14,11 @@ const processOutput = (stdout: string): VcsProcessOutput => ({
stderrTruncated: false,
});
const mockRun = vi.fn<(input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>>();
const mockRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
const layer = GitHubCli.layer.pipe(
Layer.provide(
Layer.mock(VcsProcess)({
Layer.mock(VcsProcess.VcsProcess)({
run: mockRun,
}),
),
+8 -12
View File
@@ -6,12 +6,8 @@ import {
type VcsError,
} from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "./gitHubPullRequests.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -48,7 +44,7 @@ export interface GitHubCliShape {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcessOutput, GitHubCliError>;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
readonly listOpenPullRequests: (input: {
readonly cwd: string;
@@ -226,7 +222,7 @@ function decodeGitHubJson<S extends Schema.Top>(
}
export const make = Effect.fn("makeGitHubCli")(function* () {
const process = yield* VcsProcess;
const process = yield* VcsProcess.VcsProcess;
const execute: GitHubCliShape["execute"] = (input) =>
process
@@ -261,13 +257,13 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
: Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "listOpenPullRequests",
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
detail: `GitHub CLI returned invalid PR list JSON: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -293,13 +289,13 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "getPullRequest",
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
detail: `GitHub CLI returned invalid pull request JSON: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -2,11 +2,11 @@ import { assert, it } from "@effect/vitest";
import { DateTime, Effect, Layer, Option } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
import type { VcsProcessOutput } from "../vcs/VcsProcess.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
const processResult = (stdout: string): VcsProcessOutput => ({
const processResult = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
@@ -14,8 +14,10 @@ const processResult = (stdout: string): VcsProcessOutput => ({
stderrTruncated: false,
});
function makeProvider(github: Partial<GitHubCliShape>) {
return GitHubSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitHubCli)(github)));
function makeProvider(github: Partial<GitHubCli.GitHubCliShape>) {
return GitHubSourceControlProvider.make().pipe(
Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
);
}
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
@@ -127,7 +129,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<GitHubCliShape["createPullRequest"]>[0] | null = null;
let createInput: Parameters<GitHubCli.GitHubCliShape["createPullRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createPullRequest: (input) => {
createInput = input;
@@ -5,11 +5,15 @@ import {
type ChangeRequestState,
} from "@t3tools/contracts";
import { GitHubCli, type GitHubCliError, type GitHubPullRequestSummary } from "./GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
function providerError(
operation: string,
cause: GitHubCli.GitHubCliError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "github",
operation,
@@ -18,7 +22,7 @@ function providerError(operation: string, cause: GitHubCliError): SourceControlP
});
}
function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
return {
provider: "github",
number: summary.number,
@@ -40,75 +44,119 @@ function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
};
}
export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
const github = yield* GitHubCli;
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);
const listChangeRequests: SourceControlProviderShape["listChangeRequests"] = (input) => {
if (input.state === "open") {
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 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;
return github
.listOpenPullRequests({
.execute({
cwd: input.cwd,
headSelector: input.headSelector,
...(input.limit !== undefined ? { limit: input.limit } : {}),
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.map((items) => items.map(toChangeRequest)),
Effect.mapError((error) => providerError("listChangeRequests", error)),
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),
),
);
}
};
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({
return SourceControlProvider.SourceControlProvider.of({
kind: "github",
listChangeRequests,
getChangeRequest: (input) =>
@@ -145,4 +193,4 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
});
});
export const layer = Layer.effect(SourceControlProvider, make());
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
@@ -1,25 +1,24 @@
import { assert, it } from "@effect/vitest";
import { assert, it, afterEach, expect, vi } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { afterEach, expect, vi } from "vitest";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput, type VcsProcessShape } from "../vcs/VcsProcess.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitLabCli from "./GitLabCli.ts";
const mockedRun = vi.fn<VcsProcessShape["run"]>();
const mockedRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
const layer = it.layer(
GitLabCli.layer.pipe(
Layer.provide(
Layer.mock(VcsProcess)({
Layer.mock(VcsProcess.VcsProcess)({
run: mockedRun,
}),
),
),
);
function processOutput(stdout: string): VcsProcessOutput {
function processOutput(stdout: string): VcsProcess.VcsProcessOutput {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
+16 -18
View File
@@ -2,13 +2,9 @@ import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateT
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
import {
decodeGitLabMergeRequestJson,
decodeGitLabMergeRequestListJson,
formatGitLabJsonDecodeError,
} from "./gitLabMergeRequests.ts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import type { SourceControlRefSelector } from "./SourceControlProvider.ts";
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;
@@ -46,12 +42,12 @@ export interface GitLabCliShape {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcessOutput, GitLabCliError>;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
readonly listMergeRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly state: "open" | "closed" | "merged" | "all";
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
@@ -76,8 +72,8 @@ export interface GitLabCliShape {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly target?: SourceControlRefSelector;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly target?: SourceControlProvider.SourceControlRefSelector;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitLabCliError>;
@@ -220,12 +216,14 @@ function normalizeHeadSelector(headSelector: string): string {
function sourceRefName(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly source?: SourceControlProvider.SourceControlRefSelector;
}): string {
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
}
function sourceProjectIdentifier(source: SourceControlRefSelector | undefined): string | null {
function sourceProjectIdentifier(
source: SourceControlProvider.SourceControlRefSelector | undefined,
): string | null {
return source?.repository ?? source?.owner ?? null;
}
@@ -252,7 +250,7 @@ function parseRepositoryPath(repository: string): {
}
export const make = Effect.fn("makeGitLabCli")(function* () {
const process = yield* VcsProcess;
const process = yield* VcsProcess.VcsProcess;
const execute: GitLabCliShape["execute"] = (input) =>
process
@@ -286,13 +284,13 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
: 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: ${formatGitLabJsonDecodeError(decoded.failure)}`,
detail: `GitLab CLI returned invalid MR list JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -310,13 +308,13 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
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: ${formatGitLabJsonDecodeError(decoded.failure)}`,
detail: `GitLab CLI returned invalid merge request JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -1,11 +1,13 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import { GitLabCli, type GitLabCliShape } from "./GitLabCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
function makeProvider(gitlab: Partial<GitLabCliShape>) {
return GitLabSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitLabCli)(gitlab)));
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", () =>
@@ -48,7 +50,7 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
it.effect("lists GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let listInput: Parameters<GitLabCliShape["listMergeRequests"]>[0] | null = null;
let listInput: Parameters<GitLabCli.GitLabCliShape["listMergeRequests"]>[0] | null = null;
const provider = yield* makeProvider({
listMergeRequests: (input) => {
listInput = input;
@@ -74,7 +76,7 @@ it.effect("lists GitLab MRs through provider-neutral input names", () =>
it.effect("creates GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<GitLabCliShape["createMergeRequest"]>[0] | null = null;
let createInput: Parameters<GitLabCli.GitLabCliShape["createMergeRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createMergeRequest: (input) => {
createInput = input;
@@ -1,10 +1,14 @@
import { Effect, Layer, Option } from "effect";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import { GitLabCli, type GitLabCliError, type GitLabMergeRequestSummary } from "./GitLabCli.ts";
import { SourceControlProvider, type SourceControlRefSelector } from "./SourceControlProvider.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(operation: string, cause: GitLabCliError): SourceControlProviderError {
function providerError(
operation: string,
cause: GitLabCli.GitLabCliError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "gitlab",
operation,
@@ -13,7 +17,7 @@ function providerError(operation: string, cause: GitLabCliError): SourceControlP
});
}
function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
return {
provider: "gitlab",
number: summary.number,
@@ -35,27 +39,57 @@ function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
};
}
function sourceFromInput(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): SourceControlRefSelector | undefined {
if (input.source) {
return input.source;
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.",
});
}
const match = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
const owner = match?.[1]?.trim();
const refName = match?.[2]?.trim();
return owner && refName ? { owner, refName } : undefined;
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 make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
const gitlab = yield* GitLabCli;
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;
return SourceControlProvider.of({
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
const gitlab = yield* GitLabCli.GitLabCli;
return SourceControlProvider.SourceControlProvider.of({
kind: "gitlab",
listChangeRequests: (input) => {
const source = sourceFromInput(input);
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
.listMergeRequests({
cwd: input.cwd,
@@ -75,7 +109,7 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) => {
const source = sourceFromInput(input);
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
.createMergeRequest({
cwd: input.cwd,
@@ -107,4 +141,4 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
});
});
export const layer = Layer.effect(SourceControlProvider, make());
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
@@ -5,8 +5,34 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessSpawnError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { SourceControlDiscovery, layer } from "./SourceControlDiscovery.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
const sourceControlProviderRegistryTestLayer = (input: {
readonly bitbucket: Partial<BitbucketApi.BitbucketApiShape>;
readonly process: Partial<VcsProcess.VcsProcessShape>;
}) =>
SourceControlProviderRegistry.layer.pipe(
Layer.provide(
Layer.mergeAll(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-registry-test-" }).pipe(
Layer.provide(NodeServices.layer),
),
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
Layer.mock(VcsProcess.VcsProcess)(input.process),
),
),
);
const processOutput = (
stdout: string,
@@ -22,39 +48,53 @@ const processOutput = (
stderrTruncated: false,
});
it.effect("reports implemented tools separately from locally available CLIs", () => {
const testLayer = layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
),
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) => {
if (input.command === "git") {
return Effect.succeed(processOutput("git version 2.51.0\n"));
}
if (input.command === "gh" && input.args[0] === "--version") {
return Effect.succeed(processOutput("gh version 2.83.0\n"));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
it.effect("reports implemented tools separately from locally available executables", () => {
const processMock = {
run: (input: VcsProcess.VcsProcessInput) => {
if (input.command === "git") {
return Effect.succeed(processOutput("git version 2.51.0\n"));
}
if (input.command === "gh" && input.args[0] === "--version") {
return Effect.succeed(processOutput("gh version 2.83.0\n"));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
Logged in to github.com account juliusmarminge (keyring)
- Active account: true
- Git operations protocol: ssh
- Token: gho_************************************
- Token scopes: 'admin:public_key', 'gist', 'read:org', 'repo'
`),
);
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
);
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
},
} satisfies Partial<VcsProcess.VcsProcessShape>;
const testLayer = SourceControlDiscovery.layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
),
Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
Layer.provide(
sourceControlProviderRegistryTestLayer({
process: processMock,
bitbucket: {
probeAuth: Effect.succeed({
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.",
),
}),
},
}),
),
@@ -62,7 +102,7 @@ Logged in to github.com account juliusmarminge (keyring)
);
return Effect.gen(function* () {
const discovery = yield* SourceControlDiscovery;
const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
const result = yield* discovery.discover;
assert.deepStrictEqual(
@@ -79,7 +119,6 @@ Logged in to github.com account juliusmarminge (keyring)
assert.deepStrictEqual(
result.sourceControlProviders.map((item) => ({
kind: item.kind,
implemented: item.implemented,
status: item.status,
auth: item.auth.status,
account: item.auth.account,
@@ -87,88 +126,89 @@ Logged in to github.com account juliusmarminge (keyring)
[
{
kind: "github",
implemented: true,
status: "available",
auth: "authenticated",
account: Option.some("juliusmarminge"),
},
{
kind: "gitlab",
implemented: true,
status: "missing",
auth: "unknown",
account: Option.none(),
},
{
kind: "azure-devops",
implemented: false,
status: "missing",
auth: "unknown",
account: Option.none(),
},
{
kind: "bitbucket",
implemented: false,
status: "missing",
auth: "unknown",
status: "available",
auth: "unauthenticated",
account: Option.none(),
},
],
);
const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
assert.ok(bitbucket);
assert.strictEqual("executable" in bitbucket, false);
assert.strictEqual(bitbucket.executable, undefined);
}).pipe(Effect.provide(testLayer));
});
it.effect("probes provider authentication without exposing token details", () => {
const testLayer = layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-auth-discovery-" }),
),
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) => {
if (input.args[0] === "--version") {
return Effect.succeed(processOutput(`${input.command} version test\n`));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
const processMock = {
run: (input: VcsProcess.VcsProcessInput) => {
if (input.args[0] === "--version") {
return Effect.succeed(processOutput(`${input.command} version test\n`));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
Logged in to github.com account octocat (keyring)
- Token: gho_************************************
- Token scopes: 'repo'
`),
);
}
if (input.command === "glab" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`gitlab.com
);
}
if (input.command === "glab" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`gitlab.com
Logged in to gitlab.com as gitlab-user
`),
);
}
if (
input.command === "az" &&
input.args.join(" ") === "account show --query user.name -o tsv"
) {
return Effect.succeed(processOutput("[email protected]\n"));
}
if (input.command === "bb" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`bitbucket.org
Logged in as bitbucket-user
`),
);
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
);
}
if (
input.command === "az" &&
input.args.join(" ") === "account show --query user.name -o tsv"
) {
return Effect.succeed(processOutput("[email protected]\n"));
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
},
} satisfies Partial<VcsProcess.VcsProcessShape>;
const testLayer = SourceControlDiscovery.layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-auth-discovery-" }),
),
Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
Layer.provide(
sourceControlProviderRegistryTestLayer({
process: processMock,
bitbucket: {
probeAuth: Effect.succeed({
status: "authenticated",
account: Option.some("bitbucket-user"),
host: Option.some("bitbucket.org"),
detail: Option.none(),
}),
},
}),
),
@@ -176,7 +216,7 @@ Logged in as bitbucket-user
);
return Effect.gen(function* () {
const discovery = yield* SourceControlDiscovery;
const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
const result = yield* discovery.discover;
assert.deepStrictEqual(
@@ -207,9 +247,9 @@ Logged in as bitbucket-user
},
{
kind: "bitbucket",
auth: "unknown",
account: Option.none(),
detail: Option.some("Bitbucket provider support is not available yet."),
auth: "authenticated",
account: Option.some("bitbucket-user"),
detail: Option.none(),
},
],
);
@@ -1,8 +1,5 @@
import {
type SourceControlProviderAuth,
type SourceControlDiscoveryResult,
type SourceControlProviderDiscoveryItem,
type SourceControlProviderKind,
type VcsDiscoveryItem,
type VcsDriverKind,
} from "@t3tools/contracts";
@@ -10,6 +7,8 @@ import { Context, Effect, Layer, Option } from "effect";
import { ServerConfig } from "../config.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
interface DiscoveryProbe {
readonly label: string;
@@ -25,18 +24,6 @@ type VcsProbe = DiscoveryProbe & {
readonly versionArgs: ReadonlyArray<string>;
};
type ProviderProbe = DiscoveryProbe & {
readonly kind: SourceControlProviderKind;
readonly authArgs?: ReadonlyArray<string>;
readonly parseAuth?: (input: AuthProbeInput) => SourceControlProviderAuth;
};
interface AuthProbeInput {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
}
interface DiscoveryProbeResult<Kind extends string> {
readonly kind: Kind;
readonly label: string;
@@ -67,203 +54,6 @@ const VCS_PROBES: ReadonlyArray<VcsProbe> = [
},
];
const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
{
kind: "github",
label: "GitHub",
executable: "gh",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitHubAuth,
implemented: true,
installHint: "Install GitHub CLI with `brew install gh` or from https://cli.github.com/.",
},
{
kind: "gitlab",
label: "GitLab",
executable: "glab",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitLabAuth,
implemented: true,
installHint:
"Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.",
},
{
kind: "azure-devops",
label: "Azure DevOps",
executable: "az",
versionArgs: ["--version"],
authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
parseAuth: parseAzureAuth,
implemented: false,
installHint:
"Install Azure CLI with `brew install azure-cli`, then add Azure DevOps support with `az extension add --name azure-devops`.",
},
{
kind: "bitbucket",
label: "Bitbucket",
implemented: false,
installHint: "Bitbucket provider support is not available yet.",
},
];
function firstNonEmptyLine(text: string): Option.Option<string> {
const line = text
.split(/\r?\n/)
.map((entry) => entry.trim())
.find((entry) => entry.length > 0);
return line === undefined ? Option.none() : Option.some(line);
}
function detailFromCause(cause: unknown): Option.Option<string> {
if (cause instanceof Error && cause.message.trim().length > 0) {
return Option.some(cause.message.trim());
}
return Option.none();
}
function authAccount(account: string | undefined): Option.Option<string> {
const trimmed = account?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authHost(host: string | undefined): Option.Option<string> {
const trimmed = host?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authDetail(detail: string | undefined): Option.Option<string> {
const trimmed = detail?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function providerAuth(input: {
readonly status: SourceControlProviderAuth["status"];
readonly account?: string | undefined;
readonly host?: string | undefined;
readonly detail?: string | undefined;
}): SourceControlProviderAuth {
return {
status: input.status,
account: authAccount(input.account),
host: authHost(input.host),
detail: authDetail(input.detail),
};
}
function unknownAuth(detail?: string): SourceControlProviderAuth {
return providerAuth({ status: "unknown", detail });
}
function combinedAuthOutput(input: AuthProbeInput): string {
return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
}
function sanitizedAuthLines(text: string): ReadonlyArray<string> {
return text
.split(/\r?\n/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
}
function firstSafeAuthLine(text: string): string | undefined {
return sanitizedAuthLines(text)[0];
}
function parseCliHost(text: string): string | undefined {
return sanitizedAuthLines(text)
.map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
.find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
}
function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
for (const pattern of patterns) {
const match = pattern.exec(text);
const value = match?.[1]?.trim();
if (value && value.length > 0) return value;
}
return undefined;
}
function parseGitHubAuth(input: AuthProbeInput): SourceControlProviderAuth {
const output = combinedAuthOutput(input);
const account = matchFirst(output, [
/Logged in to .* account\s+([^\s(]+)/iu,
/Logged in to .* as\s+([^\s(]+)/iu,
]);
const host = parseCliHost(output);
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
host,
detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
});
}
if (account) {
return providerAuth({ status: "authenticated", account, host });
}
return providerAuth({
status: "unknown",
host,
detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
});
}
function parseGitLabAuth(input: AuthProbeInput): SourceControlProviderAuth {
const output = combinedAuthOutput(input);
const account = matchFirst(output, [
/Logged in to .* as\s+([^\s(]+)/iu,
/Logged in to .* account\s+([^\s(]+)/iu,
/account:\s*([^\s(]+)/iu,
]);
const host = parseCliHost(output);
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
host,
detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
});
}
if (account) {
return providerAuth({ status: "authenticated", account, host });
}
return providerAuth({
status: "unknown",
host,
detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
});
}
function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
detail:
firstSafeAuthLine(combinedAuthOutput(input)) ?? "Run `az login` to authenticate Azure CLI.",
});
}
if (account && account.length > 0) {
return providerAuth({ status: "authenticated", account, host: "dev.azure.com" });
}
return providerAuth({
status: "unknown",
host: "dev.azure.com",
detail: "Azure CLI account status could not be parsed.",
});
}
export interface SourceControlDiscoveryShape {
readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
}
@@ -278,8 +68,10 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const config = yield* ServerConfig;
const process = yield* VcsProcess.VcsProcess;
const sourceControlProviders =
yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
const probe = <Kind extends VcsDriverKind>(
input: DiscoveryProbe & { readonly kind: Kind },
): Effect.Effect<DiscoveryProbeResult<Kind>> => {
const executable = input.executable;
@@ -316,8 +108,9 @@ export const layer = Layer.effect(
executable,
implemented: input.implemented,
status: "available" as const,
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
firstNonEmptyLine(result.stderr),
version: Option.orElse(
SourceControlProviderDiscovery.firstNonEmptyLine(result.stdout),
() => SourceControlProviderDiscovery.firstNonEmptyLine(result.stderr),
),
installHint: input.installHint,
detail: Option.none<string>(),
@@ -332,74 +125,19 @@ export const layer = Layer.effect(
status: "missing" as const,
version: Option.none<string>(),
installHint: input.installHint,
detail: detailFromCause(cause),
detail: SourceControlProviderDiscovery.detailFromCause(cause),
} satisfies DiscoveryProbeResult<Kind>),
),
);
};
const probeProvider = (input: ProviderProbe) =>
probe(input).pipe(
Effect.flatMap((item) => {
const executable = input.executable;
const authArgs = input.authArgs;
const parseAuth = input.parseAuth;
if (!executable || !authArgs || !parseAuth) {
return Effect.succeed({
...item,
auth: unknownAuth(input.installHint),
} satisfies SourceControlProviderDiscoveryItem);
}
if (item.status !== "available") {
return Effect.succeed({
...item,
auth: unknownAuth("CLI is not installed."),
} satisfies SourceControlProviderDiscoveryItem);
}
return process
.run({
operation: "source-control.discovery.auth",
command: executable,
args: authArgs,
cwd: config.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
...item,
auth: parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
Effect.succeed({
...item,
auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
} satisfies SourceControlProviderDiscoveryItem),
),
);
}),
);
return SourceControlDiscovery.of({
discover: Effect.all({
versionControlSystems: Effect.all(
VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray<Effect.Effect<VcsDiscoveryItem>>,
{ concurrency: "unbounded" },
),
sourceControlProviders: Effect.all(
SOURCE_CONTROL_PROVIDER_PROBES.map((entry) => probeProvider(entry)) as ReadonlyArray<
Effect.Effect<SourceControlProviderDiscoveryItem>
>,
{ concurrency: "unbounded" },
),
sourceControlProviders: sourceControlProviders.discover,
}),
});
}),
@@ -21,6 +21,33 @@ export interface SourceControlRefSelector {
readonly repository?: string;
}
export function parseSourceControlOwnerRef(
headSelector: string,
): SourceControlRefSelector | undefined {
const match = /^([^:/\s]+):(.+)$/u.exec(headSelector.trim());
const owner = match?.[1]?.trim();
const refName = match?.[2]?.trim();
return owner && refName ? { owner, refName } : undefined;
}
export function normalizeSourceBranch(headSelector: string): string {
return parseSourceControlOwnerRef(headSelector)?.refName ?? headSelector.trim();
}
export function sourceBranch(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): string {
return input.source?.refName ?? normalizeSourceBranch(input.headSelector);
}
export function sourceControlRefFromInput(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): SourceControlRefSelector | undefined {
return input.source ?? parseSourceControlOwnerRef(input.headSelector);
}
export interface SourceControlProviderShape {
readonly kind: SourceControlProviderKind;
readonly listChangeRequests: (input: {
@@ -0,0 +1,237 @@
import type {
SourceControlProviderAuth,
SourceControlProviderDiscoveryItem,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { Effect, Option } from "effect";
import type * as VcsProcess from "../vcs/VcsProcess.ts";
export interface SourceControlAuthProbeInput {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
}
interface SourceControlDiscoverySpecBase {
readonly kind: SourceControlProviderKind;
readonly label: string;
readonly installHint: string;
}
export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly type: "cli";
readonly executable: string;
readonly versionArgs: ReadonlyArray<string>;
readonly authArgs: ReadonlyArray<string>;
readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
};
export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly type: "api";
readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
};
export type SourceControlProviderDiscoverySpec =
| SourceControlCliDiscoverySpec
| SourceControlApiDiscoverySpec;
interface DiscoveryProbeResult {
readonly kind: SourceControlProviderKind;
readonly label: string;
readonly executable: string;
readonly status: "available" | "missing";
readonly version: Option.Option<string>;
readonly installHint: string;
readonly detail: Option.Option<string>;
}
export function firstNonEmptyLine(text: string): Option.Option<string> {
const line = text
.split(/\r?\n/)
.map((entry) => entry.trim())
.find((entry) => entry.length > 0);
return line === undefined ? Option.none() : Option.some(line);
}
export function detailFromCause(cause: unknown): Option.Option<string> {
if (cause instanceof Error && cause.message.trim().length > 0) {
return Option.some(cause.message.trim());
}
return Option.none();
}
function authAccount(account: string | undefined): Option.Option<string> {
const trimmed = account?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authHost(host: string | undefined): Option.Option<string> {
const trimmed = host?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authDetail(detail: string | undefined): Option.Option<string> {
const trimmed = detail?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
export function providerAuth(input: {
readonly status: SourceControlProviderAuth["status"];
readonly account?: string | undefined;
readonly host?: string | undefined;
readonly detail?: string | undefined;
}): SourceControlProviderAuth {
return {
status: input.status,
account: authAccount(input.account),
host: authHost(input.host),
detail: authDetail(input.detail),
};
}
export function unknownAuth(detail?: string): SourceControlProviderAuth {
return providerAuth({ status: "unknown", detail });
}
export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
}
function sanitizedAuthLines(text: string): ReadonlyArray<string> {
return text
.split(/\r?\n/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
}
export function firstSafeAuthLine(text: string): string | undefined {
return sanitizedAuthLines(text)[0];
}
export function parseCliHost(text: string): string | undefined {
return sanitizedAuthLines(text)
.map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
.find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
}
export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
for (const pattern of patterns) {
const match = pattern.exec(text);
const value = match?.[1]?.trim();
if (value && value.length > 0) return value;
}
return undefined;
}
function probeCli(input: {
readonly spec: SourceControlCliDiscoverySpec;
readonly process: VcsProcess.VcsProcessShape;
readonly cwd: string;
}): Effect.Effect<DiscoveryProbeResult> {
return input.process
.run({
operation: "source-control.discovery.probe",
command: input.spec.executable,
args: input.spec.versionArgs,
cwd: input.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
kind: input.spec.kind,
label: input.spec.label,
executable: input.spec.executable,
status: "available" as const,
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
firstNonEmptyLine(result.stderr),
),
installHint: input.spec.installHint,
detail: Option.none<string>(),
}) satisfies DiscoveryProbeResult,
),
Effect.catch((cause) =>
Effect.succeed({
kind: input.spec.kind,
label: input.spec.label,
executable: input.spec.executable,
status: "missing" as const,
version: Option.none<string>(),
installHint: input.spec.installHint,
detail: detailFromCause(cause),
} satisfies DiscoveryProbeResult),
),
);
}
export function probeSourceControlProvider(input: {
readonly spec: SourceControlProviderDiscoverySpec;
readonly process: VcsProcess.VcsProcessShape;
readonly cwd: string;
}): Effect.Effect<SourceControlProviderDiscoveryItem> {
if (input.spec.type === "api") {
return input.spec.probeAuth.pipe(
Effect.map(
(auth) =>
({
kind: input.spec.kind,
label: input.spec.label,
status: "available" as const,
version: Option.none<string>(),
installHint: input.spec.installHint,
detail: Option.none<string>(),
auth,
}) satisfies SourceControlProviderDiscoveryItem,
),
);
}
const spec = input.spec;
return probeCli({
spec,
process: input.process,
cwd: input.cwd,
}).pipe(
Effect.flatMap((item) => {
if (item.status !== "available") {
return Effect.succeed({
...item,
auth: unknownAuth("Hosting integration command was not found on the server PATH."),
} satisfies SourceControlProviderDiscoveryItem);
}
return input.process
.run({
operation: "source-control.discovery.auth",
command: spec.executable,
args: spec.authArgs,
cwd: input.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
...item,
auth: spec.parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
Effect.succeed({
...item,
auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
} satisfies SourceControlProviderDiscoveryItem),
),
);
}),
);
}
@@ -1,11 +1,16 @@
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { DateTime, Effect, Layer, Option } from "effect";
import { GitHubCli } from "./GitHubCli.ts";
import { GitLabCli } from "./GitLabCli.ts";
import { ServerConfig } from "../config.ts";
import type * as VcsDriver from "../vcs/VcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
@@ -29,10 +34,10 @@ function makeRegistry(input: {
expiresAt: Option.none(),
},
}),
} satisfies Partial<VcsDriverShape>;
} satisfies Partial<VcsDriver.VcsDriverShape>;
const registryLayer = Layer.mock(VcsDriverRegistry)({
get: () => Effect.succeed(driver as unknown as VcsDriverShape),
const registryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriverShape),
resolve: () =>
Effect.succeed({
kind: "git",
@@ -46,13 +51,23 @@ function makeRegistry(input: {
expiresAt: Option.none(),
},
},
driver: driver as unknown as VcsDriverShape,
driver: driver as unknown as VcsDriver.VcsDriverShape,
}),
});
return SourceControlProviderRegistry.make().pipe(
Effect.provide(
Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}), Layer.mock(GitLabCli)({})),
Layer.mergeAll(
registryLayer,
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)({}),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(VcsProcess.VcsProcess)({}),
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-registry-test-" }).pipe(
Layer.provide(NodeServices.layer),
),
),
),
);
}
@@ -93,6 +108,30 @@ it.effect("routes GitLab remotes to the GitLab provider", () =>
}),
);
it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:pingdotgg/t3code.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "bitbucket");
}),
);
it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "azure-devops");
}),
);
it.effect("falls back to a non-origin remote when origin is not configured", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
@@ -1,40 +1,46 @@
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
import { SourceControlProviderError } from "@t3tools/contracts";
import {
SourceControlProviderError,
type SourceControlProviderDiscoveryItem,
} from "@t3tools/contracts";
import type { SourceControlProviderKind } from "@t3tools/contracts";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import {
SourceControlProvider,
type SourceControlProviderContext,
type SourceControlProviderShape,
} from "./SourceControlProvider.ts";
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
import { ServerConfig } from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
export interface SourceControlProviderRegistration {
readonly kind: SourceControlProviderKind;
readonly provider: SourceControlProviderShape;
readonly provider: SourceControlProvider.SourceControlProviderShape;
readonly discovery: SourceControlProviderDiscovery.SourceControlProviderDiscoverySpec;
}
export interface SourceControlProviderHandle {
readonly provider: SourceControlProviderShape;
readonly context: SourceControlProviderContext | null;
readonly provider: SourceControlProvider.SourceControlProviderShape;
readonly context: SourceControlProvider.SourceControlProviderContext | null;
}
export interface SourceControlProviderRegistryShape {
readonly get: (
kind: SourceControlProviderKind,
) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
) => Effect.Effect<SourceControlProvider.SourceControlProviderShape, SourceControlProviderError>;
readonly resolveHandle: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
readonly resolve: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
}) => Effect.Effect<SourceControlProvider.SourceControlProviderShape, SourceControlProviderError>;
readonly discover: Effect.Effect<ReadonlyArray<SourceControlProviderDiscoveryItem>>;
}
export class SourceControlProviderRegistry extends Context.Service<
@@ -42,7 +48,9 @@ export class SourceControlProviderRegistry extends Context.Service<
SourceControlProviderRegistryShape
>()("t3/source-control/SourceControlProviderRegistry") {}
function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProviderShape {
function unsupportedProvider(
kind: SourceControlProviderKind,
): SourceControlProvider.SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.fail(
new SourceControlProviderError({
@@ -52,7 +60,7 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
}),
);
return SourceControlProvider.of({
return SourceControlProvider.SourceControlProvider.of({
kind,
listChangeRequests: () => unsupported("listChangeRequests"),
getChangeRequest: () => unsupported("getChangeRequest"),
@@ -78,7 +86,7 @@ function selectProviderContext(
readonly name: string;
readonly url: string;
}>,
): SourceControlProviderContext | null {
): SourceControlProvider.SourceControlProviderContext | null {
const candidates = remotes
.map((remote) => {
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
@@ -90,7 +98,7 @@ function selectProviderContext(
}
: null;
})
.filter((value): value is SourceControlProviderContext => value !== null);
.filter((value): value is SourceControlProvider.SourceControlProviderContext => value !== null);
return (
candidates.find((candidate) => candidate.remoteName === "origin") ??
@@ -100,12 +108,60 @@ function selectProviderContext(
);
}
function bindProviderContext(
provider: SourceControlProvider.SourceControlProviderShape,
context: SourceControlProvider.SourceControlProviderContext | null,
): SourceControlProvider.SourceControlProviderShape {
if (context === null) {
return provider;
}
return SourceControlProvider.SourceControlProvider.of({
kind: provider.kind,
listChangeRequests: (input) =>
provider.listChangeRequests({
...input,
context: input.context ?? context,
}),
getChangeRequest: (input) =>
provider.getChangeRequest({
...input,
context: input.context ?? context,
}),
createChangeRequest: (input) =>
provider.createChangeRequest({
...input,
context: input.context ?? context,
}),
getRepositoryCloneUrls: (input) =>
provider.getRepositoryCloneUrls({
...input,
context: input.context ?? context,
}),
createRepository: (input) => provider.createRepository(input),
getDefaultBranch: (input) =>
provider.getDefaultBranch({
...input,
context: input.context ?? context,
}),
checkoutChangeRequest: (input) =>
provider.checkoutChangeRequest({
...input,
context: input.context ?? context,
}),
});
}
export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
const vcsRegistry = yield* VcsDriverRegistry;
const providers = new Map<SourceControlProviderKind, SourceControlProviderShape>(
registrations.map((registration) => [registration.kind, registration.provider]),
);
const config = yield* ServerConfig;
const process = yield* VcsProcess.VcsProcess;
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
const providers = new Map<
SourceControlProviderKind,
SourceControlProvider.SourceControlProviderShape
>(registrations.map((registration) => [registration.kind, registration.provider]));
const discoverySpecs = registrations.map((registration) => registration.discovery);
const get: SourceControlProviderRegistryShape["get"] = (kind) =>
Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
@@ -125,7 +181,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
const providerContextCache = yield* Cache.makeWith<
string,
SourceControlProviderContext | null,
SourceControlProvider.SourceControlProviderContext | null,
SourceControlProviderError
>(detectProviderContext, {
capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
@@ -136,8 +192,9 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
Cache.get(providerContextCache, input.cwd).pipe(
Effect.map((context) => {
const kind = context?.provider.kind ?? "unknown";
const provider = providers.get(kind) ?? unsupportedProvider(kind);
return {
provider: providers.get(kind) ?? unsupportedProvider(kind),
provider: bindProviderContext(provider, context),
context,
} satisfies SourceControlProviderHandle;
}),
@@ -147,6 +204,16 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
get,
resolveHandle,
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
discover: Effect.all(
discoverySpecs.map((spec) =>
SourceControlProviderDiscovery.probeSourceControlProvider({
spec,
process,
cwd: config.cwd,
}),
),
{ concurrency: "unbounded" },
),
});
},
);
@@ -154,14 +221,29 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
const github = yield* GitHubSourceControlProvider.make();
const gitlab = yield* GitLabSourceControlProvider.make();
const bitbucket = yield* BitbucketSourceControlProvider.make();
const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery();
const azureDevOps = yield* AzureDevOpsSourceControlProvider.make();
return yield* makeWithProviders([
{
kind: "github",
provider: github,
discovery: GitHubSourceControlProvider.discovery,
},
{
kind: "gitlab",
provider: gitlab,
discovery: GitLabSourceControlProvider.discovery,
},
{
kind: "azure-devops",
provider: azureDevOps,
discovery: AzureDevOpsSourceControlProvider.discovery,
},
{
kind: "bitbucket",
provider: bitbucket,
discovery: bitbucketDiscovery,
},
]);
});
@@ -6,14 +6,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError, type SourceControlProviderError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import {
GitVcsDriver,
type ExecuteGitResult,
type GitVcsDriverShape,
} from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
import type { SourceControlProviderShape } from "./SourceControlProvider.ts";
import { SourceControlRepositoryService, layer } from "./SourceControlRepositoryService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import type * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
const CLONE_URLS = {
nameWithOwner: "octocat/t3code",
@@ -22,8 +18,8 @@ const CLONE_URLS = {
};
function makeProvider(
overrides: Partial<SourceControlProviderShape> = {},
): SourceControlProviderShape {
overrides: Partial<SourceControlProvider.SourceControlProviderShape> = {},
): SourceControlProvider.SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
never,
@@ -43,7 +39,7 @@ function makeProvider(
};
}
function processOutput(): ExecuteGitResult {
function processOutput(): GitVcsDriver.ExecuteGitResult {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
@@ -54,17 +50,17 @@ function processOutput(): ExecuteGitResult {
}
function makeLayer(input: {
readonly provider?: SourceControlProviderShape;
readonly git?: Partial<GitVcsDriverShape>;
readonly provider?: SourceControlProvider.SourceControlProviderShape;
readonly git?: Partial<GitVcsDriver.GitVcsDriverShape>;
}) {
return layer.pipe(
return SourceControlRepositoryService.layer.pipe(
Layer.provide(
Layer.mock(SourceControlProviderRegistry)({
Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
get: () => Effect.succeed(input.provider ?? makeProvider()),
}),
),
Layer.provide(
Layer.mock(GitVcsDriver)({
Layer.mock(GitVcsDriver.GitVcsDriver)({
execute: () => Effect.succeed(processOutput()),
ensureRemote: () => Effect.succeed("origin"),
pushCurrentBranch: () =>
@@ -93,7 +89,7 @@ it.effect("looks up repositories through the requested provider without search",
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.lookupRepository({
provider: "github",
repository: "octocat/t3code",
@@ -115,7 +111,7 @@ it.effect("clones a looked-up repository into the requested destination", () =>
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.cloneRepository({
provider: "github",
repository: "octocat/t3code",
@@ -167,7 +163,7 @@ it.effect("publishes by creating the repository, adding a remote, and pushing up
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
@@ -222,7 +218,7 @@ it.effect("publishes to the remote name returned by ensureRemote", () => {
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
@@ -258,7 +254,7 @@ it.effect("publishes to the remote name returned by ensureRemote", () => {
it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
let pushCalls = 0;
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
@@ -1,4 +1,4 @@
import OS from "node:os";
import * as NodeOS from "node:os";
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
import {
@@ -15,8 +15,8 @@ import {
} from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
export interface SourceControlRepositoryServiceShape {
readonly lookupRepository: (
@@ -102,10 +102,10 @@ function selectRemoteUrl(
function expandHomePath(input: string, path: Path.Path): string {
if (input === "~") {
return OS.homedir();
return NodeOS.homedir();
}
if (input.startsWith("~/") || input.startsWith("~\\")) {
return path.join(OS.homedir(), input.slice(2));
return path.join(NodeOS.homedir(), input.slice(2));
}
return input;
}
@@ -113,9 +113,9 @@ function expandHomePath(input: string, path: Path.Path): string {
export const make = Effect.fn("makeSourceControlRepositoryService")(function* () {
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver;
const git = yield* GitVcsDriver.GitVcsDriver;
const path = yield* Path.Path;
const providers = yield* SourceControlProviderRegistry;
const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const ensureConcreteProvider = (input: {
readonly operation: string;
@@ -0,0 +1,106 @@
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
export interface NormalizedAzureDevOpsPullRequestRecord {
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>;
}
const AzureDevOpsPullRequestSchema = Schema.Struct({
pullRequestId: PositiveInt,
title: TrimmedNonEmptyString,
url: Schema.optional(Schema.String),
sourceRefName: TrimmedNonEmptyString,
targetRefName: TrimmedNonEmptyString,
status: Schema.String,
creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
_links: Schema.optional(
Schema.Struct({
web: Schema.optional(
Schema.Struct({
href: Schema.String,
}),
),
}),
),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function normalizeRefName(refName: string): string {
return refName.trim().replace(/^refs\/heads\//, "");
}
function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" | "merged" {
switch (status.trim().toLowerCase()) {
case "completed":
return "merged";
case "abandoned":
return "closed";
default:
return "open";
}
}
function normalizeAzureDevOpsPullRequestRecord(
raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
): NormalizedAzureDevOpsPullRequestRecord {
return {
number: raw.pullRequestId,
title: raw.title,
url: trimOptionalString(raw._links?.web?.href) ?? trimOptionalString(raw.url) ?? "",
baseRefName: normalizeRefName(raw.targetRefName),
headRefName: normalizeRefName(raw.sourceRefName),
state: normalizeAzureDevOpsPullRequestState(raw.status),
updatedAt: (raw.closedDate ?? Option.none()).pipe(
Option.orElse(() => raw.creationDate ?? Option.none()),
),
};
}
const decodeAzureDevOpsPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeAzureDevOpsPullRequest = decodeJsonResult(AzureDevOpsPullRequestSchema);
const decodeAzureDevOpsPullRequestEntry = Schema.decodeUnknownExit(AzureDevOpsPullRequestSchema);
export const formatAzureDevOpsJsonDecodeError = formatSchemaError;
export function decodeAzureDevOpsPullRequestListJson(
raw: string,
): Result.Result<
ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>,
Cause.Cause<Schema.SchemaError>
> {
const result = decodeAzureDevOpsPullRequestList(raw);
if (Result.isSuccess(result)) {
const pullRequests: NormalizedAzureDevOpsPullRequestRecord[] = [];
for (const entry of result.success) {
const decodedEntry = decodeAzureDevOpsPullRequestEntry(entry);
if (Exit.isFailure(decodedEntry)) {
continue;
}
pullRequests.push(normalizeAzureDevOpsPullRequestRecord(decodedEntry.value));
}
return Result.succeed(pullRequests);
}
return Result.fail(result.failure);
}
export function decodeAzureDevOpsPullRequestJson(
raw: string,
): Result.Result<NormalizedAzureDevOpsPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
const result = decodeAzureDevOpsPullRequest(raw);
if (Result.isSuccess(result)) {
return Result.succeed(normalizeAzureDevOpsPullRequestRecord(result.success));
}
return Result.fail(result.failure);
}
@@ -0,0 +1,104 @@
import { DateTime, Option, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
export interface NormalizedBitbucketPullRequestRecord {
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 const BitbucketRepositoryRefSchema = Schema.Struct({
full_name: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
workspace: Schema.optional(
Schema.NullOr(
Schema.Struct({
slug: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
}),
),
),
});
export const BitbucketPullRequestBranchSchema = Schema.Struct({
repository: Schema.optional(Schema.NullOr(BitbucketRepositoryRefSchema)),
branch: Schema.Struct({
name: TrimmedNonEmptyString,
}),
});
export const BitbucketPullRequestSchema = Schema.Struct({
id: PositiveInt,
title: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
updated_on: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
links: Schema.Struct({
html: Schema.Struct({
href: TrimmedNonEmptyString,
}),
}),
source: BitbucketPullRequestBranchSchema,
destination: BitbucketPullRequestBranchSchema,
});
export const BitbucketPullRequestListSchema = Schema.Struct({
values: Schema.Array(BitbucketPullRequestSchema),
next: Schema.optional(TrimmedNonEmptyString),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function repositoryOwner(repository: Schema.Schema.Type<typeof BitbucketRepositoryRefSchema>) {
return (
trimOptionalString(repository.workspace?.slug) ??
(repository.full_name?.includes("/") ? (repository.full_name.split("/")[0] ?? null) : null)
);
}
function normalizeBitbucketPullRequestState(state: string | null | undefined) {
switch (state?.trim().toUpperCase()) {
case "MERGED":
return "merged" as const;
case "DECLINED":
case "SUPERSEDED":
return "closed" as const;
case "OPEN":
default:
return "open" as const;
}
}
export function normalizeBitbucketPullRequestRecord(
raw: Schema.Schema.Type<typeof BitbucketPullRequestSchema>,
): NormalizedBitbucketPullRequestRecord {
const headRepositoryNameWithOwner = trimOptionalString(raw.source.repository?.full_name);
const baseRepositoryNameWithOwner = trimOptionalString(raw.destination.repository?.full_name);
const headRepositoryOwnerLogin = raw.source.repository
? repositoryOwner(raw.source.repository)
: null;
const isCrossRepository =
headRepositoryNameWithOwner !== null &&
baseRepositoryNameWithOwner !== null &&
headRepositoryNameWithOwner !== baseRepositoryNameWithOwner;
return {
number: raw.id,
title: raw.title,
url: raw.links.html.href,
baseRefName: raw.destination.branch.name,
headRefName: raw.source.branch.name,
state: normalizeBitbucketPullRequestState(raw.state),
updatedAt: raw.updated_on ?? Option.none(),
...(isCrossRepository ? { isCrossRepository: true } : {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
+115 -113
View File
@@ -18,9 +18,9 @@ import {
type VcsStatusInput,
type VcsStatusResult,
} from "@t3tools/contracts";
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
import * as GitVcsDriverCore from "./GitVcsDriverCore.ts";
import * as VcsDriver from "./VcsDriver.ts";
import * as VcsProcess from "./VcsProcess.ts";
export interface ExecuteGitInput {
readonly operation: string;
@@ -304,7 +304,7 @@ function parseGitRemoteVerboseOutput(
}
const gitCommand = (
process: VcsProcessShape,
process: VcsProcess.VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
@@ -335,7 +335,7 @@ const gitCommand = (
});
export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
const process = yield* VcsProcess;
const process = yield* VcsProcess.VcsProcess;
const capabilities = {
kind: "git" as const,
supportsWorktrees: true,
@@ -345,7 +345,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
ignoreClassifier: "native" as const,
};
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
const isInsideWorkTree: VcsDriver.VcsDriverShape["isInsideWorkTree"] = (cwd) =>
gitCommand(
process,
"GitVcsDriver.isInsideWorkTree",
@@ -358,7 +358,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
},
).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
const execute: VcsDriverShape["execute"] = (input) =>
const execute: VcsDriver.VcsDriverShape["execute"] = (input) =>
gitCommand(process, input.operation, input.cwd, input.args, {
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.env !== undefined ? { env: input.env } : {}),
@@ -370,33 +370,33 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
: {}),
});
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
function* (cwd) {
if (!(yield* isInsideWorkTree(cwd))) {
return null;
}
const detectRepository: VcsDriver.VcsDriverShape["detectRepository"] = Effect.fn(
"detectRepository",
)(function* (cwd) {
if (!(yield* isInsideWorkTree(cwd))) {
return null;
}
const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
"rev-parse",
"--show-toplevel",
]);
const gitCommonDir = yield* gitCommand(
process,
"GitVcsDriver.detectRepository.commonDir",
cwd,
["rev-parse", "--git-common-dir"],
).pipe(Effect.catch(() => Effect.succeed(null)));
const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
"rev-parse",
"--show-toplevel",
]);
const gitCommonDir = yield* gitCommand(
process,
"GitVcsDriver.detectRepository.commonDir",
cwd,
["rev-parse", "--git-common-dir"],
).pipe(Effect.catch(() => Effect.succeed(null)));
return {
kind: "git" as const,
rootPath: root.stdout.trim(),
metadataPath: gitCommonDir?.stdout.trim() || null,
freshness: yield* nowFreshness(),
};
},
);
return {
kind: "git" as const,
rootPath: root.stdout.trim(),
metadataPath: gitCommonDir?.stdout.trim() || null,
freshness: yield* nowFreshness(),
};
});
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
const listWorkspaceFiles: VcsDriver.VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
gitCommand(
process,
"GitVcsDriver.listWorkspaceFiles",
@@ -438,98 +438,100 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
),
);
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
});
if (result.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.listRemotes",
command: "git remote -v",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git remote -v failed",
const listRemotes: VcsDriver.VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(
function* (cwd) {
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
});
}
const parsed = parseGitRemoteVerboseOutput(result.stdout);
const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
if (!remote.url) {
return [];
}
return [
{
name,
url: remote.url,
pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
isPrimary: name === "origin",
},
];
});
return {
remotes,
freshness: yield* nowFreshness(),
};
});
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
function* (cwd, relativePaths) {
if (relativePaths.length === 0) {
return relativePaths;
}
const ignoredPaths = new Set<string>();
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
for (const chunk of chunks) {
const result = yield* gitCommand(
process,
"GitVcsDriver.filterIgnoredPaths",
if (result.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.listRemotes",
command: "git remote -v",
cwd,
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
exitCode: result.exitCode,
detail: result.stderr.trim() || "git remote -v failed",
});
}
const parsed = parseGitRemoteVerboseOutput(result.stdout);
const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
if (!remote.url) {
return [];
}
return [
{
stdin: `${chunk.join("\0")}\0`,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
name,
url: remote.url,
pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
isPrimary: name === "origin",
},
);
];
});
if (result.exitCode !== 0 && result.exitCode !== 1) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.filterIgnoredPaths",
command: "git check-ignore",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git check-ignore failed",
});
}
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
ignoredPaths.add(ignoredPath);
}
}
if (ignoredPaths.size === 0) {
return relativePaths;
}
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
return {
remotes,
freshness: yield* nowFreshness(),
};
},
);
const initRepository: VcsDriverShape["initRepository"] = (input) =>
const filterIgnoredPaths: VcsDriver.VcsDriverShape["filterIgnoredPaths"] = Effect.fn(
"filterIgnoredPaths",
)(function* (cwd, relativePaths) {
if (relativePaths.length === 0) {
return relativePaths;
}
const ignoredPaths = new Set<string>();
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
for (const chunk of chunks) {
const result = yield* gitCommand(
process,
"GitVcsDriver.filterIgnoredPaths",
cwd,
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
{
stdin: `${chunk.join("\0")}\0`,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
},
);
if (result.exitCode !== 0 && result.exitCode !== 1) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.filterIgnoredPaths",
command: "git check-ignore",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git check-ignore failed",
});
}
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
ignoredPaths.add(ignoredPath);
}
}
if (ignoredPaths.size === 0) {
return relativePaths;
}
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
});
const initRepository: VcsDriver.VcsDriverShape["initRepository"] = (input) =>
gitCommand(process, "GitVcsDriver.initRepository", input.cwd, ["init"], {
timeoutMs: 10_000,
maxOutputBytes: 64 * 1024,
}).pipe(Effect.asVoid);
return {
return VcsDriver.VcsDriver.of({
capabilities,
execute,
detectRepository,
@@ -538,18 +540,18 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
listRemotes,
filterIgnoredPaths,
initRepository,
} satisfies VcsDriverShape;
});
});
export const makeVcsDriver = Effect.fn("makeGitVcsDriver")(function* () {
const driver = yield* makeVcsDriverShape();
return VcsDriver.of(driver);
return VcsDriver.VcsDriver.of(driver);
});
export const make = Effect.fn("makeGitVcsDriverService")(function* () {
const git = yield* makeGitVcsDriverCore();
const git = yield* GitVcsDriverCore.makeGitVcsDriverCore();
return GitVcsDriver.of(git);
});
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
export const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver());
export const layer = Layer.effect(GitVcsDriver, make());
+1 -2
View File
@@ -1,7 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assert, it, describe } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, PlatformError, Scope } from "effect";
import { describe } from "vitest";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -8,13 +8,13 @@ import type {
VcsListWorkspaceFilesResult,
VcsRepositoryIdentity,
} from "@t3tools/contracts";
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
import * as VcsProcess from "./VcsProcess.ts";
export interface VcsDriverShape {
readonly capabilities: VcsDriverCapabilities;
readonly execute: (
input: Omit<VcsProcessInput, "command">,
) => Effect.Effect<VcsProcessOutput, VcsError>;
input: Omit<VcsProcess.VcsProcessInput, "command">,
) => Effect.Effect<VcsProcess.VcsProcessOutput, VcsError>;
readonly detectRepository: (cwd: string) => Effect.Effect<VcsRepositoryIdentity | null, VcsError>;
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, VcsError>;
readonly listWorkspaceFiles: (
+14 -15
View File
@@ -1,13 +1,12 @@
import { assert, it } from "@effect/vitest";
import { assert, it, describe } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { describe } from "vitest";
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "./VcsProcess.ts";
import { VcsProjectConfig } from "./VcsProjectConfig.ts";
import { VcsDriverRegistry, make as makeVcsDriverRegistry } from "./VcsDriverRegistry.ts";
import * as VcsProcess from "./VcsProcess.ts";
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
import * as VcsDriverRegistry from "./VcsDriverRegistry.ts";
const processOutput = (stdout: string): VcsProcessOutput => ({
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
@@ -17,21 +16,21 @@ const processOutput = (stdout: string): VcsProcessOutput => ({
describe("VcsDriverRegistry", () => {
it.effect("routes directly by VCS driver kind for non-repository workflows", () => {
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
Layer.mock(VcsProcess.VcsProcess)({
run: () => Effect.succeed(processOutput("")),
}),
),
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
const driver = yield* registry.get("git");
assert.strictEqual(driver.capabilities.kind, "git");
@@ -39,15 +38,15 @@ describe("VcsDriverRegistry", () => {
});
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
const calls: VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
const calls: VcsProcess.VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
Layer.mock(VcsProjectConfig.VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
Layer.mock(VcsProcess.VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
@@ -68,7 +67,7 @@ describe("VcsDriverRegistry", () => {
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
const first = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
const second = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
+5 -5
View File
@@ -4,7 +4,7 @@ import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/co
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
import type { VcsDriverShape } from "./VcsDriver.ts";
import * as VcsDriver from "./VcsDriver.ts";
const DETECTION_CACHE_CAPACITY = 2_048;
const DETECTION_CACHE_TTL = Duration.seconds(2);
@@ -17,11 +17,11 @@ export interface VcsDriverResolveInput {
export interface VcsDriverHandle {
readonly kind: VcsDriverKind;
readonly repository: VcsRepositoryIdentity;
readonly driver: VcsDriverShape;
readonly driver: VcsDriver.VcsDriverShape;
}
export interface VcsDriverRegistryShape {
readonly get: (kind: VcsDriverKind) => Effect.Effect<VcsDriverShape, VcsError>;
readonly get: (kind: VcsDriverKind) => Effect.Effect<VcsDriver.VcsDriverShape, VcsError>;
readonly detect: (
input: VcsDriverResolveInput,
) => Effect.Effect<VcsDriverHandle | null, VcsError>;
@@ -66,7 +66,7 @@ function parseDetectionCacheKey(key: string): {
export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
const git = yield* GitVcsDriver.makeVcsDriverShape();
const drivers: Partial<Record<VcsDriverKind, VcsDriverShape>> = {
const drivers: Partial<Record<VcsDriverKind, VcsDriver.VcsDriverShape>> = {
git,
};
@@ -82,7 +82,7 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
kind: VcsDriverKind,
driver: VcsDriverShape,
driver: VcsDriver.VcsDriverShape,
cwd: string,
) {
const repository = yield* driver.detectRepository(cwd);
+6 -7
View File
@@ -1,11 +1,10 @@
import { assert, it } from "@effect/vitest";
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Path } from "effect";
import { describe } from "vitest";
import { VcsProjectConfig, layer as VcsProjectConfigLayer } from "./VcsProjectConfig.ts";
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
const TestLayer = VcsProjectConfigLayer.pipe(
const TestLayer = VcsProjectConfig.layer.pipe(
Layer.provide(NodeServices.layer),
Layer.provideMerge(NodeServices.layer),
);
@@ -14,7 +13,7 @@ describe("VcsProjectConfig", () => {
it.layer(TestLayer)("uses an explicit requested VCS kind before config", (it) => {
it.effect("returns the requested kind", () =>
Effect.gen(function* () {
const config = yield* VcsProjectConfig;
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({
cwd: "/repo",
requestedKind: "jj",
@@ -42,7 +41,7 @@ describe("VcsProjectConfig", () => {
JSON.stringify({ vcs: { kind: "jj" } }),
);
const config = yield* VcsProjectConfig;
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: nested });
assert.equal(kind, "jj");
@@ -57,7 +56,7 @@ describe("VcsProjectConfig", () => {
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const config = yield* VcsProjectConfig;
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
@@ -2,13 +2,13 @@ import { assert, it } from "@effect/vitest";
import { DateTime, Effect, Layer, Option } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type { VcsDriverShape } from "./VcsDriver.ts";
import { VcsDriverRegistry } from "./VcsDriverRegistry.ts";
import { VcsProvisioningService, layer } from "./VcsProvisioningService.ts";
import * as VcsDriver from "./VcsDriver.ts";
import * as VcsDriverRegistry from "./VcsDriverRegistry.ts";
import * as VcsProvisioningService from "./VcsProvisioningService.ts";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
function makeDriver(calls: string[]): VcsDriverShape {
function makeDriver(calls: string[]): VcsDriver.VcsDriverShape {
return {
capabilities: {
kind: "git",
@@ -58,16 +58,16 @@ function makeDriver(calls: string[]): VcsDriverShape {
it.effect("routes repository initialization through an explicit VCS driver kind", () => {
const calls: string[] = [];
const driver = makeDriver(calls);
const testLayer = layer.pipe(
const testLayer = VcsProvisioningService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry)({
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")),
}),
),
);
return Effect.gen(function* () {
const provisioning = yield* VcsProvisioningService;
const provisioning = yield* VcsProvisioningService.VcsProvisioningService;
yield* provisioning.initRepository({ cwd: "/repo", kind: "git" });
assert.deepStrictEqual(calls, ["git:/repo"]);
@@ -77,16 +77,16 @@ it.effect("routes repository initialization through an explicit VCS driver kind"
it.effect("defaults repository initialization to Git until callers choose a VCS kind", () => {
const calls: string[] = [];
const driver = makeDriver(calls);
const testLayer = layer.pipe(
const testLayer = VcsProvisioningService.layer.pipe(
Layer.provide(
Layer.mock(VcsDriverRegistry)({
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")),
}),
),
);
return Effect.gen(function* () {
const provisioning = yield* VcsProvisioningService;
const provisioning = yield* VcsProvisioningService.VcsProvisioningService;
yield* provisioning.initRepository({ cwd: "/repo" });
assert.deepStrictEqual(calls, ["default:/repo"]);
@@ -6,7 +6,7 @@ import {
type VcsInitInput,
VcsUnsupportedOperationError,
} from "@t3tools/contracts";
import { VcsDriverRegistry } from "./VcsDriverRegistry.ts";
import * as VcsDriverRegistry from "./VcsDriverRegistry.ts";
export interface VcsProvisioningServiceShape {
readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;
@@ -36,7 +36,7 @@ function resolveRequestedKind(
}
export const make = Effect.fn("makeVcsProvisioningService")(function* () {
const registry = yield* VcsDriverRegistry;
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
const initRepository: VcsProvisioningServiceShape["initRepository"] = Effect.fn(
"VcsProvisioningService.initRepository",
@@ -1,4 +1,4 @@
import { assert, it } from "@effect/vitest";
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Deferred, Effect, Exit, FileSystem, Layer, Option, Path, Scope, Stream } from "effect";
import type {
@@ -7,13 +7,9 @@ import type {
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { describe } from "vitest";
import {
VcsStatusBroadcaster,
layer as VcsStatusBroadcasterLayer,
} from "./VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
const baseLocalStatus: VcsStatusLocalResult = {
isRepo: true,
@@ -49,9 +45,9 @@ function makeTestLayer(state: {
localInvalidationCalls: number;
remoteInvalidationCalls: number;
}) {
return VcsStatusBroadcasterLayer.pipe(
return VcsStatusBroadcaster.layer.pipe(
Layer.provide(
Layer.mock(GitWorkflowService)({
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
@@ -87,7 +83,7 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
@@ -112,7 +108,7 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
@@ -153,7 +149,7 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
@@ -188,9 +184,9 @@ describe("VcsStatusBroadcaster", () => {
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
const testLayer = VcsStatusBroadcasterLayer.pipe(
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provide(
Layer.mock(GitWorkflowService)({
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
@@ -211,7 +207,7 @@ describe("VcsStatusBroadcaster", () => {
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>),
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
),
);
@@ -228,7 +224,7 @@ describe("VcsStatusBroadcaster", () => {
yield* fileSystem.symlink(realDir, linkDir);
const realPath = yield* fileSystem.realPath(realDir);
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: linkDir });
yield* broadcaster.getStatus({ cwd: realDir });
@@ -249,7 +245,7 @@ describe("VcsStatusBroadcaster", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
@@ -289,9 +285,9 @@ describe("VcsStatusBroadcaster", () => {
};
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const testLayer = VcsStatusBroadcasterLayer.pipe(
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provide(
Layer.mock(GitWorkflowService)({
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
@@ -321,7 +317,7 @@ describe("VcsStatusBroadcaster", () => {
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>),
} satisfies Partial<GitWorkflowService.GitWorkflowServiceShape>),
),
);
@@ -331,7 +327,7 @@ describe("VcsStatusBroadcaster", () => {
remoteInterruptedDeferred = remoteInterrupted;
remoteStartedDeferred = remoteStarted;
const broadcaster = yield* VcsStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
const firstScope = yield* Scope.make();
+3 -3
View File
@@ -1,6 +1,7 @@
import { realpathSync } from "node:fs";
import {
Context,
Duration,
Effect,
Exit,
@@ -20,10 +21,9 @@ import type {
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { Context } from "effect";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import { GitWorkflowService } from "../git/GitWorkflowService.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
@@ -80,7 +80,7 @@ function normalizeCwd(cwd: string): string {
export const layer = Layer.effect(
VcsStatusBroadcaster,
Effect.gen(function* () {
const workflow = yield* GitWorkflowService;
const workflow = yield* GitWorkflowService.GitWorkflowService;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<VcsStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
@@ -1,10 +1,17 @@
import { assert, it } from "@effect/vitest";
import { DateTime, Option } from "effect";
import { Effect, FileSystem, Layer, Path, type PlatformError, type Scope } from "effect";
import { describe } from "vitest";
import { assert, it, describe } from "@effect/vitest";
import {
Effect,
FileSystem,
Layer,
Path,
type PlatformError,
type Scope,
DateTime,
Option,
} from "effect";
import type { VcsDriverKind } from "@t3tools/contracts";
import { VcsDriver } from "../VcsDriver.ts";
import * as VcsDriver from "../VcsDriver.ts";
export interface VcsDriverFixture<R, E> {
readonly createRepo: (cwd: string) => Effect.Effect<void, E, R>;
@@ -24,7 +31,11 @@ export interface VcsDriverFixture<R, E> {
export interface VcsDriverContractSuiteInput<R, E> {
readonly name: string;
readonly kind: VcsDriverKind;
readonly layer: Layer.Layer<VcsDriver | R | FileSystem.FileSystem | Path.Path, E, never>;
readonly layer: Layer.Layer<
VcsDriver.VcsDriver | R | FileSystem.FileSystem | Path.Path,
E,
never
>;
readonly fixture: VcsDriverFixture<R, E>;
}
@@ -42,7 +53,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
it.effect("returns null outside a repository", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
const driver = yield* VcsDriver.VcsDriver;
assert.equal(yield* driver.detectRepository(cwd), null);
assert.equal(yield* driver.isInsideWorkTree(cwd), false);
@@ -52,7 +63,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
it.effect("detects repository identity inside a repository and nested directories", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
const driver = yield* VcsDriver.VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
@@ -77,7 +88,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
it.effect("lists tracked and untracked non-ignored files", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
const driver = yield* VcsDriver.VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.writeFile(cwd, "tracked.ts", "export const tracked = true;\n");
@@ -101,7 +112,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
it.effect("excludes ignored files from workspace listing", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
const driver = yield* VcsDriver.VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.ignorePath(cwd, "*.log");
@@ -122,7 +133,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
it.effect("filters ignored paths", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
const driver = yield* VcsDriver.VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.ignorePath(cwd, "*.log");
@@ -140,7 +151,7 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
it.effect("returns empty input unchanged", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
const driver = yield* VcsDriver.VcsDriver;
yield* input.fixture.createRepo(cwd);
+31 -1
View File
@@ -56,6 +56,14 @@ import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.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 SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
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 {
BootstrapCredentialService,
@@ -672,6 +680,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
ORCHESTRATION_WS_METHODS.subscribeShell,
Effect.gen(function* () {
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration shell snapshot load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
@@ -1017,6 +1028,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
version: 1 as const,
type: "keybindingsUpdated" as const,
payload: {
keybindings: event.keybindings,
issues: event.issues,
},
})),
@@ -1130,7 +1142,25 @@ export const websocketRpcRouteLayer = Layer.unwrap(
makeWsRpcLayer(session.sessionId).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(
SourceControlDiscoveryLayer.layer.pipe(Layer.provide(VcsProcess.layer)),
SourceControlDiscoveryLayer.layer.pipe(
Layer.provide(
SourceControlProviderRegistry.layer.pipe(
Layer.provide(
Layer.mergeAll(
AzureDevOpsCli.layer,
BitbucketApi.layer,
GitHubCli.layer,
GitLabCli.layer,
),
),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provide(
VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer)),
),
),
),
Layer.provide(VcsProcess.layer),
),
),
),
),
@@ -10,6 +10,12 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
function createLocalStorageStub(): Storage {
+14 -3
View File
@@ -19,6 +19,14 @@ const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
wsBaseUrl: Schema.String,
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
desktopSsh: Schema.optionalKey(
Schema.Struct({
alias: Schema.String,
hostname: Schema.String,
username: Schema.NullOr(Schema.String),
port: Schema.NullOr(Schema.Number),
}),
),
bearerToken: Schema.optionalKey(Schema.String),
});
type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type;
@@ -37,7 +45,7 @@ function hasWindow(): boolean {
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -45,6 +53,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readBrowserClientSettings(): ClientSettings | null {
@@ -135,6 +144,7 @@ export function writeBrowserSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
bearerToken,
}
: toPersistedSavedEnvironmentRecord(record);
@@ -166,7 +176,7 @@ export function writeBrowserSavedEnvironmentSecret(
return record;
}
found = true;
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -174,7 +184,8 @@ export function writeBrowserSavedEnvironmentSecret(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken: secret,
} satisfies BrowserSavedEnvironmentRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
});
return found;
@@ -0,0 +1,59 @@
"use client";
import { type ReactNode, useLayoutEffect, useRef, useState } from "react";
export function AnimatedHeight({ children }: { readonly children: ReactNode }) {
const contentRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState<number | null>(null);
useLayoutEffect(() => {
const element = contentRef.current;
if (!element) return;
let firstFrameId: number | null = null;
let secondFrameId: number | null = null;
const updateHeight = () => {
const nextHeight = Math.ceil(element.scrollHeight || element.getBoundingClientRect().height);
setHeight((currentHeight) => (currentHeight === nextHeight ? currentHeight : nextHeight));
};
const cancelPendingFrames = () => {
if (firstFrameId !== null) {
window.cancelAnimationFrame(firstFrameId);
firstFrameId = null;
}
if (secondFrameId !== null) {
window.cancelAnimationFrame(secondFrameId);
secondFrameId = null;
}
};
const updateHeightAfterPaint = () => {
cancelPendingFrames();
updateHeight();
firstFrameId = window.requestAnimationFrame(() => {
firstFrameId = null;
updateHeight();
secondFrameId = window.requestAnimationFrame(() => {
secondFrameId = null;
updateHeight();
});
});
};
updateHeightAfterPaint();
const resizeObserver = new ResizeObserver(updateHeightAfterPaint);
resizeObserver.observe(element);
return () => {
resizeObserver.disconnect();
cancelPendingFrames();
};
}, []);
return (
<div
className="overflow-hidden transition-[height] duration-200 ease-out motion-reduce:transition-none"
style={height === null ? undefined : { height }}
>
<div ref={contentRef}>{children}</div>
</div>
);
}
+29 -13
View File
@@ -80,8 +80,6 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
() => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
[availableEnvironments, environmentId],
);
const environmentLabel = activeEnvironment?.label ?? "Run on";
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const WorkspaceIcon =
effectiveEnvMode === "worktree"
? FolderGit2Icon
@@ -93,6 +91,34 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: effectiveEnvMode === "worktree"
? resolveEnvModeLabel("worktree")
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
<EnvironmentIcon className="size-3 shrink-0 mx-0!" />
<WorkspaceIcon className="size-3 shrink-0 mx-0!" />
</span>
) : (
<WorkspaceIcon className="size-3 shrink-0" />
);
const triggerContent = (
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
if (isLocked) {
return (
<span className="inline-flex min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 md:hidden">
{triggerContent}
</span>
);
}
return (
<Menu>
@@ -100,17 +126,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
render={<Button variant="ghost" size="xs" />}
className="min-w-0 max-w-[48%] flex-1 justify-start text-muted-foreground/70 hover:text-foreground/80 md:hidden"
>
{showEnvironmentPicker ? (
<>
<EnvironmentIcon className="size-3 shrink-0" />
<span className="min-w-0 truncate">{environmentLabel}</span>
</>
) : (
<>
<WorkspaceIcon className="size-3 shrink-0" />
<span className="min-w-0 truncate">{workspaceLabel}</span>
</>
)}
{triggerContent}
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</MenuTrigger>
<MenuPopup align="start" side="top" className="w-64">
+142 -1
View File
@@ -22,6 +22,7 @@ import {
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { Option } from "effect";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
import { page } from "vitest/browser";
@@ -953,6 +954,73 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
if (tag === WS_METHODS.serverGetConfig) {
return fixture.serverConfig;
}
if (tag === WS_METHODS.serverDiscoverSourceControl) {
return {
versionControlSystems: [],
sourceControlProviders: [
{
kind: "github",
label: "GitHub",
executable: "gh",
status: "available",
version: Option.some("gh version 2.0.0"),
installHint: "Install GitHub CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("t3-oss"),
host: Option.some("github.com"),
detail: Option.none(),
},
},
{
kind: "gitlab",
label: "GitLab",
executable: "glab",
status: "available",
version: Option.some("glab version 1.0.0"),
installHint: "Install GitLab CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("t3-oss"),
host: Option.some("gitlab.com"),
detail: Option.none(),
},
},
{
kind: "bitbucket",
label: "Bitbucket",
executable: "Bitbucket REST API",
status: "available",
version: Option.none(),
installHint: "Set Bitbucket API token environment variables.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("t3-oss"),
host: Option.some("bitbucket.org"),
detail: Option.none(),
},
},
{
kind: "azure-devops",
label: "Azure DevOps",
executable: "az",
status: "available",
version: Option.some("azure-cli 2.0.0"),
installHint: "Install Azure CLI.",
detail: Option.none(),
auth: {
status: "authenticated",
account: Option.some("t3-oss"),
host: Option.some("dev.azure.com"),
detail: Option.none(),
},
},
],
};
}
if (tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
@@ -1663,6 +1731,74 @@ describe("ChatView timeline estimator parity (full app)", () => {
customWsRpcResolver = null;
document.body.innerHTML = "";
});
it("renders locked single-environment mobile run context as a static workspace label", async () => {
const mounted = await mountChatView({
viewport: COMPACT_FOOTER_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-mobile-locked-workspace" as MessageId,
targetText: "locked mobile workspace",
}),
});
try {
await waitForElement(
() =>
Array.from(document.querySelectorAll<HTMLElement>("span")).find(
(element) => element.textContent?.trim() === "Local checkout",
) ?? null,
"Unable to find static mobile workspace label.",
);
expect(findButtonByText("Local checkout")).toBeNull();
} finally {
await mounted.cleanup();
}
});
it("keeps dismiss-only composer banners aligned on mobile", async () => {
const mounted = await mountChatView({
viewport: COMPACT_FOOTER_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-mobile-version-banner" as MessageId,
targetText: "mobile version banner",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
environment: {
...nextFixture.serverConfig.environment,
serverVersion: "9.9.9",
},
};
},
});
try {
const banner = await waitForElement(
() =>
Array.from(document.querySelectorAll<HTMLElement>('[data-slot="alert"]')).find(
(element) => element.textContent?.includes("Client and server versions differ"),
) ?? null,
"Unable to find version mismatch banner.",
);
const title = banner.querySelector<HTMLElement>('[data-slot="alert-title"]');
const description = banner.querySelector<HTMLElement>('[data-slot="alert-description"]');
const dismissButton = banner.querySelector<HTMLButtonElement>(
'button[aria-label="Dismiss version mismatch warning"]',
);
expect(title).toBeTruthy();
expect(description).toBeTruthy();
expect(dismissButton).toBeTruthy();
expect(dismissButton!.getBoundingClientRect().top).toBeLessThan(
description!.getBoundingClientRect().top,
);
} finally {
await mounted.cleanup();
}
});
it("re-expands the bootstrap project using its logical key", async () => {
useUiStateStore.setState({
projectExpandedById: {
@@ -4582,6 +4718,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Local folder", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/");
@@ -4644,6 +4781,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Local folder", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/Development/");
@@ -4703,6 +4841,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await page.getByTestId("sidebar-add-project-trigger").click();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Local folder", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Desktop/fresh-project");
@@ -4782,6 +4921,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await page.getByTestId("sidebar-add-project-trigger").click();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Local folder", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/codex/");
@@ -4908,12 +5048,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
await palette.getByText("Local folder", { exact: true }).click();
await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByText("This device", { exact: true }).first())
.toBeInTheDocument();
await palette.getByText("Staging", { exact: true }).click();
await palette.getByText("Local folder", { exact: true }).click();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await expect.element(browseInput).toHaveValue("~/workspaces/");
@@ -5007,6 +5147,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const palette = page.getByTestId("command-palette");
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Local folder", { exact: true }).click();
const browseInput = palette.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await browseInput.fill("~/Applications/access");
+299 -76
View File
@@ -104,7 +104,7 @@ import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
import { cn, randomUUID } from "~/lib/utils";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
@@ -121,6 +121,7 @@ import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import {
reconnectSavedEnvironment,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
@@ -148,6 +149,7 @@ import { NoActiveThreadState } from "./NoActiveThreadState";
import { resolveEffectiveEnvMode, resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
@@ -180,6 +182,13 @@ import {
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { retainThreadDetailSubscription } from "../environments/runtime/service";
import { RightPanelSheet } from "./RightPanelSheet";
import { Button } from "./ui/button";
import {
buildVersionMismatchDismissalKey,
dismissVersionMismatch,
isVersionMismatchDismissed,
resolveServerConfigVersionMismatch,
} from "../versionSkew";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -187,6 +196,11 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROPOSED_PLANS: Thread["proposedPlans"] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
type EnvironmentUnavailableState = {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly connectionState: "connecting" | "disconnected" | "error";
};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
@@ -855,6 +869,78 @@ export default function ChatView(props: ChatViewProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId);
const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId);
const activeSavedEnvironmentRecord =
activeThread && activeThread.environmentId !== primaryEnvironmentId
? (savedEnvironmentRegistry[activeThread.environmentId] ?? null)
: null;
const activeSavedEnvironmentRuntime = activeSavedEnvironmentRecord
? (savedEnvironmentRuntimeById[activeSavedEnvironmentRecord.environmentId] ?? null)
: null;
const activeSavedEnvironmentConnectionState = activeSavedEnvironmentRecord
? (activeSavedEnvironmentRuntime?.connectionState ?? "disconnected")
: "connected";
const activeEnvironmentUnavailable =
activeSavedEnvironmentRecord !== null && activeSavedEnvironmentConnectionState !== "connected";
const activeSavedEnvironmentId = activeSavedEnvironmentRecord?.environmentId ?? null;
const activeEnvironmentUnavailableLabel = activeSavedEnvironmentRecord
? resolveEnvironmentOptionLabel({
isPrimary: false,
environmentId: activeSavedEnvironmentRecord.environmentId,
runtimeLabel: activeSavedEnvironmentRuntime?.descriptor?.label ?? null,
savedLabel: activeSavedEnvironmentRecord.label,
})
: null;
const activeEnvironmentUnavailableState = useMemo<EnvironmentUnavailableState | null>(() => {
if (
!activeEnvironmentUnavailable ||
!activeEnvironmentUnavailableLabel ||
!activeSavedEnvironmentId
) {
return null;
}
return {
environmentId: activeSavedEnvironmentId,
label: activeEnvironmentUnavailableLabel,
connectionState:
activeSavedEnvironmentConnectionState === "connecting" ||
activeSavedEnvironmentConnectionState === "error"
? activeSavedEnvironmentConnectionState
: "disconnected",
};
}, [
activeEnvironmentUnavailable,
activeEnvironmentUnavailableLabel,
activeSavedEnvironmentConnectionState,
activeSavedEnvironmentId,
]);
const [reconnectingEnvironmentId, setReconnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const handleReconnectActiveEnvironment = useCallback(
async (environmentId: EnvironmentId, label: string) => {
setReconnectingEnvironmentId(environmentId);
try {
await reconnectSavedEnvironment(environmentId);
toastManager.add({
type: "success",
title: "Environment reconnected",
description: `${label} is ready.`,
});
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not reconnect environment",
description: error instanceof Error ? error.message : "Failed to reconnect.",
}),
);
} finally {
setReconnectingEnvironmentId(null);
}
},
[],
);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
@@ -1055,6 +1141,120 @@ export default function ChatView(props: ChatViewProps) {
primaryEnvironmentId && activeThread?.environmentId === primaryEnvironmentId
? primaryServerConfig
: (activeEnvRuntimeState?.serverConfig ?? primaryServerConfig);
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
const versionMismatchDismissKey =
versionMismatch && activeThread
? buildVersionMismatchDismissalKey(activeThread.environmentId, versionMismatch)
: null;
const [dismissedVersionMismatchKey, setDismissedVersionMismatchKey] = useState<string | null>(
null,
);
const versionMismatchDismissed =
versionMismatchDismissKey === dismissedVersionMismatchKey ||
isVersionMismatchDismissed(versionMismatchDismissKey);
const showVersionMismatchBanner =
versionMismatch !== null && versionMismatchDismissKey !== null && !versionMismatchDismissed;
const hasMultipleRegisteredEnvironments = Object.keys(savedEnvironmentRegistry).length > 0;
const versionMismatchServerLabel = useMemo(() => {
if (!hasMultipleRegisteredEnvironments || !activeThread) {
return "server";
}
const isPrimary = activeThread.environmentId === primaryEnvironmentId;
const savedRecord = savedEnvironmentRegistry[activeThread.environmentId];
const runtimeState = savedEnvironmentRuntimeById[activeThread.environmentId];
return `${resolveEnvironmentOptionLabel({
isPrimary,
environmentId: activeThread.environmentId,
runtimeLabel: runtimeState?.descriptor?.label ?? serverConfig?.environment.label ?? null,
savedLabel: savedRecord?.label ?? null,
})} server`;
}, [
activeThread,
hasMultipleRegisteredEnvironments,
primaryEnvironmentId,
savedEnvironmentRegistry,
savedEnvironmentRuntimeById,
serverConfig?.environment.label,
]);
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
const items: ComposerBannerStackItem[] = [];
if (activeEnvironmentUnavailableState) {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant:
activeEnvironmentUnavailableState.connectionState === "error" ? "error" : "warning",
icon: <WifiOffIcon />,
title: (
<>
{activeEnvironmentUnavailableState.label} is{" "}
{activeEnvironmentUnavailableState.connectionState === "connecting"
? "connecting"
: "disconnected"}
</>
),
description: "Reconnect this environment before sending messages or running actions.",
actions: (
<>
<Button
size="xs"
disabled={
activeEnvironmentUnavailableState.connectionState === "connecting" ||
reconnectingEnvironmentId === activeEnvironmentUnavailableState.environmentId
}
onClick={() =>
void handleReconnectActiveEnvironment(
activeEnvironmentUnavailableState.environmentId,
activeEnvironmentUnavailableState.label,
)
}
>
{activeEnvironmentUnavailableState.connectionState === "connecting" ||
reconnectingEnvironmentId === activeEnvironmentUnavailableState.environmentId
? "Reconnecting..."
: "Reconnect"}
</Button>
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</>
),
});
}
if (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey) {
items.push({
id: `version-mismatch:${versionMismatchDismissKey}`,
variant: "warning",
icon: <TriangleAlertIcon />,
title: "Client and server versions differ",
description: (
<>
Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "}
{versionMismatch.serverVersion}. Sync them if RPC calls or reconnects fail.
</>
),
dismissLabel: "Dismiss version mismatch warning",
onDismiss: () => {
dismissVersionMismatch(versionMismatchDismissKey);
setDismissedVersionMismatchKey(versionMismatchDismissKey);
},
});
}
return items;
}, [
activeEnvironmentUnavailableState,
handleReconnectActiveEnvironment,
navigate,
reconnectingEnvironmentId,
showVersionMismatchBanner,
versionMismatch,
versionMismatchDismissKey,
versionMismatchServerLabel,
]);
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
const unlockedSelectedProvider = resolveSelectableProvider(
providerStatuses,
@@ -2354,6 +2554,13 @@ export default function ChatView(props: ChatViewProps) {
const localApi = readLocalApi();
if (!api || !localApi || !activeThread || isRevertingCheckpoint) return;
if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
setThreadError(
activeThread.id,
`Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
);
return;
}
if (phase === "running" || isSendBusy || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
@@ -2389,6 +2596,8 @@ export default function ChatView(props: ChatViewProps) {
},
[
activeThread,
activeEnvironmentUnavailable,
activeEnvironmentUnavailableLabel,
environmentId,
isConnecting,
isRevertingCheckpoint,
@@ -2401,7 +2610,15 @@ export default function ChatView(props: ChatViewProps) {
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const api = readEnvironmentApi(environmentId);
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (
!api ||
!activeThread ||
isSendBusy ||
isConnecting ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
)
return;
if (activePendingProgress) {
onAdvanceActivePendingUserInput();
return;
@@ -3022,6 +3239,7 @@ export default function ChatView(props: ChatViewProps) {
!isServerThread ||
isSendBusy ||
isConnecting ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
) {
return;
@@ -3136,6 +3354,7 @@ export default function ChatView(props: ChatViewProps) {
activeThreadBranch,
activeThread,
beginLocalDispatch,
activeEnvironmentUnavailable,
isConnecting,
isSendBusy,
isServerThread,
@@ -3382,74 +3601,82 @@ export default function ChatView(props: ChatViewProps) {
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
<ChatComposer
ref={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
shouldAutoScrollRef={isAtEndRef}
scheduleStickToBottom={scrollToEnd}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={onPreviousActivePendingUserInputQuestion}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
<div className="relative isolate">
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
<div className="relative z-10">
<ChatComposer
ref={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
shouldAutoScrollRef={isAtEndRef}
scheduleStickToBottom={scrollToEnd}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
</div>
</div>
{isGitRepo && (
<BranchToolbar
environmentId={activeThread.environmentId}
@@ -3468,12 +3695,8 @@ export default function ChatView(props: ChatViewProps) {
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments
? {
availableEnvironments: logicalProjectEnvironments,
onEnvironmentChange,
}
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
)}
</div>
@@ -17,6 +17,7 @@ export interface CommandPaletteItem {
readonly description?: string;
readonly timestamp?: string;
readonly icon: ReactNode;
readonly disabled?: boolean;
/** Optional content rendered inline before the title text. */
readonly titleLeadingContent?: ReactNode;
/** Optional content rendered inline after the title text (before the timestamp). */
+280 -163
View File
@@ -7,11 +7,13 @@ import {
type FilesystemBrowseResult,
type ProjectId,
ProviderInstanceId,
type SourceControlDiscoveryResult,
type SourceControlProviderKind,
type SourceControlRepositoryInfo,
} from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { Option } from "effect";
import {
ArrowDownIcon,
ArrowLeftIcon,
@@ -28,6 +30,7 @@ import {
useCallback,
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -45,6 +48,10 @@ import {
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useSettings } from "../hooks/useSettings";
import { readLocalApi } from "../localApi";
import {
getSourceControlDiscoverySnapshot,
refreshSourceControlDiscovery,
} from "../lib/sourceControlDiscoveryState";
import {
startNewThreadInProjectFromContext,
startNewThreadFromContext,
@@ -92,7 +99,7 @@ import {
} from "./CommandPalette.logic";
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { GitHubIcon, GitLabIcon } from "./Icons";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
import { ProjectFavicon } from "./ProjectFavicon";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { useServerKeybindings } from "../rpc/serverState";
@@ -108,6 +115,7 @@ import {
import { Button } from "./ui/button";
import { Kbd, KbdGroup } from "./ui/kbd";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
import type { ChatComposerHandle } from "./chat/ChatComposer";
@@ -143,7 +151,10 @@ interface AddProjectEnvironmentOption {
readonly isPrimary: boolean;
}
type AddProjectRemoteProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
type AddProjectRemoteProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "bitbucket" | "azure-devops"
>;
type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
type AddProjectCloneFlow =
@@ -161,7 +172,19 @@ type AddProjectCloneFlow =
readonly remoteUrl: string;
};
const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = ["github", "gitlab", "url"];
const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
"url",
"github",
"gitlab",
"bitbucket",
"azure-devops",
];
const REMOTE_PROJECT_PROVIDER_SOURCES: ReadonlyArray<AddProjectRemoteProviderKind> = [
"github",
"gitlab",
"bitbucket",
"azure-devops",
];
function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
switch (source) {
@@ -169,11 +192,30 @@ function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
return "GitHub";
case "gitlab":
return "GitLab";
case "bitbucket":
return "Bitbucket";
case "azure-devops":
return "Azure DevOps";
case "url":
return "Git URL";
}
}
function remoteProjectSourcePathHint(source: AddProjectRemoteSource): string {
switch (source) {
case "github":
return "owner/repo";
case "gitlab":
return "group/project";
case "bitbucket":
return "workspace/repository";
case "azure-devops":
return "project/repository";
case "url":
return "URL";
}
}
function remoteProjectSourceProvider(
source: AddProjectRemoteSource,
): AddProjectRemoteProviderKind | null {
@@ -186,6 +228,10 @@ function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: stri
return <GitHubIcon className={className} />;
case "gitlab":
return <GitLabIcon className={className} />;
case "bitbucket":
return <BitbucketIcon className={className} />;
case "azure-devops":
return <AzureDevOpsIcon className={className} />;
case "url":
return <LinkIcon className={className} />;
}
@@ -197,7 +243,80 @@ function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string
if (flow.source === "url") {
return "Enter Git clone URL";
}
return `Enter ${remoteProjectSourceLabel(flow.source)} repository (owner/repo)`;
return `Enter ${remoteProjectSourceLabel(flow.source)} repository (${remoteProjectSourcePathHint(flow.source)})`;
}
function sourceProviderKind(source: AddProjectRemoteSource): AddProjectRemoteProviderKind | null {
return source === "url" ? null : source;
}
function sortAddProjectProviderSources(
readinessBySource: AddProjectRemoteSourceReadiness,
): ReadonlyArray<AddProjectRemoteProviderKind> {
return REMOTE_PROJECT_PROVIDER_SOURCES.toSorted((left, right) => {
const leftReady = readinessBySource[left].ready;
const rightReady = readinessBySource[right].ready;
if (leftReady !== rightReady) {
return leftReady ? -1 : 1;
}
return remoteProjectSourceLabel(left).localeCompare(remoteProjectSourceLabel(right));
});
}
type AddProjectRemoteSourceReadiness = Record<
AddProjectRemoteSource,
{ readonly ready: boolean; readonly hint: string | null }
>;
function buildAddProjectRemoteSourceReadiness(
discovery: SourceControlDiscoveryResult | null,
): AddProjectRemoteSourceReadiness {
const unavailable = {
ready: false,
hint: "Provider status unavailable. Open Settings -> Source Control and rescan.",
} as const;
const defaultReadiness: AddProjectRemoteSourceReadiness = {
url: { ready: true, hint: null },
github: unavailable,
gitlab: unavailable,
bitbucket: unavailable,
"azure-devops": unavailable,
};
if (!discovery) {
return defaultReadiness;
}
const providerByKind = new Map(
discovery.sourceControlProviders.map((provider) => [provider.kind, provider]),
);
const readiness = { ...defaultReadiness };
for (const source of REMOTE_PROJECT_SOURCES) {
const kind = sourceProviderKind(source);
if (!kind) continue;
const provider = providerByKind.get(kind);
if (!provider) {
readiness[source] = unavailable;
continue;
}
if (provider.status !== "available") {
readiness[source] = { ready: false, hint: provider.installHint };
continue;
}
if (provider.auth.status === "unauthenticated") {
readiness[source] = {
ready: false,
hint:
Option.getOrNull(provider.auth.detail) ??
`${provider.label} is not authenticated. Open Settings -> Source Control for setup guidance.`,
};
continue;
}
readiness[source] = { ready: true, hint: null };
}
return readiness;
}
function errorMessage(error: unknown): string {
@@ -658,6 +777,145 @@ function OpenCommandPaletteDialog() {
[],
);
const openSourceControlSettings = useCallback(() => {
setOpen(false);
void navigate({ to: "/settings/source-control" });
}, [navigate, setOpen]);
const buildAddProjectSourceGroups = useCallback(
(
environmentId: EnvironmentId,
readinessBySource: AddProjectRemoteSourceReadiness,
): CommandPaletteView["groups"] => {
const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [
{
kind: "action",
value: `action:add-project:${environmentId}:local`,
searchTerms: ["local", "folder", "directory", "browse"],
title: "Local folder",
description: "Browse a folder on disk",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
startAddProjectBrowse(environmentId);
},
},
];
const orderedSources: ReadonlyArray<AddProjectRemoteSource> = [
"url",
...sortAddProjectProviderSources(readinessBySource),
];
for (const source of orderedSources) {
const label = remoteProjectSourceLabel(source);
const title = source === "url" ? "Git URL" : `${label} repository`;
const description =
source === "url"
? "Clone from a remote URL"
: `Clone ${label} ${remoteProjectSourcePathHint(source)}`;
const readiness = readinessBySource[source];
const disabledHint = readiness.hint;
const titleTrailingContent = readiness.ready ? undefined : (
<span className="ml-auto">
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
className="h-5 rounded-[.25rem] px-1.5 text-[10px] text-warning-foreground"
onClick={() => {
openSourceControlSettings();
}}
>
Setup Required
</Button>
}
/>
<TooltipPopup align="end" side="left">
{disabledHint ?? "Open Settings -> Source Control to configure this provider."}
</TooltipPopup>
</Tooltip>
</span>
);
if (!readiness.ready) {
sourceItems.push({
kind: "action",
value: `action:add-project:${environmentId}:${source}:not-ready`,
searchTerms: ["clone", "remote", "repository", "repo", "git", label, "setup required"],
title,
description,
disabled: true,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
...(titleTrailingContent ? { titleTrailingContent } : {}),
run: async () => {},
});
continue;
}
sourceItems.push({
kind: "action",
value: `action:add-project:${environmentId}:${source}`,
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
title,
description,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
...(titleTrailingContent ? { titleTrailingContent } : {}),
keepOpen: true,
run: async () => {
startAddProjectClone(environmentId, source);
},
});
}
return [{ value: `sources:${environmentId}`, label: "Sources", items: sourceItems }];
},
[openSourceControlSettings, startAddProjectBrowse, startAddProjectClone],
);
const startAddProjectSourceSelection = useCallback(
(environmentId: EnvironmentId): void => {
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow(null);
const target = { environmentId };
const initialDiscovery = getSourceControlDiscoverySnapshot(target).data;
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: buildAddProjectSourceGroups(
environmentId,
buildAddProjectRemoteSourceReadiness(initialDiscovery),
),
});
if (initialDiscovery) {
return;
}
void refreshSourceControlDiscovery(target).then((discovery) => {
setViewStack((previousViews) => {
const currentTopView = previousViews.at(-1);
if (currentTopView?.groups[0]?.value !== `sources:${environmentId}`) {
return previousViews;
}
return [
...previousViews.slice(0, -1),
{
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: buildAddProjectSourceGroups(
environmentId,
buildAddProjectRemoteSourceReadiness(discovery),
),
},
];
});
});
},
[buildAddProjectSourceGroups],
);
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
(option) => ({
kind: "action",
@@ -668,7 +926,7 @@ function OpenCommandPaletteDialog() {
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
startAddProjectBrowse(option.environmentId);
startAddProjectSourceSelection(option.environmentId);
},
}),
);
@@ -684,156 +942,6 @@ function OpenCommandPaletteDialog() {
[addProjectEnvironmentItems],
);
const addProjectRemoteEnvironmentGroups = useMemo<
Record<AddProjectRemoteSource, CommandPaletteView["groups"]>
>(() => {
const buildGroups = (source: AddProjectRemoteSource): CommandPaletteView["groups"] => [
{
value: `environments:${source}`,
label: "Environments",
items: addProjectEnvironmentOptions.map((option) => ({
kind: "action" as const,
value: `action:add-project:${source}:environment:${option.environmentId}`,
searchTerms: [
option.label,
option.environmentId,
option.isPrimary ? "this device" : "",
remoteProjectSourceLabel(source),
],
title: option.label,
description: option.isPrimary ? "This device" : option.environmentId,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
keepOpen: true,
run: async () => {
startAddProjectClone(option.environmentId, source);
},
})),
},
];
return {
github: buildGroups("github"),
gitlab: buildGroups("gitlab"),
url: buildGroups("url"),
};
}, [addProjectEnvironmentOptions, startAddProjectClone]);
const openAddProjectCloneFlow = useCallback(
(source: AddProjectRemoteSource) => {
if (addProjectEnvironmentOptions.length > 1) {
pushPaletteView({
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
groups: addProjectRemoteEnvironmentGroups[source],
});
return;
}
const environmentId = defaultAddProjectEnvironmentId;
if (!environmentId) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to clone project",
description: "No environment is available.",
}),
);
return;
}
startAddProjectClone(environmentId, source);
},
[
addProjectEnvironmentOptions.length,
addProjectRemoteEnvironmentGroups,
defaultAddProjectEnvironmentId,
startAddProjectClone,
],
);
const addProjectSourceGroups = useMemo<CommandPaletteView["groups"]>(() => {
const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (addProjectEnvironmentOptions.length > 1) {
sourceItems.push({
kind: "submenu",
value: "action:add-project:local",
searchTerms: ["local", "folder", "directory", "browse", "environment"],
title: "Local folder",
description: "Browse a folder on disk",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
});
} else {
sourceItems.push({
kind: "action",
value: "action:add-project:local",
searchTerms: ["local", "folder", "directory", "browse"],
title: "Local folder",
description: "Browse a folder on disk",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
const environmentId = defaultAddProjectEnvironmentId;
if (!environmentId) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to browse projects",
description: "No environment is available.",
}),
);
return;
}
startAddProjectBrowse(environmentId);
},
});
}
for (const source of REMOTE_PROJECT_SOURCES) {
const label = remoteProjectSourceLabel(source);
const title = source === "url" ? "Git URL" : `${label} repository`;
const description =
source === "url" ? "Clone from a remote URL" : `Clone ${label} owner/repo`;
if (addProjectEnvironmentOptions.length > 1) {
sourceItems.push({
kind: "submenu",
value: `action:add-project:${source}`,
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
title,
description,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
groups: addProjectRemoteEnvironmentGroups[source],
});
continue;
}
sourceItems.push({
kind: "action",
value: `action:add-project:${source}`,
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
title,
description,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
keepOpen: true,
run: async () => {
openAddProjectCloneFlow(source);
},
});
}
return [{ value: "sources", label: "Sources", items: sourceItems }];
}, [
addProjectEnvironmentGroups,
addProjectEnvironmentOptions.length,
addProjectRemoteEnvironmentGroups,
defaultAddProjectEnvironmentId,
openAddProjectCloneFlow,
startAddProjectBrowse,
]);
const openAddProjectFlow = useCallback(() => {
if (addProjectEnvironmentOptions.length > 1) {
pushPaletteView({
@@ -855,15 +963,15 @@ function OpenCommandPaletteDialog() {
return;
}
startAddProjectBrowse(environmentId);
void startAddProjectSourceSelection(environmentId);
}, [
addProjectEnvironmentGroups,
addProjectEnvironmentOptions.length,
defaultAddProjectEnvironmentId,
startAddProjectBrowse,
startAddProjectSourceSelection,
]);
useEffect(() => {
useLayoutEffect(() => {
if (openIntent?.kind !== "add-project") {
return;
}
@@ -914,7 +1022,7 @@ function OpenCommandPaletteDialog() {
}
actionItems.push({
kind: "submenu",
kind: "action",
value: "action:add-project",
searchTerms: [
"add project",
@@ -928,13 +1036,18 @@ function OpenCommandPaletteDialog() {
"git",
"github",
"gitlab",
"bitbucket",
"azure",
"devops",
"url",
"environment",
],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectSourceGroups,
keepOpen: true,
run: async () => {
openAddProjectFlow();
},
});
actionItems.push({
@@ -1355,6 +1468,10 @@ function OpenCommandPaletteDialog() {
}
function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
if (item.disabled) {
return;
}
if (item.kind === "submenu") {
pushView(item);
return;
@@ -1471,7 +1588,7 @@ function OpenCommandPaletteDialog() {
variant="outline"
size="xs"
tabIndex={-1}
className="absolute end-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
className="absolute inset-e-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
aria-label={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
disabled={!canSubmitRemoteProjectFlow}
onMouseDown={(event) => {
@@ -1493,7 +1610,7 @@ function OpenCommandPaletteDialog() {
size="xs"
tabIndex={-1}
className={cn(
"absolute end-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
"absolute inset-e-2.5 top-1/2 pe-1 ps-2 -translate-y-1/2",
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
@@ -43,15 +43,19 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
<CommandGroup items={group.items} key={group.value}>
<CommandGroupLabel>{group.label}</CommandGroupLabel>
<CommandCollection>
{(item) => (
<CommandPaletteResultRow
item={item}
key={item.value}
keybindings={props.keybindings}
isActive={props.highlightedItemValue === item.value}
onExecuteItem={props.onExecuteItem}
/>
)}
{(item) =>
item.disabled ? (
<DisabledCommandPaletteResultRow item={item} key={item.value} />
) : (
<CommandPaletteResultRow
item={item}
key={item.value}
keybindings={props.keybindings}
isActive={props.highlightedItemValue === item.value}
onExecuteItem={props.onExecuteItem}
/>
)
}
</CommandCollection>
</CommandGroup>
))}
@@ -59,6 +63,33 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
);
}
function DisabledCommandPaletteResultRow(props: {
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
}) {
return (
<div className="flex min-h-8 select-none items-center gap-2 rounded-sm px-2 py-1.5 text-base opacity-64 sm:min-h-7 sm:text-sm">
{props.item.icon}
{props.item.description ? (
<span className="flex min-w-0 flex-1 flex-col">
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
</span>
<span className="truncate text-muted-foreground/70 text-xs">
{props.item.description}
</span>
</span>
) : (
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
</span>
)}
{props.item.titleTrailingContent}
</div>
);
}
function CommandPaletteResultRow(props: {
item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
isActive: boolean;
@@ -89,7 +120,6 @@ function CommandPaletteResultRow(props: {
<span className="flex min-w-0 items-center gap-1.5 text-sm text-foreground">
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
{props.item.titleTrailingContent}
</span>
<span className="truncate text-muted-foreground/70 text-xs">
{props.item.description}
@@ -99,9 +129,9 @@ function CommandPaletteResultRow(props: {
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-sm text-foreground">
{props.item.titleLeadingContent}
<span className="truncate">{props.item.title}</span>
{props.item.titleTrailingContent}
</span>
)}
{props.item.titleTrailingContent}
{props.item.timestamp ? (
<span className="min-w-12 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground/70">
{props.item.timestamp}
File diff suppressed because it is too large. Load diff
@@ -289,7 +289,7 @@ function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
version: 1,
type: "keybindingsUpdated",
payload: { issues },
payload: { keybindings: fixture.serverConfig.keybindings, issues },
});
}
+20 -6
View File
@@ -10,15 +10,29 @@ export function ProjectFavicon(input: {
cwd: string;
className?: string;
}) {
const src = resolveEnvironmentHttpUrl({
environmentId: input.environmentId,
pathname: "/api/project-favicon",
searchParams: { cwd: input.cwd },
});
const src = (() => {
try {
return resolveEnvironmentHttpUrl({
environmentId: input.environmentId,
pathname: "/api/project-favicon",
searchParams: { cwd: input.cwd },
});
} catch {
return null;
}
})();
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
src && loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
);
if (!src) {
return (
<FolderIcon
className={`size-3.5 shrink-0 text-muted-foreground/50 ${input.className ?? ""}`}
/>
);
}
return (
<>
{status !== "loaded" ? (
@@ -8,6 +8,7 @@ function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionSt
attemptCount: 0,
closeCode: null,
closeReason: null,
connectionLabel: null,
connectedAt: null,
disconnectedAt: null,
hasConnected: false,
@@ -53,8 +53,16 @@ function describeExhaustedToast(): string {
return "Retries exhausted trying to reconnect";
}
function buildReconnectTitle(_status: WsConnectionStatus): string {
return "Disconnected from T3 Server";
function getConnectionDisplayName(status: WsConnectionStatus): string {
return status.connectionLabel?.trim() || "T3 Server";
}
function buildReconnectTitle(status: WsConnectionStatus): string {
return `Disconnected from ${getConnectionDisplayName(status)}`;
}
function buildRecoveredTitle(status: WsConnectionStatus): string {
return `Reconnected to ${getConnectionDisplayName(status)}`;
}
function describeRecoveredToast(
@@ -297,7 +305,7 @@ export function WebSocketConnectionCoordinator() {
},
description: describeExhaustedToast(),
timeout: 0,
title: "Disconnected from T3 Server",
title: buildReconnectTitle(status),
type: "error",
})
: stackedThreadToast({
@@ -334,7 +342,7 @@ export function WebSocketConnectionCoordinator() {
) {
const successToast = {
description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt),
title: "Reconnected to T3 Server",
title: buildRecoveredTitle(status),
type: "success" as const,
timeout: 0,
data: {
@@ -2,11 +2,13 @@ import type { AuthSessionState } from "@t3tools/contracts";
import React, { startTransition, useEffect, useRef, useState, useCallback } from "react";
import { APP_DISPLAY_NAME } from "../../branding";
import { addSavedEnvironment } from "../../environments/runtime";
import {
peekPairingTokenFromUrl,
stripPairingTokenFromUrl,
submitServerAuthCredential,
} from "../../environments/primary";
import { readHostedPairingRequest } from "../../hostedPairing";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
@@ -159,6 +161,127 @@ export function PairingRouteSurface({
);
}
export function HostedPairingRouteSurface() {
const hostedPairingRequestRef = useRef(readHostedPairingRequest());
const [status, setStatus] = useState<"pairing" | "paired" | "error">(() =>
hostedPairingRequestRef.current ? "pairing" : "error",
);
const [message, setMessage] = useState(() =>
hostedPairingRequestRef.current
? "Connecting to this backend."
: "This pairing link is missing its backend host or token.",
);
const [canRetry, setCanRetry] = useState(false);
const submitAttemptedRef = useRef(false);
const tokenSubmittedRef = useRef(false);
const submitHostedPairingRequest = useCallback(async () => {
const request = hostedPairingRequestRef.current;
if (!request) {
setStatus("error");
setMessage("This pairing link is missing its backend host or token.");
setCanRetry(false);
return;
}
if (tokenSubmittedRef.current) {
setStatus("error");
setMessage("This one-time pairing token was already submitted. Request a new pairing link.");
setCanRetry(false);
return;
}
setStatus("pairing");
setMessage("Connecting to this backend.");
setCanRetry(false);
tokenSubmittedRef.current = true;
try {
const record = await addSavedEnvironment({
label: request.label,
host: request.host,
pairingCode: request.token,
});
setStatus("paired");
setMessage(`${record.label} is saved in this browser.`);
} catch (error) {
tokenSubmittedRef.current = false;
setStatus("error");
setCanRetry(true);
setMessage(
`${errorMessageFromUnknown(error)} If the backend accepted this one-time token, request a new pairing link before retrying.`,
);
}
}, []);
useEffect(() => {
if (submitAttemptedRef.current) {
return;
}
submitAttemptedRef.current = true;
stripPairingTokenFromUrl();
void submitHostedPairingRequest();
}, [submitHostedPairingRequest]);
const request = hostedPairingRequestRef.current;
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
<div className="pointer-events-none absolute inset-0 opacity-80">
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-emerald-500)_14%,transparent),transparent)]" />
<div className="absolute inset-y-0 left-0 w-72 bg-[radial-gradient(28rem_18rem_at_left,color-mix(in_srgb,var(--color-sky-500)_10%,transparent),transparent)]" />
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
</div>
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
{APP_DISPLAY_NAME}
</p>
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
{status === "paired"
? "Backend paired"
: status === "error"
? "Pairing failed"
: "Pairing backend"}
</h1>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
{request ? (
<div className="mt-5 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
Host: <span className="font-mono text-foreground/80">{request.host}</span>
</div>
) : null}
{status === "error" ? (
<div className="mt-5 rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
Verify the backend is reachable from this browser, supports CORS for hosted clients, and
is served over HTTPS when opening this page from HTTPS.
</div>
) : null}
<div className="mt-6 flex flex-wrap gap-2">
{status === "pairing" ? (
<Button disabled size="sm">
Pairing...
</Button>
) : canRetry ? (
<Button size="sm" onClick={() => void submitHostedPairingRequest()}>
Try again
</Button>
) : null}
{status === "paired" ? (
<Button size="sm" variant="outline" onClick={() => (window.location.href = "/")}>
Open app
</Button>
) : null}
</div>
</section>
</div>
);
}
function errorMessageFromUnknown(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
+406 -105
View File
@@ -71,6 +71,7 @@ import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
import { expandMobileComposerForKeyboard } from "./mobileComposerFocus";
import {
getComposerProviderState,
renderProviderTraitsMenuContent,
@@ -111,6 +112,7 @@ import type { PendingApproval, PendingUserInput } from "../../session-logic";
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -289,7 +291,9 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
promptHasText: boolean;
isSendBusy: boolean;
isConnecting: boolean;
isEnvironmentUnavailable: boolean;
hasSendableContent: boolean;
preserveComposerFocusOnPointerDown?: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
@@ -308,8 +312,10 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
promptHasText={props.promptHasText}
isSendBusy={props.isSendBusy}
isConnecting={props.isConnecting}
isEnvironmentUnavailable={props.isEnvironmentUnavailable}
isPreparingWorktree={props.isPreparingWorktree}
hasSendableContent={props.hasSendableContent}
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
onInterrupt={props.onInterrupt}
onImplementPlanInNewThread={props.onImplementPlanInNewThread}
@@ -379,6 +385,10 @@ export interface ChatComposerProps {
isConnecting: boolean;
isSendBusy: boolean;
isPreparingWorktree: boolean;
environmentUnavailable: {
readonly label: string;
readonly connectionState: "connecting" | "disconnected" | "error";
} | null;
// Pending approvals / inputs
activePendingApproval: PendingApproval | null;
@@ -389,7 +399,7 @@ export interface ChatComposerProps {
isLastQuestion: boolean;
canAdvance: boolean;
customAnswer: string;
activeQuestion: { id: string } | null;
activeQuestion: { id: string; multiSelect?: boolean | undefined } | null;
} | null;
activePendingResolvedAnswers: Record<string, unknown> | null;
activePendingIsResponding: boolean;
@@ -486,6 +496,7 @@ export const ChatComposer = memo(
isConnecting,
isSendBusy,
isPreparingWorktree,
environmentUnavailable,
activePendingApproval,
pendingApprovals,
pendingUserInputs,
@@ -774,17 +785,28 @@ export const ChatComposer = memo(
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const [isComposerCompactMenuOpen, setIsComposerCompactMenuOpen] = useState(false);
const isMobileViewport = useMediaQuery("max-sm");
const isMobileFloatingLayerOpen = isComposerModelPickerOpen || isComposerCompactMenuOpen;
const mobileCollapsedOnlyClassName =
"sm:hidden max-sm:group-focus-within/composer:hidden max-sm:group-data-[mobile-focus-primed=true]/composer:hidden max-sm:group-data-[mobile-floating-open=true]/composer:hidden";
const mobileExpandedOnlyClassName =
"max-sm:hidden max-sm:group-focus-within/composer:block max-sm:group-data-[mobile-focus-primed=true]/composer:block max-sm:group-data-[mobile-floating-open=true]/composer:block";
const mobileExpandedFlexOnlyClassName =
"max-sm:hidden max-sm:group-focus-within/composer:flex max-sm:group-data-[mobile-focus-primed=true]/composer:flex max-sm:group-data-[mobile-floating-open=true]/composer:flex";
// ------------------------------------------------------------------
// Refs
// ------------------------------------------------------------------
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerSurfaceRef = useRef<HTMLDivElement>(null);
const composerFormHeightRef = useRef(0);
const composerSelectLockRef = useRef(false);
const composerMenuOpenRef = useRef(false);
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null);
const mobileComposerPrimeReleaseFrameRef = useRef<number | null>(null);
const dragDepthRef = useRef(0);
// ------------------------------------------------------------------
@@ -929,6 +951,7 @@ export const ChatComposer = memo(
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
(showPlanFollowUpPrompt && activeProposedPlan !== null);
const showCollapsedMobilePromptRow = !isComposerApprovalState && pendingUserInputs.length === 0;
const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null;
const showPlanSidebarToggle = Boolean(activePlan || sidebarProposedPlan || planSidebarOpen);
@@ -1021,6 +1044,10 @@ export const ChatComposer = memo(
: null,
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
);
const collapsedComposerPrimaryActionDisabled =
phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions = isMobileViewport && pendingPrimaryAction !== null;
// ------------------------------------------------------------------
// Prompt helpers
@@ -1550,6 +1577,69 @@ export const ChatComposer = memo(
[composerHighlightedItemId, composerMenuItems],
);
const blurMobileComposerAfterSend = useCallback(() => {
if (!isMobileViewport) return;
if (mobileComposerPrimeReleaseFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerPrimeReleaseFrameRef.current);
mobileComposerPrimeReleaseFrameRef.current = null;
}
composerSurfaceRef.current?.setAttribute("data-mobile-focus-primed", "false");
const activeElement = document.activeElement;
if (activeElement instanceof HTMLElement) {
activeElement.blur();
}
}, [isMobileViewport]);
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
return showPlanFollowUpPrompt || composerSendState.hasSendableContent;
}, [
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
isConnecting,
isMobileViewport,
isSendBusy,
phase,
showPlanFollowUpPrompt,
]);
const submitComposer = useCallback(
(event?: { preventDefault: () => void }) => {
onSend(event);
if (shouldBlurMobileComposerOnSubmit()) {
blurMobileComposerAfterSend();
}
},
[blurMobileComposerAfterSend, onSend, shouldBlurMobileComposerOnSubmit],
);
const expandMobileComposer = useCallback(() => {
expandMobileComposerForKeyboard({
cancelPendingRelease: () => {
if (mobileComposerPrimeReleaseFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerPrimeReleaseFrameRef.current);
mobileComposerPrimeReleaseFrameRef.current = null;
}
},
primeExpandedState: () => {
composerSurfaceRef.current?.setAttribute("data-mobile-focus-primed", "true");
},
focusEditorAtEnd: () => {
composerEditorRef.current?.focusAtEnd();
},
scheduleRelease: () => {
mobileComposerPrimeReleaseFrameRef.current = window.requestAnimationFrame(() => {
mobileComposerPrimeReleaseFrameRef.current = null;
composerSurfaceRef.current?.setAttribute("data-mobile-focus-primed", "false");
});
},
});
}, []);
// ------------------------------------------------------------------
// Callbacks: command key
// ------------------------------------------------------------------
@@ -1580,7 +1670,7 @@ export const ChatComposer = memo(
}
}
if (key === "Enter" && !event.shiftKey) {
void onSend();
submitComposer();
return true;
}
return false;
@@ -1690,6 +1780,13 @@ export const ChatComposer = memo(
const handleImplementPlanInNewThreadPrimaryAction = useCallback(() => {
void onImplementPlanInNewThread();
}, [onImplementPlanInNewThread]);
useEffect(() => {
return () => {
if (mobileComposerPrimeReleaseFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerPrimeReleaseFrameRef.current);
}
};
}, []);
// ------------------------------------------------------------------
// Imperative handle
@@ -1803,7 +1900,7 @@ export const ChatComposer = memo(
return (
<form
ref={composerFormRef}
onSubmit={onSend}
onSubmit={submitComposer}
className="mx-auto w-full min-w-0 max-w-208"
data-chat-composer-form="true"
>
@@ -1818,21 +1915,35 @@ export const ChatComposer = memo(
onDrop={onComposerDrop}
>
<div
ref={composerSurfaceRef}
data-mobile-focus-primed="false"
data-mobile-floating-open={isMobileFloatingLayerOpen ? "true" : "false"}
className={cn(
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
"group/composer rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
environmentUnavailable ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
>
{activePendingApproval ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<div
className={cn(
"rounded-t-[19px] border-b border-border/65 bg-muted/20",
mobileExpandedOnlyClassName,
)}
>
<ComposerPendingApprovalPanel
approval={activePendingApproval}
pendingCount={pendingApprovals.length}
/>
</div>
) : pendingUserInputs.length > 0 ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<div
className={cn(
"rounded-t-[19px] border-b border-border/65 bg-muted/20",
mobileExpandedOnlyClassName,
)}
>
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
respondingRequestIds={respondingRequestIds}
@@ -1843,7 +1954,12 @@ export const ChatComposer = memo(
/>
</div>
) : showPlanFollowUpPrompt && activeProposedPlan ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<div
className={cn(
"rounded-t-[19px] border-b border-border/65 bg-muted/20",
mobileExpandedOnlyClassName,
)}
>
<ComposerPlanFollowUpBanner
key={activeProposedPlan.id}
planTitle={proposedPlanTitle(activeProposedPlan.planMarkdown) ?? null}
@@ -1851,10 +1967,147 @@ export const ChatComposer = memo(
</div>
) : null}
{activePendingApproval ? (
<div
className={cn(
"rounded-t-[19px] border-b border-border/65 bg-muted/20",
mobileCollapsedOnlyClassName,
)}
data-chat-composer-collapsed-controls="true"
>
<ComposerPendingApprovalPanel
approval={activePendingApproval}
pendingCount={pendingApprovals.length}
/>
<div className="flex flex-wrap items-center justify-end gap-2 px-3 pb-3 sm:px-4">
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
onRespondToApproval={onRespondToApproval}
/>
</div>
</div>
) : pendingUserInputs.length > 0 ? (
<div
className={cn(
"rounded-t-[19px] border-b border-border/65 bg-muted/20",
mobileCollapsedOnlyClassName,
)}
data-chat-composer-collapsed-controls="true"
>
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
respondingRequestIds={respondingRequestIds}
answers={activePendingDraftAnswers}
questionIndex={activePendingQuestionIndex}
onToggleOption={onSelectActivePendingUserInputOption}
onAdvance={onAdvanceActivePendingUserInput}
/>
<div className="px-3 pb-3 sm:px-4">
<div
data-chat-composer-mobile-pending-compact="true"
className={cn(
"flex min-w-0 items-center gap-2 rounded-lg border border-border/55 bg-background/55 p-1.5 pl-3 transition-colors hover:bg-background/80",
!activePendingProgress?.activeQuestion?.multiSelect && "p-0",
)}
>
<button
type="button"
className={cn(
"min-w-0 flex-1 truncate bg-transparent py-1.5 text-left text-sm",
activePendingProgress?.customAnswer
? "text-foreground"
: "text-muted-foreground/60",
!activePendingProgress?.activeQuestion?.multiSelect && "px-3 py-2",
)}
onPointerDown={(event) => {
event.preventDefault();
expandMobileComposer();
}}
onClick={expandMobileComposer}
aria-label="Write custom answer"
>
{activePendingProgress?.customAnswer || "Write custom answer"}
</button>
{activePendingProgress?.activeQuestion?.multiSelect ? (
<ComposerPrimaryActions
compact
pendingAction={pendingPrimaryAction}
isRunning={false}
showPlanFollowUpPrompt={false}
promptHasText={false}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isPreparingWorktree={false}
hasSendableContent={false}
preserveComposerFocusOnPointerDown
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
onInterrupt={handleInterruptPrimaryAction}
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
/>
) : null}
</div>
</div>
</div>
) : null}
{showCollapsedMobilePromptRow ? (
<div
className={cn(
"flex items-center justify-between gap-2 px-3 py-2",
mobileCollapsedOnlyClassName,
)}
>
<button
type="button"
className={cn(
"min-w-0 flex-1 truncate bg-transparent p-0 text-left text-[14px] focus:outline-none",
(activePendingProgress ? activePendingProgress.customAnswer : prompt.trim())
? "text-foreground"
: "text-muted-foreground/35",
)}
onPointerDown={(event) => {
event.preventDefault();
expandMobileComposer();
}}
onClick={expandMobileComposer}
aria-label="Expand composer"
>
{activePendingProgress
? activePendingProgress.customAnswer ||
"Type your own answer, or leave this blank to use the selected option"
: prompt.trim() || "Ask anything..."}
</button>
<button
type="button"
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
disabled={collapsedComposerPrimaryActionDisabled}
aria-label={collapsedComposerPrimaryActionLabel}
onPointerDown={(event) => event.preventDefault()}
onClick={(event) => {
event.stopPropagation();
submitComposer();
}}
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<path
d="M8 3L8 13M8 3L4 7M8 3L12 7"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
</div>
) : null}
<div
className={cn(
"relative px-3 pb-2 sm:px-4",
hasComposerHeader ? "pt-2.5 sm:pt-3" : "pt-3.5 sm:pt-4",
mobileExpandedOnlyClassName,
)}
>
{composerMenuOpen && !isComposerApprovalState && (
@@ -1877,110 +2130,152 @@ export const ChatComposer = memo(
)}
{!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
composerImages.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages.map((image) => (
<div
key={image.id}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
{image.previewUrl ? (
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(composerImages, image.id);
if (!preview) return;
onExpandImage(preview);
}}
>
<img
src={image.previewUrl}
alt={image.name}
className="h-full w-full object-cover"
/>
</button>
) : (
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
{image.name}
</div>
)}
{nonPersistedComposerImageIdSet.has(image.id) && (
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label="Draft attachment may not persist"
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
>
<CircleAlertIcon className="size-3" />
</span>
}
/>
<TooltipPopup
side="top"
className="max-w-64 whitespace-normal leading-tight"
>
Draft attachment could not be saved locally and may be lost on
navigation.
</TooltipPopup>
</Tooltip>
)}
<Button
variant="ghost"
size="icon-xs"
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
onClick={() => removeComposerImage(image.id)}
aria-label={`Remove ${image.name}`}
pendingUserInputs.length === 0 &&
composerImages.length > 0 ? (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages.map((image) => (
<div
key={image.id}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
{image.previewUrl ? (
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(composerImages, image.id);
if (!preview) return;
onExpandImage(preview);
}}
>
<XIcon />
</Button>
</div>
))}
</div>
)}
<img
src={image.previewUrl}
alt={image.name}
className="h-full w-full object-cover"
/>
</button>
) : (
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
{image.name}
</div>
)}
{nonPersistedComposerImageIdSet.has(image.id) && (
<Tooltip>
<TooltipTrigger
render={
<span
role="img"
aria-label="Draft attachment may not persist"
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
>
<CircleAlertIcon className="size-3" />
</span>
}
/>
<TooltipPopup
side="top"
className="max-w-64 whitespace-normal leading-tight"
>
Draft attachment could not be saved locally and may be lost on
navigation.
</TooltipPopup>
</Tooltip>
)}
<Button
variant="ghost"
size="icon-xs"
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
onClick={() => removeComposerImage(image.id)}
aria-label={`Remove ${image.name}`}
>
<XIcon />
</Button>
</div>
))}
</div>
) : null}
<ComposerPromptEditor
ref={composerEditorRef}
value={
isComposerApprovalState
? ""
: activePendingProgress
? activePendingProgress.customAnswer
: prompt
}
cursor={composerCursor}
terminalContexts={
!isComposerApprovalState && pendingUserInputs.length === 0
? composerTerminalContexts
: []
}
skills={selectedProviderStatus?.skills ?? []}
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
onChange={onPromptChange}
onCommandKeyDown={onComposerCommandKey}
onPaste={onComposerPaste}
placeholder={
isComposerApprovalState
? (activePendingApproval?.detail ?? "Resolve this approval request to continue")
: activePendingProgress
? "Type your own answer, or leave this blank to use the selected option"
: showPlanFollowUpPrompt && activeProposedPlan
? "Add feedback to refine the plan, or leave this blank to implement it"
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use / to show available commands"
}
disabled={isConnecting || isComposerApprovalState}
/>
<div className="relative">
<ComposerPromptEditor
ref={composerEditorRef}
value={
isComposerApprovalState
? ""
: activePendingProgress
? activePendingProgress.customAnswer
: prompt
}
cursor={composerCursor}
terminalContexts={
!isComposerApprovalState && pendingUserInputs.length === 0
? composerTerminalContexts
: []
}
skills={selectedProviderStatus?.skills ?? []}
{...(showMobilePendingAnswerActions ? { className: "max-sm:pb-11" } : {})}
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
onChange={onPromptChange}
onCommandKeyDown={onComposerCommandKey}
onPaste={onComposerPaste}
placeholder={
isComposerApprovalState
? (activePendingApproval?.detail ??
"Resolve this approval request to continue")
: activePendingProgress
? "Type your own answer, or leave this blank to use the selected option"
: showPlanFollowUpPrompt && activeProposedPlan
? "Add feedback to refine the plan, or leave this blank to implement it"
: environmentUnavailable
? `${environmentUnavailable.label} is ${
environmentUnavailable.connectionState === "connecting"
? "connecting"
: "disconnected"
}`
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use / to show available commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
(environmentUnavailable !== null && activePendingProgress === null)
}
/>
{showMobilePendingAnswerActions ? (
<div
data-chat-composer-mobile-pending-actions="true"
className="absolute bottom-0 right-0 flex justify-end"
>
<ComposerPrimaryActions
compact
pendingAction={pendingPrimaryAction}
isRunning={false}
showPlanFollowUpPrompt={false}
promptHasText={false}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isPreparingWorktree={false}
hasSendableContent={false}
preserveComposerFocusOnPointerDown
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
onInterrupt={handleInterruptPrimaryAction}
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
/>
</div>
) : null}
</div>
</div>
{/* Bottom toolbar */}
{activePendingApproval ? (
<div className="flex items-center justify-end gap-2 px-2.5 pb-2.5 sm:px-3 sm:pb-3">
<div
className={cn(
"flex items-center justify-end gap-2 px-2.5 pb-2.5 sm:px-3 sm:pb-3",
mobileExpandedFlexOnlyClassName,
)}
>
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
@@ -1994,6 +2289,9 @@ export const ChatComposer = memo(
className={cn(
"flex min-w-0 flex-nowrap items-center justify-between gap-2 overflow-visible px-2.5 pb-2.5 sm:px-3 sm:pb-3",
isComposerFooterCompact ? "gap-1.5" : "gap-2 sm:gap-0",
showMobilePendingAnswerActions
? "max-sm:hidden"
: mobileExpandedFlexOnlyClassName,
)}
>
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
@@ -2029,6 +2327,7 @@ export const ChatComposer = memo(
runtimeMode={runtimeMode}
showInteractionModeToggle={composerProviderControls.showInteractionModeToggle}
traitsMenuContent={providerTraitsMenuContent}
onOpenChange={setIsComposerCompactMenuOpen}
onToggleInteractionMode={toggleInteractionMode}
onTogglePlanSidebar={togglePlanSidebar}
onRuntimeModeChange={handleRuntimeModeChange}
@@ -2080,8 +2379,10 @@ export const ChatComposer = memo(
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isPreparingWorktree={isPreparingWorktree}
hasSendableContent={composerSendState.hasSendableContent}
preserveComposerFocusOnPointerDown={isMobileViewport}
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
onInterrupt={handleInterruptPrimaryAction}
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
@@ -0,0 +1,48 @@
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { shouldShowOpenInPicker } from "./ChatHeader";
describe("shouldShowOpenInPicker", () => {
const primaryEnvironmentId = EnvironmentId.make("environment-primary");
it("shows the picker for projects in the primary environment", () => {
expect(
shouldShowOpenInPicker({
activeProjectName: "codething-mvp",
activeThreadEnvironmentId: primaryEnvironmentId,
primaryEnvironmentId,
}),
).toBe(true);
});
it("hides the picker when hosted static mode has no primary environment", () => {
expect(
shouldShowOpenInPicker({
activeProjectName: "codething-mvp",
activeThreadEnvironmentId: EnvironmentId.make("environment-remote"),
primaryEnvironmentId: null,
}),
).toBe(false);
});
it("hides the picker for remote environments", () => {
expect(
shouldShowOpenInPicker({
activeProjectName: "codething-mvp",
activeThreadEnvironmentId: EnvironmentId.make("environment-remote"),
primaryEnvironmentId,
}),
).toBe(false);
});
it("hides the picker when there is no active project", () => {
expect(
shouldShowOpenInPicker({
activeProjectName: undefined,
activeThreadEnvironmentId: primaryEnvironmentId,
primaryEnvironmentId,
}),
).toBe(false);
});
});
+18 -3
View File
@@ -44,6 +44,18 @@ interface ChatHeaderProps {
onToggleDiff: () => void;
}
export function shouldShowOpenInPicker(input: {
readonly activeProjectName: string | undefined;
readonly activeThreadEnvironmentId: EnvironmentId;
readonly primaryEnvironmentId: EnvironmentId | null;
}): boolean {
return (
Boolean(input.activeProjectName) &&
input.primaryEnvironmentId !== null &&
input.activeThreadEnvironmentId === input.primaryEnvironmentId
);
}
export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
activeThreadId,
@@ -70,8 +82,11 @@ export const ChatHeader = memo(function ChatHeader({
onToggleDiff,
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const isRemoteEnvironment =
primaryEnvironmentId !== null && activeThreadEnvironmentId !== primaryEnvironmentId;
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName,
activeThreadEnvironmentId,
primaryEnvironmentId,
});
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
@@ -106,7 +121,7 @@ export const ChatHeader = memo(function ChatHeader({
onDeleteScript={onDeleteProjectScript}
/>
)}
{activeProjectName && !isRemoteEnvironment && (
{showOpenInPicker && (
<OpenInPicker
keybindings={keybindings}
availableEditors={availableEditors}
@@ -20,12 +20,13 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
runtimeMode: RuntimeMode;
showInteractionModeToggle: boolean;
traitsMenuContent?: ReactNode;
onOpenChange?: (open: boolean) => void;
onToggleInteractionMode: () => void;
onTogglePlanSidebar: () => void;
onRuntimeModeChange: (mode: RuntimeMode) => void;
}) {
return (
<Menu>
<Menu onOpenChange={(open) => props.onOpenChange?.(open)}>
<MenuTrigger
render={
<Button
@@ -0,0 +1,195 @@
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { XIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
import { Button } from "../ui/button";
const DISMISS_TRANSITION_MS = 220;
const frontExitStyle = {
opacity: 0,
transform: "translate3d(0, 4rem, 0)",
} satisfies CSSProperties;
const stackedExitStyle = {
opacity: 0,
transform: "translate3d(0, 7rem, 0)",
} satisfies CSSProperties;
const restingStyle = {
opacity: 1,
transform: "translate3d(0, 0, 0)",
} satisfies CSSProperties;
const exitTransitionStyle = {
transition: `transform ${DISMISS_TRANSITION_MS}ms ease-in, opacity ${DISMISS_TRANSITION_MS}ms ease-in`,
willChange: "transform, opacity",
} satisfies CSSProperties;
export interface ComposerBannerStackItem {
readonly id: string;
readonly variant: "error" | "info" | "success" | "warning";
readonly icon: ReactNode;
readonly title: ReactNode;
readonly description?: ReactNode;
readonly actions?: ReactNode;
readonly dismissLabel?: string;
readonly onDismiss?: () => void;
}
interface ComposerBannerStackProps {
readonly className?: string;
readonly items: ReadonlyArray<ComposerBannerStackItem>;
}
export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) {
const [exitingItemId, setExitingItemId] = useState<string | null>(null);
const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (exitingItemId && !items.some((item) => item.id === exitingItemId)) {
setExitingItemId(null);
}
}, [exitingItemId, items]);
useEffect(() => {
return () => {
if (dismissTimeoutRef.current) {
clearTimeout(dismissTimeoutRef.current);
}
};
}, []);
if (items.length === 0) {
return null;
}
const frontItem = items[0];
if (!frontItem) {
return null;
}
const stackedItems = items.slice(1);
const hasStack = stackedItems.length > 0;
const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id;
const requestDismiss = (item: ComposerBannerStackItem) => {
if (!item.onDismiss || exitingItemId) {
return;
}
setExitingItemId(item.id);
if (dismissTimeoutRef.current) {
clearTimeout(dismissTimeoutRef.current);
}
dismissTimeoutRef.current = setTimeout(() => {
dismissTimeoutRef.current = null;
item.onDismiss?.();
}, DISMISS_TRANSITION_MS);
};
return (
<div className={cn("group/banner-stack mx-auto mb-2 max-w-208", className)}>
<div
className={cn(
"relative",
hasStack ? "group-hover/banner-stack:z-50 group-focus-within/banner-stack:z-50" : null,
)}
>
{showCollapsedStackCap ? (
<div
className={cn(
"pointer-events-none absolute inset-x-0 -top-3 z-0 mx-auto h-3 rounded-t-xl",
"border border-b-0 border-warning/24 bg-background/96 shadow-[0_6px_18px_rgba(0,0,0,0.06)]",
"transition-opacity duration-150 ease-out",
"group-hover/banner-stack:opacity-0 group-focus-within/banner-stack:opacity-0",
)}
style={{ width: "96%" }}
aria-hidden="true"
/>
) : null}
<div
className={cn(
"relative z-10",
exitingItemId === frontItem.id ? "pointer-events-none" : null,
)}
style={{
...exitTransitionStyle,
...(exitingItemId === frontItem.id ? frontExitStyle : restingStyle),
}}
>
<ComposerBannerStackAlert
item={frontItem}
exiting={exitingItemId === frontItem.id}
onDismissRequest={() => requestDismiss(frontItem)}
/>
</div>
{hasStack ? (
<div
className={cn(
"pointer-events-none absolute inset-x-0 bottom-[calc(100%+0.5rem)] z-20 space-y-2 opacity-0",
"transition-[opacity,transform] duration-150 ease-out",
"translate-y-1 transform-gpu will-change-[opacity,transform]",
"group-hover/banner-stack:pointer-events-auto group-hover/banner-stack:translate-y-0 group-hover/banner-stack:opacity-100",
"group-focus-within/banner-stack:pointer-events-auto group-focus-within/banner-stack:translate-y-0 group-focus-within/banner-stack:opacity-100",
)}
>
{stackedItems.map((item) => (
<div
key={item.id}
className={cn(exitingItemId === item.id ? "pointer-events-none" : null)}
style={{
...exitTransitionStyle,
...(exitingItemId === item.id ? stackedExitStyle : restingStyle),
}}
>
<ComposerBannerStackAlert
item={item}
exiting={exitingItemId === item.id}
onDismissRequest={() => requestDismiss(item)}
/>
</div>
))}
</div>
) : null}
</div>
</div>
);
}
function ComposerBannerStackAlert({
item,
exiting,
onDismissRequest,
}: {
readonly item: ComposerBannerStackItem;
readonly exiting: boolean;
readonly onDismissRequest: () => void;
}) {
const dismissOnly = item.onDismiss && !item.actions;
return (
<Alert variant={item.variant}>
{item.icon}
<AlertTitle>{item.title}</AlertTitle>
{item.description ? <AlertDescription>{item.description}</AlertDescription> : null}
{item.actions || item.onDismiss ? (
<AlertAction
className={
dismissOnly
? "max-sm:col-start-3 max-sm:row-start-1 max-sm:mt-0 max-sm:self-start"
: undefined
}
>
{item.actions}
{item.onDismiss ? (
<Button
size="icon-xs"
variant="ghost"
aria-label={item.dismissLabel ?? "Dismiss warning"}
disabled={exiting}
onClick={onDismissRequest}
>
<XIcon className="size-3.5" />
</Button>
) : null}
</AlertAction>
) : null}
</Alert>
);
}
@@ -1,4 +1,4 @@
import { memo } from "react";
import { memo, type PointerEventHandler } from "react";
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
@@ -20,8 +20,10 @@ interface ComposerPrimaryActionsProps {
promptHasText: boolean;
isSendBusy: boolean;
isConnecting: boolean;
isEnvironmentUnavailable: boolean;
isPreparingWorktree: boolean;
hasSendableContent: boolean;
preserveComposerFocusOnPointerDown?: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
@@ -45,6 +47,10 @@ export const formatPendingPrimaryActionLabel = (input: {
return input.questionIndex > 0 ? "Submit answers" : "Submit answer";
};
const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
event.preventDefault();
};
export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
compact,
pendingAction,
@@ -53,12 +59,18 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
promptHasText,
isSendBusy,
isConnecting,
isEnvironmentUnavailable,
isPreparingWorktree,
hasSendableContent,
preserveComposerFocusOnPointerDown = false,
onPreviousPendingQuestion,
onInterrupt,
onImplementPlanInNewThread,
}: ComposerPrimaryActionsProps) {
const pointerFocusProps = preserveComposerFocusOnPointerDown
? { onPointerDown: preventPointerFocus }
: undefined;
if (pendingAction) {
return (
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
@@ -68,6 +80,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
size="icon-sm"
variant="outline"
className="rounded-full"
{...pointerFocusProps}
onClick={onPreviousPendingQuestion}
disabled={pendingAction.isResponding}
aria-label="Previous question"
@@ -79,6 +92,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
size="sm"
variant="outline"
className="rounded-full"
{...pointerFocusProps}
onClick={onPreviousPendingQuestion}
disabled={pendingAction.isResponding}
>
@@ -90,7 +104,9 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="submit"
size="sm"
className={cn("rounded-full", compact ? "px-3" : "px-4")}
{...pointerFocusProps}
disabled={
isEnvironmentUnavailable ||
pendingAction.isResponding ||
(pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance)
}
@@ -111,6 +127,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="button"
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105 sm:h-8 sm:w-8"
{...pointerFocusProps}
onClick={onInterrupt}
aria-label="Stop generation"
>
@@ -128,7 +145,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="submit"
size="sm"
className={cn("rounded-full", compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8")}
disabled={isSendBusy || isConnecting}
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
>
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
</Button>
@@ -141,7 +159,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="submit"
size="sm"
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
disabled={isSendBusy || isConnecting}
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
>
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
</Button>
@@ -153,7 +172,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
variant="default"
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
aria-label="Implementation actions"
disabled={isSendBusy || isConnecting}
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
/>
}
>
@@ -161,7 +181,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
</MenuTrigger>
<MenuPopup align="end" side="top">
<MenuItem
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
onClick={() => void onImplementPlanInNewThread()}
>
Implement in a new thread
@@ -176,15 +196,18 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={isSendBusy || isConnecting || !hasSendableContent}
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
aria-label={
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
isEnvironmentUnavailable
? "Environment disconnected"
: isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
}
>
{isConnecting || isSendBusy ? (
@@ -0,0 +1,17 @@
import { describe, expect, it, vi } from "vitest";
import { expandMobileComposerForKeyboard } from "./mobileComposerFocus";
describe("expandMobileComposerForKeyboard", () => {
it("focuses after the expanded composer is committed and before release is scheduled", () => {
const calls: string[] = [];
expandMobileComposerForKeyboard({
cancelPendingRelease: vi.fn(() => calls.push("cancel-release")),
primeExpandedState: vi.fn(() => calls.push("prime-expanded")),
focusEditorAtEnd: vi.fn(() => calls.push("focus")),
scheduleRelease: vi.fn(() => calls.push("schedule-release")),
});
expect(calls).toEqual(["cancel-release", "prime-expanded", "focus", "schedule-release"]);
});
});
@@ -0,0 +1,13 @@
export interface MobileComposerExpandOptions {
cancelPendingRelease: () => void;
primeExpandedState: () => void;
focusEditorAtEnd: () => void;
scheduleRelease: () => void;
}
export function expandMobileComposerForKeyboard(options: MobileComposerExpandOptions) {
options.cancelPendingRelease();
options.primeExpandedState();
options.focusEditorAtEnd();
options.scheduleRelease();
}
@@ -0,0 +1,221 @@
import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { useEffect, useId, useRef, useState } from "react";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
function describeSshTarget(request: DesktopSshPasswordPromptRequest): string {
return request.username ? `${request.username}@${request.destination}` : request.destination;
}
function formatRemainingSeconds(seconds: number): string {
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}
function getPromptErrorMessage(error: unknown): string {
const message = error instanceof Error ? error.message : "SSH password prompt failed.";
return message.includes("expired") || message.includes("no longer pending")
? "This SSH password prompt expired. Try connecting again."
: message;
}
export function SshPasswordPromptDialog() {
const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
const [password, setPassword] = useState("");
const [isResponding, setIsResponding] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [responseError, setResponseError] = useState<string | null>(null);
const currentRequest = queue[0] ?? null;
const inputRef = useRef<HTMLInputElement | null>(null);
const isRespondingRef = useRef(false);
const formId = useId();
useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onSshPasswordPrompt) {
return;
}
return bridge.onSshPasswordPrompt((request) => {
setQueue((currentQueue) => [...currentQueue, request]);
});
}, []);
useEffect(() => {
setPassword("");
setResponseError(null);
if (!currentRequest) {
return;
}
setNow(Date.now());
const frame = window.requestAnimationFrame(() => {
inputRef.current?.focus();
inputRef.current?.select();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [currentRequest]);
useEffect(() => {
if (!currentRequest) {
return;
}
const interval = window.setInterval(() => {
setNow(Date.now());
}, 1_000);
return () => {
window.clearInterval(interval);
};
}, [currentRequest]);
const expiresAtMs = currentRequest ? Date.parse(currentRequest.expiresAt) : Number.NaN;
const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null;
const isExpired = remainingMs !== null && remainingMs <= 0;
const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
const remainingLabel =
remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
useEffect(() => {
if (isExpired) {
setResponseError("This SSH password prompt expired. Try connecting again.");
}
}, [isExpired]);
const removeCurrentPrompt = (requestId: string) => {
setQueue((currentQueue) =>
currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue,
);
setPassword("");
setResponseError(null);
};
const respond = async (nextPassword: string | null) => {
if (!currentRequest || isRespondingRef.current) {
return;
}
const requestId = currentRequest.requestId;
if (nextPassword !== null && isExpired) {
setResponseError("This SSH password prompt expired. Try connecting again.");
return;
}
isRespondingRef.current = true;
setIsResponding(true);
setResponseError(null);
try {
await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword);
removeCurrentPrompt(requestId);
} catch (error) {
if (nextPassword === null) {
removeCurrentPrompt(requestId);
} else {
setResponseError(getPromptErrorMessage(error));
}
} finally {
isRespondingRef.current = false;
setIsResponding(false);
}
};
const dismissExpiredPrompt = () => {
if (currentRequest) {
removeCurrentPrompt(currentRequest.requestId);
}
};
const cancelPrompt = () => {
if (isExpired) {
dismissExpiredPrompt();
return;
}
void respond(null);
};
const target = currentRequest ? describeSshTarget(currentRequest) : null;
return (
<Dialog
open={currentRequest !== null}
onOpenChange={(open) => {
if (!open) {
cancelPrompt();
}
}}
>
<DialogPopup className="max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>SSH Password Required</DialogTitle>
<DialogDescription>
T3 needs your SSH password to connect to{" "}
{target ? <code>{target}</code> : "the remote host"}. The password is passed to the
local SSH process for this connection attempt and is not saved by T3 Code.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-3" scrollFade={false}>
<form
className="space-y-3"
id={formId}
onSubmit={(event) => {
event.preventDefault();
void respond(password);
}}
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>
{remainingLabel ? (
<span
className={
isExpired
? "shrink-0 text-xs font-medium text-destructive"
: "shrink-0 text-xs text-muted-foreground"
}
>
{isExpired ? "Expired" : remainingLabel}
</span>
) : null}
</div>
<Input
ref={inputRef}
autoComplete="current-password"
disabled={isResponding || isExpired}
name="ssh-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</div>
{responseError ? (
<p className="text-sm text-destructive">{responseError}</p>
) : (
<p className="text-sm text-muted-foreground">
Use SSH keys to avoid repeated password prompts on new SSH sessions.
</p>
)}
</form>
</DialogPanel>
<DialogFooter>
<Button disabled={isResponding} type="button" variant="outline" onClick={cancelPrompt}>
{isExpired ? "Dismiss" : "Cancel"}
</Button>
<Button disabled={isResponding || isExpired} form={formId} type="submit">
Continue
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
@@ -28,6 +28,7 @@ import { RadioGroup } from "../ui/radio-group";
import { toastManager } from "../ui/toast";
import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
import { AnimatedHeight } from "../AnimatedHeight";
const PROVIDER_ACCENT_SWATCHES = [
"#2563eb",
@@ -250,7 +251,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
key={step}
type="button"
className={cn(
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left transition",
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === wizardStep
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: index < wizardStep
@@ -290,168 +291,173 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
data-slot="dialog-panel"
className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
>
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
<span id="add-instance-driver-label" className="text-xs font-medium text-foreground">
Driver
</span>
<RadioGroup
value={driver}
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
aria-labelledby="add-instance-driver-label"
className="grid grid-cols-2 gap-2.5"
>
{DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
const isSelected = option.value === driver;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
)}
>
<IconComponent className="size-5 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
{option.badgeLabel ? (
<Badge variant="warning" size="sm">
{option.badgeLabel}
</Badge>
) : null}
</RadioPrimitive.Root>
);
})}
{COMING_SOON_DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
disabled
className={cn(
"relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
)}
>
<IconComponent
className="size-5 shrink-0 text-muted-foreground"
aria-hidden
/>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
<Badge variant="warning" size="sm">
Coming Soon
</Badge>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Label</span>
<Input
className="bg-background"
placeholder="e.g. Work"
value={label}
onChange={(event) => setLabel(event.target.value)}
/>
<span className="text-[11px] text-muted-foreground">
Shown in the provider list. Optional.
</span>
</label>
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Instance ID</span>
<Input
className="bg-background"
placeholder={`${driver}_work`}
value={instanceId}
onChange={(event) => {
setInstanceIdDirty(true);
setInstanceId(event.target.value);
}}
aria-invalid={showInstanceIdError}
/>
{showInstanceIdError ? (
<span className="text-[11px] text-destructive">{instanceIdError}</span>
) : (
<span className="text-[11px] text-muted-foreground">
Routing key used by threads and sessions. Letters, digits, '-', or '_'.
<AnimatedHeight>
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
<span
id="add-instance-driver-label"
className="text-xs font-medium text-foreground"
>
Driver
</span>
)}
</label>
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<input
type="color"
value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
onChange={(event) => setAccentColor(event.target.value)}
aria-label="Provider instance accent color"
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
/>
<div className="flex flex-wrap gap-1.5">
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
const selected = accentColor.toLowerCase() === swatch;
<RadioGroup
value={driver}
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
aria-labelledby="add-instance-driver-label"
className="grid grid-cols-2 gap-2.5"
>
{DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
const isSelected = option.value === driver;
return (
<button
key={swatch}
type="button"
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"size-6 cursor-pointer rounded-full border transition",
selected
? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
: "border-black/10 hover:scale-105 dark:border-white/20",
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
)}
style={{ backgroundColor: swatch }}
onClick={() => setAccentColor(swatch)}
aria-label={`Use ${swatch} accent`}
/>
>
<IconComponent className="size-5 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
{option.badgeLabel ? (
<Badge variant="warning" size="sm">
{option.badgeLabel}
</Badge>
) : null}
</RadioPrimitive.Root>
);
})}
</div>
{accentColor ? (
<Button
type="button"
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground"
onClick={() => setAccentColor("")}
>
Clear
</Button>
) : null}
{COMING_SOON_DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
disabled
className={cn(
"relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
)}
>
<IconComponent
className="size-5 shrink-0 text-muted-foreground"
aria-hidden
/>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
<Badge variant="warning" size="sm">
Coming Soon
</Badge>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<span className="text-[11px] text-muted-foreground">
Optional marker shown in the picker.
</span>
</div>
{driverSettingsFields.length > 0 ? (
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
<ProviderSettingsForm
definition={driverOption}
value={configDraft}
idPrefix={`add-provider-${driver}`}
variant="dialog"
onChange={setConfigDraft}
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Label</span>
<Input
className="bg-background"
placeholder="e.g. Work"
value={label}
onChange={(event) => setLabel(event.target.value)}
/>
<span className="text-[11px] text-muted-foreground">
Shown in the provider list. Optional.
</span>
</label>
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Instance ID</span>
<Input
className="bg-background"
placeholder={`${driver}_work`}
value={instanceId}
onChange={(event) => {
setInstanceIdDirty(true);
setInstanceId(event.target.value);
}}
aria-invalid={showInstanceIdError}
/>
{showInstanceIdError ? (
<span className="text-[11px] text-destructive">{instanceIdError}</span>
) : (
<span className="text-[11px] text-muted-foreground">
Routing key used by threads and sessions. Letters, digits, '-', or '_'.
</span>
)}
</label>
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<input
type="color"
value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
onChange={(event) => setAccentColor(event.target.value)}
aria-label="Provider instance accent color"
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
/>
<div className="flex flex-wrap gap-1.5">
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
const selected = accentColor.toLowerCase() === swatch;
return (
<button
key={swatch}
type="button"
className={cn(
"size-6 cursor-pointer rounded-full border transition",
selected
? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
: "border-black/10 hover:scale-105 dark:border-white/20",
)}
style={{ backgroundColor: swatch }}
onClick={() => setAccentColor(swatch)}
aria-label={`Use ${swatch} accent`}
/>
);
})}
</div>
{accentColor ? (
<Button
type="button"
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground"
onClick={() => setAccentColor("")}
>
Clear
</Button>
) : null}
</div>
<span className="text-[11px] text-muted-foreground">
Optional marker shown in the picker.
</span>
</div>
) : wizardStep === 2 ? (
<div className="grid gap-2">
<p className="text-sm text-muted-foreground">
This driver has no required configuration. You can add the instance now.
</p>
</div>
) : null}
{driverSettingsFields.length > 0 ? (
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
<ProviderSettingsForm
definition={driverOption}
value={configDraft}
idPrefix={`add-provider-${driver}`}
variant="dialog"
onChange={setConfigDraft}
/>
</div>
) : wizardStep === 2 ? (
<div className="grid gap-2">
<p className="text-sm text-muted-foreground">
This driver has no required configuration. You can add the instance now.
</p>
</div>
) : null}
</AnimatedHeight>
</div>
<DialogFooter className="border-t bg-background">
File diff suppressed because it is too large. Load diff
@@ -21,6 +21,7 @@ import { render } from "vitest-browser-react";
import { __resetLocalApiForTests } from "../../localApi";
import { AppAtomRegistryProvider, resetAppAtomRegistryForTests } from "../../rpc/atomRegistry";
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
import { useUiStateStore } from "../../uiStateStore";
import { ConnectionsSettings } from "./ConnectionsSettings";
import { GeneralSettingsPanel } from "./SettingsPanels";
import { SourceControlSettingsPanel } from "./SourceControlSettings";
@@ -115,6 +116,8 @@ const authAccessHarness = vi.hoisted(() => {
};
});
const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn());
vi.mock("../../environments/runtime", () => {
const primaryConnection = {
kind: "primary" as const,
@@ -152,6 +155,7 @@ vi.mock("../../environments/runtime", () => {
new URL(path, "http://localhost:3000").toString(),
waitForSavedEnvironmentRegistryHydration: async () => undefined,
addSavedEnvironment: vi.fn(),
connectDesktopSshEnvironment: mockConnectDesktopSshEnvironment,
disconnectSavedEnvironment: vi.fn(),
ensureEnvironmentConnectionBootstrapped: async () => undefined,
getPrimaryEnvironmentConnection: () => primaryConnection,
@@ -259,7 +263,9 @@ function makeClientSession(input: {
}
const createDesktopBridgeStub = (overrides?: {
readonly discoverSshHosts?: DesktopBridge["discoverSshHosts"];
readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
readonly advertisedEndpoints?: Awaited<ReturnType<DesktopBridge["getAdvertisedEndpoints"]>>;
readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"];
}): DesktopBridge => {
@@ -295,11 +301,58 @@ const createDesktopBridgeStub = (overrides?: {
getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
discoverSshHosts: overrides?.discoverSshHosts ?? vi.fn().mockResolvedValue([]),
ensureSshEnvironment: vi.fn().mockImplementation(async (target) => ({
target,
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
pairingToken: "ssh-pairing-token",
})),
disconnectSshEnvironment: vi.fn().mockResolvedValue(undefined),
fetchSshEnvironmentDescriptor: vi.fn().mockResolvedValue({
environmentId: "environment-ssh",
label: "SSH environment",
platform: {
os: "linux",
arch: "x64",
},
serverVersion: "0.0.0-test",
capabilities: {
repositoryIdentity: true,
},
}),
bootstrapSshBearerSession: vi.fn().mockResolvedValue({
authenticated: true,
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
sessionToken: "ssh-bearer-token",
}),
fetchSshSessionState: vi.fn().mockResolvedValue({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: "t3_session",
},
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
}),
issueSshWebSocketToken: vi.fn().mockResolvedValue({
token: "ssh-ws-token",
expiresAt: "2026-05-01T12:05:00.000Z",
}),
onSshPasswordPrompt: vi.fn(() => () => {}),
resolveSshPasswordPrompt: vi.fn().mockResolvedValue(undefined),
getServerExposureState: vi.fn().mockResolvedValue(
overrides?.serverExposureState ?? {
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
),
setServerExposureMode:
@@ -308,7 +361,17 @@ const createDesktopBridgeStub = (overrides?: {
mode,
endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null,
advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
})),
setTailscaleServeEnabled: vi.fn().mockImplementation(async (input) => ({
mode: overrides?.serverExposureState?.mode ?? "network-accessible",
endpointUrl: overrides?.serverExposureState?.endpointUrl ?? "http://192.168.1.44:3773",
advertisedHost: overrides?.serverExposureState?.advertisedHost ?? "192.168.1.44",
tailscaleServeEnabled: input.enabled,
tailscaleServePort: input.port ?? 443,
})),
getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []),
pickFolder: vi.fn().mockResolvedValue(null),
confirm: vi.fn().mockResolvedValue(false),
setTheme: vi.fn().mockResolvedValue(undefined),
@@ -345,7 +408,9 @@ describe("GeneralSettingsPanel observability", () => {
resetServerStateForTests();
await __resetLocalApiForTests();
localStorage.clear();
useUiStateStore.setState({ defaultAdvertisedEndpointKey: null });
authAccessHarness.reset();
mockConnectDesktopSshEnvironment.mockReset();
});
afterEach(async () => {
@@ -431,6 +496,176 @@ describe("GeneralSettingsPanel observability", () => {
.toBeInTheDocument();
});
it("hides advertised endpoint rows when desktop network access is disabled", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
advertisedEndpoints: [
{
id: "loopback",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
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",
isDefault: true,
},
{
id: "tailscale-ip",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.105.39.17:3773/",
wsBaseUrl: "ws://100.105.39.17:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
},
],
});
authAccessHarness.setSnapshot({
pairingLinks: [],
clientSessions: [],
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("Limited to this machine.")).toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "This machine", exact: true }))
.not.toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "Tailscale IP", exact: true }))
.not.toBeInTheDocument();
});
it("collapses advertised endpoints behind the network access summary", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
mode: "network-accessible",
endpointUrl: "http://192.168.86.39:3773",
advertisedHost: "192.168.86.39",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
advertisedEndpoints: [
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
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",
},
{
id: "desktop-lan:http://192.168.86.39:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://192.168.86.39:3773/",
wsBaseUrl: "ws://192.168.86.39:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
},
{
id: "tailscale-ip:http://100.105.39.17:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.105.39.17:3773/",
wsBaseUrl: "ws://100.105.39.17:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
},
],
});
authAccessHarness.setSnapshot({
pairingLinks: [],
clientSessions: [],
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("http://192.168.86.39:3773/")).toBeInTheDocument();
await expect.element(page.getByRole("button", { name: "+2" })).toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "Local network", exact: true }))
.not.toBeInTheDocument();
await page.getByRole("button", { name: "+2" }).click();
await expect
.element(page.getByRole("heading", { name: "Local network", exact: true }))
.toBeInTheDocument();
await expect.element(page.getByText("Default", { exact: true })).toBeInTheDocument();
await page.getByRole("button", { name: "Set as default" }).first().click();
await expect.element(page.getByText("http://127.0.0.1:3773/").first()).toBeInTheDocument();
});
it("shows diagnostics inside About with a single logs-folder action", async () => {
setServerConfigSnapshot(createBaseServerConfig());
@@ -461,6 +696,8 @@ describe("GeneralSettingsPanel observability", () => {
mode: "network-accessible",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
});
let pairingLinks: Array<AuthAccessSnapshot["pairingLinks"][number]> = [];
@@ -566,7 +803,7 @@ describe("GeneralSettingsPanel observability", () => {
.element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))
.toBeInTheDocument();
await expect
.element(page.getByRole("button", { name: /^(Copy|Show link)$/ }))
.element(page.getByRole("button", { name: /^Copy pairing URL for:/ }))
.toBeInTheDocument();
await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
});
@@ -577,6 +814,8 @@ describe("GeneralSettingsPanel observability", () => {
mode: "network-accessible",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
});
let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
@@ -677,9 +916,77 @@ describe("GeneralSettingsPanel observability", () => {
await vi.waitFor(() => {
expect(desktopBridge.setServerExposureMode).toHaveBeenCalledWith("network-accessible");
});
await expect.element(page.getByText("http://192.168.1.44:3773")).toBeInTheDocument();
});
it("adds desktop ssh environments from the add-environment dialog", async () => {
const discoverSshHosts = vi.fn().mockResolvedValue([
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
source: "ssh-config" as const,
},
]);
window.desktopBridge = createDesktopBridgeStub({
discoverSshHosts,
});
mockConnectDesktopSshEnvironment.mockResolvedValue({
environmentId: EnvironmentId.make("environment-devbox"),
label: "Build box",
wsBaseUrl: "ws://127.0.0.1:3774/",
httpBaseUrl: "http://127.0.0.1:3774/",
createdAt: "2036-04-07T00:00:00.000Z",
lastConnectedAt: "2036-04-07T00:00:00.000Z",
desktopSsh: {
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await page.getByRole("button", { name: "Add environment", exact: true }).click();
const addEnvironmentDialog = page.getByRole("dialog", { name: "Add Environment" });
await expect
.element(page.getByText("Reachable at http://192.168.1.44:3773"))
.element(addEnvironmentDialog.getByRole("heading", { name: "Add Environment", exact: true }))
.toBeInTheDocument();
await addEnvironmentDialog.getByRole("button", { name: /^SSH\b/ }).click();
await vi.waitFor(() => {
expect(discoverSshHosts).toHaveBeenCalledTimes(1);
});
await expect
.element(page.getByRole("heading", { name: "devbox", exact: true }))
.toBeInTheDocument();
await addEnvironmentDialog.getByLabelText("SSH host or alias").fill("devbox.example.com");
await addEnvironmentDialog.getByLabelText("Username").fill("julius");
await addEnvironmentDialog.getByLabelText("Port").fill("2222");
await addEnvironmentDialog
.getByRole("button", { name: "Add environment", exact: true })
.first()
.click();
await vi.waitFor(() => {
expect(mockConnectDesktopSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ label: "" },
);
});
});
it("opens the logs folder in the preferred editor", async () => {
@@ -774,9 +1081,9 @@ describe("SourceControlSettingsPanel discovery states", () => {
await expect.element(page.getByText("Version Control")).toBeInTheDocument();
await expect.element(page.getByText("Source Control Providers")).toBeInTheDocument();
await expect
.element(page.getByRole("button", { name: "Scan source control tools" }))
.element(page.getByRole("button", { name: "Rescan server environment" }))
.toBeDisabled();
await expect.element(page.getByText("No source control tools found")).not.toBeInTheDocument();
await expect.element(page.getByText("Nothing detected yet")).not.toBeInTheDocument();
});
it("uses the shared empty state when discovery completes without tools", async () => {
@@ -791,9 +1098,13 @@ describe("SourceControlSettingsPanel discovery states", () => {
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("No source control tools found")).toBeInTheDocument();
await expect.element(page.getByText("Nothing detected yet")).toBeInTheDocument();
await expect
.element(page.getByText("Install a supported Git or pull request CLI, then scan again."))
.element(
page.getByText(
"Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan.",
),
)
.toBeInTheDocument();
await expect.element(page.getByRole("button", { name: "Scan" })).toBeInTheDocument();
});
@@ -822,7 +1133,7 @@ describe("SourceControlSettingsPanel discovery states", () => {
);
await expect.element(page.getByRole("heading", { name: "Git" })).toBeInTheDocument();
await expect.element(page.getByText("No source control tools found")).not.toBeInTheDocument();
await expect.element(page.getByText("Nothing detected yet")).not.toBeInTheDocument();
});
it("does not rescan on remount while the discovery atom is fresh", async () => {
@@ -69,17 +69,21 @@ function isProviderDiscoveryItem(
return "auth" in item;
}
function isVcsNotReady(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): boolean {
return !isProviderDiscoveryItem(item) && !item.implemented;
}
function authPresentation(auth: SourceControlProviderAuth): {
readonly label: string;
readonly badge: "warning" | null;
} {
if (auth.status === "authenticated") {
return { label: "Signed in", badge: null };
return { label: "Authenticated", badge: null };
}
if (auth.status === "unauthenticated") {
return { label: "Sign in", badge: "warning" };
return { label: "Not authenticated", badge: "warning" };
}
return { label: "Sign in", badge: null };
return { label: "Status unknown", badge: null };
}
function RedactedAccount(props: { readonly account: string | null }) {
@@ -94,7 +98,7 @@ function RedactedAccount(props: { readonly account: string | null }) {
}
function itemStatusDot(item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem): string {
if (!item.implemented) return "bg-muted-foreground/35";
if (isVcsNotReady(item)) return "bg-muted-foreground/35";
if (item.status !== "available") return "bg-warning";
if (isProviderDiscoveryItem(item) && item.auth.status !== "authenticated") return "bg-warning";
return "bg-success";
@@ -137,12 +141,12 @@ function itemSummary({
readonly auth: SourceControlProviderAuth | null;
readonly authAccount: string | null;
}) {
if (!item.implemented) {
if (isVcsNotReady(item)) {
return <span>Support for {item.label} is coming soon.</span>;
}
if (item.status !== "available") {
return <span>Not found - {item.installHint}</span>;
return <span>Not available on this server — {item.installHint}</span>;
}
if (auth) {
@@ -165,11 +169,17 @@ function itemSummary({
}
if (auth.status === "unauthenticated") {
return <span>Sign in with the {item.executable} CLI to enable pull request actions.</span>;
return (
<span>
{item.label} is not authenticated on this server. Sign in or configure credentials using
the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
tool on the server host to enable pull request features.
</span>
);
}
return (
<span>
Install and sign in with the {item.executable} CLI to enable pull request actions.
Could not verify {item.label}. {item.installHint}
</span>
);
}
@@ -183,7 +193,8 @@ function DiscoveryItemRow({
readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
}) {
const version = optionLabel(item.version);
const enabled = item.implemented && item.status === "available";
const enabled =
item.status === "available" && (isProviderDiscoveryItem(item) || item.implemented);
const auth = isProviderDiscoveryItem(item) ? item.auth : null;
const authStatus = auth ? authPresentation(auth) : null;
const authAccount = auth ? optionLabel(auth.account) : null;
@@ -192,7 +203,7 @@ function DiscoveryItemRow({
<div
className={cn(
"border-t border-border/60 first:border-t-0",
!item.implemented && "opacity-80",
isVcsNotReady(item) && "opacity-80",
)}
>
<div className="px-4 py-3.5 sm:px-5">
@@ -204,7 +215,7 @@ function DiscoveryItemRow({
{item.label}
</h3>
{version ? <code className="text-xs text-muted-foreground">{version}</code> : null}
{!item.implemented ? (
{isVcsNotReady(item) ? (
<Badge variant="warning" size="sm">
Coming Soon
</Badge>
@@ -220,7 +231,7 @@ function DiscoveryItemRow({
</p>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{item.implemented ? (
{!isVcsNotReady(item) ? (
<Switch checked={enabled} disabled aria-label={`${item.label} availability`} />
) : null}
</div>
@@ -279,17 +290,19 @@ function EmptySourceControlDiscovery({
const hasError = error !== null;
return (
<SettingsSection title="Detected tools">
<SettingsSection title="Server environment">
<Empty className="min-h-88">
<EmptyMedia variant="icon">
<GitPullRequestIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>
{hasError ? "Could not scan source control" : "No source control tools found"}
{hasError ? "Could not scan the server environment" : "Nothing detected yet"}
</EmptyTitle>
<EmptyDescription>
{hasError ? error : "Install a supported Git or pull request CLI, then scan again."}
{hasError
? error
: "Install Git on the server, add optional hosting integrations or credentials your workspace needs, then rescan."}
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
@@ -329,13 +342,13 @@ export function SourceControlSettingsPanel() {
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
onClick={handleScan}
disabled={discovery.isPending}
aria-label="Scan source control tools"
aria-label="Rescan server environment"
>
<RefreshCwIcon className={cn("size-3", discovery.isPending && "animate-spin")} />
</Button>
}
/>
<TooltipPopup side="top">Scan source control tools</TooltipPopup>
<TooltipPopup side="top">Rescan Git and hosting integrations</TooltipPopup>
</Tooltip>
);
@@ -0,0 +1,24 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
describe("settings pairing URL helpers", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("uses direct backend pairing URLs for HTTP endpoints", () => {
expect(resolveHostedPairingUrl("http://192.168.1.44:3773", "PAIRCODE")).toBeNull();
expect(resolveDesktopPairingUrl("http://192.168.1.44:3773", "PAIRCODE")).toBe(
"http://192.168.1.44:3773/pair#token=PAIRCODE",
);
});
it("uses hosted pairing URLs for HTTPS endpoints", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes");
expect(resolveHostedPairingUrl("https://host.tailnet.example.ts.net:3773", "PAIRCODE")).toBe(
"https://preview.t3.codes/pair?host=https%3A%2F%2Fhost.tailnet.example.ts.net%3A3773#token=PAIRCODE",
);
});
});
@@ -0,0 +1,20 @@
import { buildHostedPairingUrl } from "../../hostedPairing";
import { setPairingTokenOnUrl } from "../../pairingUrl";
export function resolveDesktopPairingUrl(endpointUrl: string, credential: string): string {
const url = new URL(endpointUrl);
url.pathname = "/pair";
return setPairingTokenOnUrl(url, credential).toString();
}
export function resolveHostedPairingUrl(endpointUrl: string, credential: string): string | null {
const url = new URL(endpointUrl);
if (url.protocol !== "https:") {
return null;
}
return buildHostedPairingUrl({
host: endpointUrl,
token: credential,
});
}
@@ -52,7 +52,7 @@ export function SettingsRow({
children,
}: {
title: ReactNode;
description: string;
description: ReactNode;
status?: ReactNode;
resetAction?: ReactNode;
control?: ReactNode;
+2 -2
View File
@@ -18,7 +18,7 @@ function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backd
return (
<AlertDialogPrimitive.Backdrop
className={cn(
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 ease-out data-ending-style:opacity-0 data-starting-style:opacity-0",
"fixed inset-0 z-50 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
className,
)}
data-slot="alert-dialog-backdrop"
@@ -31,7 +31,7 @@ function AlertDialogViewport({ className, ...props }: AlertDialogPrimitive.Viewp
return (
<AlertDialogPrimitive.Viewport
className={cn(
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center bg-white/48 p-4 backdrop-blur-[2px] dark:bg-black/28",
className,
)}
data-slot="alert-dialog-viewport"
+2 -2
View File
@@ -24,7 +24,7 @@ function DialogBackdrop({ className, ...props }: DialogPrimitive.Backdrop.Props)
return (
<DialogPrimitive.Backdrop
className={cn(
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
"fixed inset-0 z-50 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
className,
)}
data-slot="dialog-backdrop"
@@ -37,7 +37,7 @@ function DialogViewport({ className, ...props }: DialogPrimitive.Viewport.Props)
return (
<DialogPrimitive.Viewport
className={cn(
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center bg-white/48 p-4 backdrop-blur-[2px] dark:bg-black/28",
className,
)}
data-slot="dialog-viewport"
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more