Compare commits

...
Author SHA1 Message Date
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
d7969264de Add remote repository publish and discovery support (#2482)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-03 18:05:46 -07:00
Illia Panasenko f7748a0d65 feat: add "hide whitespace changes" option for diffs (#2389) 2026-05-03 11:47:37 -07:00
Julius MarmingeandJulius Marminge 0ce7e56e43 feat(scm): Gitlab (#2462)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 18:59:47 -07:00
Julius MarmingeandJulius Marminge 350d76ee14 [codex] Align GitHub source control adapter errors (#2476)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 16:59:03 -07:00
201 changed files with 22526 additions and 2981 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:",
@@ -52,6 +52,7 @@ const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
@@ -71,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;
}
@@ -506,6 +506,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
ignoreWhitespace: false,
});
assert.equal(incrementalDiff.includes("README.md"), true);
@@ -514,6 +515,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
ignoreWhitespace: false,
});
assert.equal(fullDiff.includes("README.md"), true);
+1
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:",
@@ -48,6 +48,7 @@ describe("CheckpointDiffQueryLive", () => {
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
@@ -68,9 +69,14 @@ describe("CheckpointDiffQueryLive", () => {
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
@@ -102,6 +108,7 @@ describe("CheckpointDiffQueryLive", () => {
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
@@ -113,6 +120,7 @@ describe("CheckpointDiffQueryLive", () => {
cwd: "/tmp/workspace",
fromCheckpointRef: expectedFromRef,
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
@@ -123,6 +131,67 @@ describe("CheckpointDiffQueryLive", () => {
});
});
it("defaults to hide whitespace changes", async () => {
const projectId = ProjectId.make("project-default-whitespace");
const threadId = ThreadId.make("thread-default-whitespace");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ ignoreWhitespace });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer)),
);
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.make("thread-missing");
@@ -24,6 +24,7 @@ const make = Effect.gen(function* () {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
@@ -131,6 +132,7 @@ const make = Effect.gen(function* () {
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
@@ -157,6 +159,7 @@ const make = Effect.gen(function* () {
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace ?? true,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
@@ -114,6 +114,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: true,
});
expect(diff).toContain("diff --git");
@@ -121,5 +122,80 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
expect(diff).toContain("+line 04999");
}),
);
it.effect("can hide indentation churn when changes wrap existing lines", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const componentPath = path.join(tmp, "Component.tsx");
yield* writeTextFile(
componentPath,
[
"export function View() {",
" return (",
" <section>",
" <h1>Title</h1>",
" <p>Body</p>",
" </section>",
" );",
"}",
"",
].join("\n"),
);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: fromCheckpointRef,
});
yield* writeTextFile(
componentPath,
[
"export function View() {",
" return (",
" <section>",
" {isReady ? (",
" <div>",
" <h1>Title</h1>",
" <p>Body</p>",
" </div>",
" ) : null}",
" </section>",
" );",
"}",
"",
].join("\n"),
);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: toCheckpointRef,
});
const normalDiff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: false,
});
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: true,
});
expect(normalDiff).toContain("diff --git");
expect(normalDiff).toContain("- <h1>Title</h1>");
expect(normalDiff).toContain("+ <h1>Title</h1>");
expect(whitespaceIgnoredDiff).toContain("diff --git");
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
expect(whitespaceIgnoredDiff).toContain("+ <div>");
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
}),
);
});
});
@@ -259,10 +259,20 @@ const makeCheckpointStore = Effect.gen(function* () {
});
}
const diffArgs = [
"diff",
"--patch",
"--minimal",
"--no-color",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
fromCommitOid,
toCommitOid,
];
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
args: diffArgs,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
@@ -32,6 +32,7 @@ export interface DiffCheckpointsInput {
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
readonly ignoreWhitespace: boolean;
}
export interface DeleteCheckpointRefsInput {
+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,
+154 -1
View File
@@ -14,9 +14,10 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "./GitManager.ts";
import {
GitHubCliError,
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
@@ -579,6 +580,13 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCliError({
operation: "createRepository",
detail: `Unexpected repository create: ${input.repository}`,
}),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
@@ -647,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)),
@@ -880,6 +889,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}),
@@ -909,6 +919,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}),
@@ -1671,6 +1682,41 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("pushes existing commits without committing dirty worktree changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "push-dirty.txt"), "push dirty\n");
yield* runGit(repoDir, ["add", "push-dirty.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]);
fs.mkdirSync(path.join(repoDir, ".vercel"));
fs.writeFileSync(path.join(repoDir, ".vercel", "project.json"), "{}\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "push",
});
expect(result.commit.status).toBe("skipped_not_requested");
expect(result.push.status).toBe("pushed");
expect(result.pr.status).toBe("skipped_not_requested");
expect(
yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toContain("?? .vercel/");
expect(
yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toBe("Push dirty branch");
}),
);
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2417,6 +2463,113 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"restores same-repository upstream tracking after local PR checkout without a remote ref",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-upstream"]);
fs.writeFileSync(path.join(repoDir, "upstream.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "upstream.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-upstream"]);
yield* runGit(repoDir, [
"update-ref",
"-d",
"refs/remotes/origin/feature/pr-local-upstream",
]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 65,
title: "Local upstream PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/65",
baseRefName: "main",
headRefName: "feature/pr-local-upstream",
state: "open",
isCrossRepository: false,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
repositoryCloneUrls: {
"pingdotgg/codething-mvp": {
url: remoteDir,
sshUrl: remoteDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "65",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-upstream");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("origin/feature/pr-local-upstream");
}),
);
it.effect(
"restores same-repository upstream tracking when provider omits head repository metadata",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-no-head-repo"]);
fs.writeFileSync(path.join(repoDir, "no-head-repo.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "no-head-repo.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-no-head-repo"]);
yield* runGit(repoDir, [
"update-ref",
"-d",
"refs/remotes/origin/feature/pr-local-no-head-repo",
]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 66,
title: "Local upstream PR without repo metadata",
url: "https://github.com/pingdotgg/codething-mvp/pull/66",
baseRefName: "main",
headRefName: "feature/pr-local-no-head-repo",
state: "open",
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "66",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-no-head-repo");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("origin/feature/pr-local-no-head-repo");
}),
);
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+23 -6
View File
@@ -568,6 +568,22 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
localBranch = pullRequest.headBranch,
) {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
yield* gitCore.fetchRemoteTrackingBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
return;
}
if (repositoryNameWithOwner.length === 0) {
return;
}
@@ -588,6 +604,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
url: remoteUrl,
});
yield* gitCore.fetchRemoteTrackingBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
@@ -690,6 +711,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
} satisfies GitStatusDetails;
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
const details = yield* gitCore
@@ -748,6 +770,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
aheadOfDefaultCount: details.aheadOfDefaultCount,
pr,
} satisfies VcsStatusRemoteResult;
});
@@ -1593,12 +1616,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
"Feature-branch checkout is only supported for commit actions.",
);
}
if (input.action === "push" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
"Commit or stash local changes before pushing.",
);
}
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
+19 -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, {
@@ -65,6 +64,7 @@ describe("GitWorkflowService", () => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}).pipe(
@@ -81,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,
@@ -98,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" });
@@ -111,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, {
@@ -112,6 +112,7 @@ function nonRepositoryStatus(): VcsStatusResult {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
};
}
+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(
@@ -237,6 +237,7 @@ const make = Effect.gen(function* () {
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace: false,
})
.pipe(
Effect.map((diff) =>
+57 -29
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,19 +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 * 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";
@@ -213,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* () {
@@ -326,11 +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>;
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
sourceControlRepositoryService?: Partial<SourceControlRepositoryService.SourceControlRepositoryServiceShape>;
vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcasterShape>;
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
terminalManager?: Partial<TerminalManagerShape>;
orchestrationEngine?: Partial<OrchestrationEngineShape>;
@@ -373,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,
@@ -418,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(
@@ -448,7 +443,7 @@ const buildAppUnderTest = (options?: {
kind: repository.kind,
repository,
driver: defaultVcsDriver,
} satisfies VcsDriverHandle)
} satisfies VcsDriverRegistry.VcsDriverHandle)
: null,
),
),
@@ -490,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,
@@ -545,6 +540,11 @@ const buildAppUnderTest = (options?: {
Layer.provide(gitVcsDriverLayer),
Layer.provide(gitWorkflowLayer),
Layer.provide(vcsProvisioningLayer),
Layer.provide(
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
...options?.layers?.sourceControlRepositoryService,
}),
),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provide(
Layer.mock(ProjectSetupScriptRunner)({
@@ -643,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),
@@ -2011,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)),
);
@@ -3100,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 = {
+73 -6
View File
@@ -25,7 +25,10 @@ import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReap
import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
@@ -53,6 +56,7 @@ import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
@@ -81,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* () {
@@ -160,15 +165,18 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProjectConfig.layer),
);
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
Layer.provide(
Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
const GitManagerLayerLive = GitManager.layer.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(
SourceControlProviderRegistry.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
),
),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
Layer.provideMerge(TextGeneration.layer),
);
@@ -182,11 +190,17 @@ const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
Layer.provideMerge(GitLayerLive),
);
const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
);
const VcsLayerLive = Layer.empty.pipe(
Layer.provideMerge(VcsProjectConfig.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
Layer.provideMerge(GitWorkflowLayerLive),
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
);
@@ -226,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),
@@ -326,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, {
@@ -333,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,
}),
),
@@ -211,6 +210,58 @@ describe("GitHubCli.layer", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("creates repositories and parses clone URLs from create output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
"✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
),
),
);
const gh = yield* GitHubCli.GitHubCli;
const result = yield* gh.createRepository({
cwd: "/repo",
repository: "octocat/codething-mvp",
visibility: "private",
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
expect(mockRun).toHaveBeenCalledTimes(1);
expect(mockRun).toHaveBeenNthCalledWith(1, {
operation: "GitHubCli.execute",
command: "gh",
args: ["repo", "create", "octocat/codething-mvp", "--private"],
cwd: "/repo",
timeoutMs: 30_000,
});
}).pipe(Effect.provide(layer)),
);
it.effect("falls back to constructed URLs when create output omits a URL", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
const gh = yield* GitHubCli.GitHubCli;
const result = yield* gh.createRepository({
cwd: "/repo",
repository: "octocat/codething-mvp",
visibility: "private",
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
}).pipe(Effect.provide(layer)),
);
it.effect("surfaces a friendly error when the pull request is not found", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
+75 -13
View File
@@ -1,16 +1,26 @@
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { GitHubCliError, TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../git/githubPullRequests.ts";
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
} from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
@@ -34,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;
@@ -52,6 +62,12 @@ export interface GitHubCliShape {
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
@@ -150,6 +166,43 @@ function normalizeRepositoryCloneUrls(
};
}
/**
* `gh repo create` prints the canonical URL of the new repository on stdout
* (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
* follow-up `gh repo view`, which can race GitHub's GraphQL eventual
* consistency window and falsely report the just-created repo as missing.
*/
function deriveRepositoryCloneUrlsFromCreateOutput(
stdout: string,
repository: string,
): GitHubRepositoryCloneUrls {
const fallbackHost = "github.com";
const match = stdout.match(/https?:\/\/[^\s]+/);
if (match) {
const cleaned = match[0].replace(/\.git$/, "");
try {
const parsed = new URL(cleaned);
const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
const segments = pathname.split("/").filter(Boolean);
if (segments.length === 2) {
const nameWithOwner = `${segments[0]}/${segments[1]}`;
return {
nameWithOwner,
url: `${parsed.origin}/${nameWithOwner}`,
sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
};
}
} catch {
// Fall through to the input-derived defaults below.
}
}
return {
nameWithOwner: repository,
url: `https://${fallbackHost}/${repository}`,
sshUrl: `git@${fallbackHost}:${repository}.git`,
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
@@ -169,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
@@ -204,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,
}),
);
@@ -236,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,
}),
);
@@ -271,6 +324,15 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
),
Effect.map(normalizeRepositoryCloneUrls),
),
createRepository: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "create", input.repository, `--${input.visibility}`],
}).pipe(
Effect.map((result) =>
deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
),
),
createPullRequest: (input) =>
execute({
cwd: input.cwd,
@@ -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;
@@ -3,14 +3,17 @@ import {
SourceControlProviderError,
type ChangeRequest,
type ChangeRequestState,
type GitHubCliError,
} from "@t3tools/contracts";
import { GitHubCli, type GitHubPullRequestSummary } from "./GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "../git/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,
@@ -19,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,
@@ -41,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) =>
@@ -131,6 +178,10 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
github
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
github
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
github
.getDefaultBranch(input)
@@ -142,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());
@@ -0,0 +1,326 @@
import { assert, it, afterEach, expect, vi } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitLabCli from "./GitLabCli.ts";
const mockedRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
const layer = it.layer(
GitLabCli.layer.pipe(
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: mockedRun,
}),
),
),
);
function processOutput(stdout: string): VcsProcess.VcsProcessOutput {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
afterEach(() => {
mockedRun.mockReset();
});
layer("GitLabCli.layer", (it) => {
it.effect("parses merge request view output", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
iid: 42,
title: "Add MR thread creation",
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
target_branch: "main",
source_branch: "feature/mr-threads",
state: "opened",
source_project_id: 101,
target_project_id: 100,
source_project: {
path_with_namespace: "octocat/t3code",
},
}),
),
),
);
const result = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getMergeRequest({
cwd: "/repo",
reference: "42",
});
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add MR thread creation",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
baseRefName: "main",
headRefName: "feature/mr-threads",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/t3code",
headRepositoryOwnerLogin: "octocat",
});
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: ["mr", "view", "42", "--output", "json"],
}),
);
}),
);
it.effect("skips invalid entries when parsing MR lists", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify([
{
iid: 0,
title: "invalid",
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
target_branch: "main",
source_branch: "feature/invalid",
},
{
iid: 43,
title: " Valid MR ",
web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
target_branch: " main ",
source_branch: " feature/mr-list ",
state: "merged",
},
]),
),
),
);
const result = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.listMergeRequests({
cwd: "/repo",
headSelector: "feature/mr-list",
state: "all",
});
});
assert.deepStrictEqual(result, [
{
number: 43,
title: "Valid MR",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
baseRefName: "main",
headRefName: "feature/mr-list",
state: "merged",
},
]);
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: [
"mr",
"list",
"--source-branch",
"feature/mr-list",
"--all",
"--per-page",
"20",
"--output",
"json",
],
}),
);
}),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
path_with_namespace: "octocat/t3code",
web_url: "https://gitlab.com/octocat/t3code",
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
}),
),
),
);
const result = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/t3code",
});
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/t3code",
url: "https://gitlab.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
});
}),
);
it.effect("creates merge requests through the GitLab API without placing the body in argv", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
const glab = yield* GitLabCli.GitLabCli;
yield* glab.createMergeRequest({
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
title: "Provider MR",
bodyFile: "/tmp/t3-mr-body.md",
});
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: [
"api",
"--method",
"POST",
"projects/:fullpath/merge_requests",
"--raw-field",
"source_branch=feature/provider",
"--raw-field",
"target_branch=main",
"--raw-field",
"title=Provider MR",
"--field",
"description=@/tmp/t3-mr-body.md",
],
}),
);
}),
);
it.effect("creates repositories under an explicit namespace", () =>
Effect.gen(function* () {
mockedRun
.mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
path_with_namespace: "octocat/t3code",
web_url: "https://gitlab.com/octocat/t3code",
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
}),
),
),
);
const glab = yield* GitLabCli.GitLabCli;
const result = yield* glab.createRepository({
cwd: "/repo",
repository: "octocat/t3code",
visibility: "public",
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/t3code",
url: "https://gitlab.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
});
expect(mockedRun).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: ["api", "namespaces/octocat"],
}),
);
expect(mockedRun).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: [
"api",
"--method",
"POST",
"projects",
"--raw-field",
"path=t3code",
"--raw-field",
"name=t3code",
"--raw-field",
"visibility=public",
"--raw-field",
"namespace_id=1234",
],
}),
);
}),
);
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
const glab = yield* GitLabCli.GitLabCli;
yield* glab.checkoutMergeRequest({
cwd: "/repo",
reference: "42",
force: true,
});
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: ["mr", "checkout", "42"],
}),
);
}),
);
it.effect("surfaces a friendly error when the merge request is not found", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.fail(
new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab mr view 4888",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 merge request not found",
}),
),
);
const error = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getMergeRequest({
cwd: "/repo",
reference: "4888",
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Merge request not found"), true);
}),
);
});
+442
View File
@@ -0,0 +1,442 @@
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitLabMergeRequests from "./gitLabMergeRequests.ts";
import type * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export interface GitLabMergeRequestSummary {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly updatedAt?: Option.Option<DateTime.Utc>;
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitLabRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
export interface GitLabCliShape {
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
readonly listMergeRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly state: "open" | "closed" | "merged" | "all";
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
readonly getMergeRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
readonly createMergeRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly target?: SourceControlProvider.SourceControlRefSelector;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitLabCliError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitLabCliError>;
readonly checkoutMergeRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitLabCliError>;
}
export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
"t3/source-control/GitLabCli",
) {}
function isVcsProcessSpawnError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "VcsProcessSpawnError"
);
}
function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
if (error instanceof Error) {
if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
return new GitLabCliError({
operation,
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
cause: error,
});
}
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("glab auth login") ||
lower.includes("token")
) {
return new GitLabCliError({
operation,
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
cause: error,
});
}
if (
lower.includes("merge request not found") ||
lower.includes("not found") ||
lower.includes("404")
) {
return new GitLabCliError({
operation,
detail: "Merge request not found. Check the MR number or URL and try again.",
cause: error,
});
}
return new GitLabCliError({
operation,
detail: `GitLab CLI command failed: ${error.message}`,
cause: error,
});
}
return new GitLabCliError({
operation,
detail: "GitLab CLI command failed.",
cause: error,
});
}
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
path_with_namespace: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
http_url_to_repo: TrimmedNonEmptyString,
ssh_url_to_repo: TrimmedNonEmptyString,
});
const RawGitLabDefaultBranchSchema = Schema.Struct({
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
});
const RawGitLabNamespaceSchema = Schema.Struct({
id: Schema.Number,
});
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
): GitLabRepositoryCloneUrls {
return {
nameWithOwner: raw.path_with_namespace,
url: raw.web_url,
sshUrl: raw.ssh_url_to_repo,
};
}
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitLabCliError({
operation,
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
cause: error,
}),
),
);
}
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
switch (state) {
case "open":
return [];
case "closed":
return ["--closed"];
case "merged":
return ["--merged"];
case "all":
return ["--all"];
}
}
function normalizeHeadSelector(headSelector: string): string {
const trimmed = headSelector.trim();
const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
return ownerBranch?.[1]?.trim() || trimmed;
}
function sourceRefName(input: {
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
}): string {
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
}
function sourceProjectIdentifier(
source: SourceControlProvider.SourceControlRefSelector | undefined,
): string | null {
return source?.repository ?? source?.owner ?? null;
}
function toSummaryWithOptionalUpdatedAt(
record: GitLabMergeRequestSummary & {
readonly updatedAt: Option.Option<DateTime.Utc>;
},
): GitLabMergeRequestSummary {
const { updatedAt, ...summary } = record;
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
}
function parseRepositoryPath(repository: string): {
readonly namespacePath: string | null;
readonly projectPath: string;
} {
const parts = repository
.split("/")
.map((part) => part.trim())
.filter((part) => part.length > 0);
const projectPath = parts.at(-1) ?? repository.trim();
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
return { namespacePath, projectPath };
}
export const make = Effect.fn("makeGitLabCli")(function* () {
const process = yield* VcsProcess.VcsProcess;
const execute: GitLabCliShape["execute"] = (input) =>
process
.run({
operation: "GitLabCli.execute",
command: "glab",
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
return GitLabCli.of({
execute,
listMergeRequests: (input) =>
execute({
cwd: input.cwd,
args: [
"mr",
"list",
"--source-branch",
sourceRefName(input),
...stateArgs(input.state),
"--per-page",
String(input.limit ?? 20),
"--output",
"json",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabCliError({
operation: "listMergeRequests",
detail: `GitLab CLI returned invalid MR list JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
}),
),
),
),
getMergeRequest: (input) =>
execute({
cwd: input.cwd,
args: ["mr", "view", input.reference, "--output", "json"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => GitLabMergeRequests.decodeGitLabMergeRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabCliError({
operation: "getMergeRequest",
detail: `GitLab CLI returned invalid merge request JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
}),
),
),
),
getRepositoryCloneUrls: (input) =>
execute({
cwd: input.cwd,
args: ["api", `projects/${encodeURIComponent(input.repository)}`],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitLab CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createRepository: (input) => {
const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
? execute({
cwd: input.cwd,
args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabNamespaceSchema,
"createRepository",
"GitLab CLI returned invalid namespace JSON.",
),
),
Effect.map((namespace) => namespace.id),
)
: Effect.succeed(null);
return namespaceId.pipe(
Effect.flatMap((resolvedNamespaceId) =>
execute({
cwd: input.cwd,
args: [
"api",
"--method",
"POST",
"projects",
"--raw-field",
`path=${projectPath}`,
"--raw-field",
`name=${projectPath}`,
"--raw-field",
`visibility=${input.visibility}`,
...(resolvedNamespaceId === null
? []
: ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
],
}),
),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"createRepository",
"GitLab CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
);
},
createMergeRequest: (input) => {
const sourceProject = sourceProjectIdentifier(input.source);
return execute({
cwd: input.cwd,
args: [
"api",
"--method",
"POST",
"projects/:fullpath/merge_requests",
"--raw-field",
`source_branch=${sourceRefName(input)}`,
"--raw-field",
`target_branch=${input.target?.refName ?? input.baseBranch}`,
...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
"--raw-field",
`title=${input.title}`,
"--field",
`description=@${input.bodyFile}`,
],
}).pipe(Effect.asVoid);
},
getDefaultBranch: (input) =>
execute({
cwd: input.cwd,
args: ["api", "projects/:fullpath"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabDefaultBranchSchema,
"getDefaultBranch",
"GitLab CLI returned invalid repository JSON.",
),
),
Effect.map((value) => value.default_branch ?? null),
),
checkoutMergeRequest: (input) =>
execute({
cwd: input.cwd,
args: ["mr", "checkout", input.reference],
}).pipe(Effect.asVoid),
});
});
export const layer = Layer.effect(GitLabCli, make());
@@ -0,0 +1,107 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as GitLabCli from "./GitLabCli.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
function makeProvider(gitlab: Partial<GitLabCli.GitLabCliShape>) {
return GitLabSourceControlProvider.make().pipe(
Effect.provide(Layer.mock(GitLabCli.GitLabCli)(gitlab)),
);
}
it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
getMergeRequest: () =>
Effect.succeed({
number: 42,
title: "Add GitLab provider",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
}),
});
const changeRequest = yield* provider.getChangeRequest({
cwd: "/repo",
reference: "42",
});
assert.deepStrictEqual(changeRequest, {
provider: "gitlab",
number: 42,
title: "Add GitLab provider",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
});
}),
);
it.effect("lists GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let listInput: Parameters<GitLabCli.GitLabCliShape["listMergeRequests"]>[0] | null = null;
const provider = yield* makeProvider({
listMergeRequests: (input) => {
listInput = input;
return Effect.succeed([]);
},
});
yield* provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/provider",
state: "all",
limit: 10,
});
assert.deepStrictEqual(listInput, {
cwd: "/repo",
headSelector: "feature/provider",
state: "all",
limit: 10,
});
}),
);
it.effect("creates GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<GitLabCli.GitLabCliShape["createMergeRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createMergeRequest: (input) => {
createInput = input;
return Effect.void;
},
});
yield* provider.createChangeRequest({
cwd: "/repo",
baseRefName: "main",
headSelector: "owner:feature/provider",
title: "Provider MR",
bodyFile: "/tmp/body.md",
});
assert.deepStrictEqual(createInput, {
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
source: {
owner: "owner",
refName: "feature/provider",
},
title: "Provider MR",
bodyFile: "/tmp/body.md",
});
}),
);
@@ -0,0 +1,144 @@
import { Effect, Layer, Option } from "effect";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(
operation: string,
cause: GitLabCli.GitLabCliError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "gitlab",
operation,
detail: cause.detail,
cause,
});
}
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
return {
provider: "gitlab",
number: summary.number,
title: summary.title,
url: summary.url,
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: summary.updatedAt ?? Option.none(),
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
...(summary.headRepositoryNameWithOwner !== undefined
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
: {}),
...(summary.headRepositoryOwnerLogin !== undefined
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
: {}),
};
}
function parseGitLabAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
const output = SourceControlProviderDiscovery.combinedAuthOutput(input);
const account = SourceControlProviderDiscovery.matchFirst(output, [
/Logged in to .* as\s+([^\s(]+)/iu,
/Logged in to .* account\s+([^\s(]+)/iu,
/account:\s*([^\s(]+)/iu,
]);
const host = SourceControlProviderDiscovery.parseCliHost(output);
if (input.exitCode !== 0) {
return SourceControlProviderDiscovery.providerAuth({
status: "unauthenticated",
host,
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
"Run `glab auth login` to authenticate GitLab CLI.",
});
}
if (account) {
return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host });
}
return SourceControlProviderDiscovery.providerAuth({
status: "unknown",
host,
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
"GitLab CLI auth status could not be parsed.",
});
}
export const discovery = {
type: "cli",
kind: "gitlab",
label: "GitLab",
executable: "glab",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitLabAuth,
installHint:
"Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
const gitlab = yield* GitLabCli.GitLabCli;
return SourceControlProvider.SourceControlProvider.of({
kind: "gitlab",
listChangeRequests: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
.listMergeRequests({
cwd: input.cwd,
headSelector: input.headSelector,
...(source ? { source } : {}),
state: input.state,
...(input.limit !== undefined ? { limit: input.limit } : {}),
})
.pipe(
Effect.map((items) => items.map(toChangeRequest)),
Effect.mapError((error) => providerError("listChangeRequests", error)),
);
},
getChangeRequest: (input) =>
gitlab.getMergeRequest(input).pipe(
Effect.map(toChangeRequest),
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
.createMergeRequest({
cwd: input.cwd,
baseBranch: input.baseRefName,
headSelector: input.headSelector,
...(source ? { source } : {}),
...(input.target ? { target: input.target } : {}),
title: input.title,
bodyFile: input.bodyFile,
})
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
},
getRepositoryCloneUrls: (input) =>
gitlab
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
gitlab
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
gitlab
.getDefaultBranch(input)
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
checkoutChangeRequest: (input) =>
gitlab
.checkoutMergeRequest(input)
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
});
});
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
@@ -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,85 +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: false,
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(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(),
}),
},
}),
),
@@ -173,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(
@@ -1,8 +1,5 @@
import {
type SourceControlProviderAuth,
type SourceControlDiscoveryResult,
type SourceControlProviderDiscoveryItem,
type SourceControlProviderKind,
type VcsDiscoveryItem,
type VcsDriverKind,
} from "@t3tools/contracts";
@@ -10,35 +7,27 @@ 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;
readonly executable: string;
readonly versionArgs: ReadonlyArray<string>;
readonly executable?: string;
readonly versionArgs?: ReadonlyArray<string>;
readonly implemented: boolean;
readonly installHint: string;
}
type VcsProbe = DiscoveryProbe & {
readonly kind: VcsDriverKind;
readonly executable: string;
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;
readonly executable: string;
readonly executable?: string;
readonly implemented: boolean;
readonly status: "available" | "missing";
readonly version: Option.Option<string>;
@@ -65,238 +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: false,
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",
executable: "bb",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseBitbucketAuth,
implemented: false,
installHint: "Install a Bitbucket CLI (`bb`) and authenticate it for your Bitbucket workspace.",
},
];
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.",
});
}
function parseBitbucketAuth(input: AuthProbeInput): SourceControlProviderAuth {
const output = combinedAuthOutput(input);
const account = matchFirst(output, [
/Logged in to .* as\s+([^\s(]+)/iu,
/Logged in as\s+([^\s(]+)/iu,
/account:\s*([^\s(]+)/iu,
/user:\s*([^\s(]+)/iu,
/username:\s*([^\s(]+)/iu,
]);
const host = parseCliHost(output) ?? "bitbucket.org";
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
host,
detail:
firstSafeAuthLine(output) ?? "Authenticate the Bitbucket CLI before enabling Bitbucket.",
});
}
if (account) {
return providerAuth({ status: "authenticated", account, host });
}
return providerAuth({
status: "unknown",
host,
detail: firstSafeAuthLine(output) ?? "Bitbucket CLI auth status could not be parsed.",
});
}
export interface SourceControlDiscoveryShape {
readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
}
@@ -311,15 +68,32 @@ 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>> =>
process
): Effect.Effect<DiscoveryProbeResult<Kind>> => {
const executable = input.executable;
const versionArgs = input.versionArgs;
if (!executable || !versionArgs) {
return Effect.succeed({
kind: input.kind,
label: input.label,
implemented: input.implemented,
status: "missing" as const,
version: Option.none<string>(),
installHint: input.installHint,
detail: Option.some(input.installHint),
} satisfies DiscoveryProbeResult<Kind>);
}
return process
.run({
operation: "source-control.discovery.probe",
command: input.executable,
args: input.versionArgs,
command: executable,
args: versionArgs,
cwd: config.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
@@ -331,11 +105,12 @@ export const layer = Layer.effect(
({
kind: input.kind,
label: input.label,
executable: input.executable,
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>(),
@@ -345,54 +120,16 @@ export const layer = Layer.effect(
Effect.succeed({
kind: input.kind,
label: input.label,
executable: input.executable,
executable,
implemented: input.implemented,
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) => {
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: input.executable,
args: input.authArgs,
cwd: config.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
...item,
auth: input.parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
Effect.succeed({
...item,
auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
} satisfies SourceControlProviderDiscoveryItem),
),
);
}),
);
};
return SourceControlDiscovery.of({
discover: Effect.all({
@@ -400,12 +137,7 @@ export const layer = Layer.effect(
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,
}),
});
}),
@@ -6,6 +6,7 @@ import type {
SourceControlProviderInfo,
SourceControlProviderKind,
SourceControlRepositoryCloneUrls,
SourceControlRepositoryVisibility,
} from "@t3tools/contracts";
export interface SourceControlProviderContext {
@@ -20,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: {
@@ -50,6 +78,11 @@ export interface SourceControlProviderShape {
readonly context?: SourceControlProviderContext;
readonly repository: string;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
@@ -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,10 +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 { 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");
@@ -28,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",
@@ -45,12 +51,24 @@ 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)({}))),
Effect.provide(
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),
),
),
),
);
}
@@ -78,27 +96,40 @@ it.effect("routes directly by provider kind for remote-first workflows", () =>
}),
);
it.effect(
"detects GitLab remotes and returns an unsupported provider until one is registered",
() =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
});
it.effect("routes GitLab remotes to the GitLab provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "gitlab");
const error = yield* Effect.flip(
provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/source-control",
state: "open",
}),
);
assert.strictEqual(provider.kind, "gitlab");
}),
);
assert.strictEqual(error.provider, "gitlab");
}),
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", () =>
@@ -1,39 +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 { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.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<
@@ -41,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({
@@ -51,12 +60,13 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
}),
);
return SourceControlProvider.of({
return SourceControlProvider.SourceControlProvider.of({
kind,
listChangeRequests: () => unsupported("listChangeRequests"),
getChangeRequest: () => unsupported("getChangeRequest"),
createChangeRequest: () => unsupported("createChangeRequest"),
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
createRepository: () => unsupported("createRepository"),
getDefaultBranch: () => unsupported("getDefaultBranch"),
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
});
@@ -76,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);
@@ -88,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") ??
@@ -98,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));
@@ -123,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,
@@ -134,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;
}),
@@ -145,16 +204,46 @@ 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" },
),
});
},
);
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,
},
]);
});
@@ -0,0 +1,318 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError, type SourceControlProviderError } from "@t3tools/contracts";
import { ServerConfig } from "../config.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",
url: "https://github.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
};
function makeProvider(
overrides: Partial<SourceControlProvider.SourceControlProviderShape> = {},
): SourceControlProvider.SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
never,
SourceControlProviderError
>;
return {
kind: "github",
listChangeRequests: () => unsupported("listChangeRequests"),
getChangeRequest: () => unsupported("getChangeRequest"),
createChangeRequest: () => unsupported("createChangeRequest"),
getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
createRepository: () => Effect.succeed(CLONE_URLS),
getDefaultBranch: () => Effect.succeed(null),
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
...overrides,
};
}
function processOutput(): GitVcsDriver.ExecuteGitResult {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
function makeLayer(input: {
readonly provider?: SourceControlProvider.SourceControlProviderShape;
readonly git?: Partial<GitVcsDriver.GitVcsDriverShape>;
}) {
return SourceControlRepositoryService.layer.pipe(
Layer.provide(
Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
get: () => Effect.succeed(input.provider ?? makeProvider()),
}),
),
Layer.provide(
Layer.mock(GitVcsDriver.GitVcsDriver)({
execute: () => Effect.succeed(processOutput()),
ensureRemote: () => Effect.succeed("origin"),
pushCurrentBranch: () =>
Effect.succeed({
status: "pushed" as const,
branch: "feature/remote-v1",
upstreamBranch: "origin/feature/remote-v1",
setUpstream: true,
}),
...input.git,
}),
),
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-repos-" })),
Layer.provideMerge(NodeServices.layer),
);
}
it.effect("looks up repositories through the requested provider without search", () => {
const calls: Array<{ cwd: string; repository: string }> = [];
const provider = makeProvider({
getRepositoryCloneUrls: (input) =>
Effect.sync(() => {
calls.push({ cwd: input.cwd, repository: input.repository });
return CLONE_URLS;
}),
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.lookupRepository({
provider: "github",
repository: "octocat/t3code",
cwd: "/workspace",
});
assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
}).pipe(Effect.provide(makeLayer({ provider })));
});
it.effect("clones a looked-up repository into the requested destination", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const parent = yield* fs.makeTempDirectoryScoped({
prefix: "t3-source-control-clone-parent-",
});
const destinationPath = `${parent}/t3code`;
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.cloneRepository({
provider: "github",
repository: "octocat/t3code",
destinationPath,
protocol: "https",
});
assert.deepStrictEqual(result, {
cwd: destinationPath,
remoteUrl: CLONE_URLS.url,
repository: { provider: "github", ...CLONE_URLS },
});
assert.deepStrictEqual(cloneCalls, [
{
cwd: parent,
args: ["clone", CLONE_URLS.url, "t3code"],
},
]);
}).pipe(
Effect.provide(
makeLayer({
git: {
execute: (input) =>
Effect.sync(() => {
cloneCalls.push({ cwd: input.cwd, args: input.args });
return processOutput();
}),
},
}),
),
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
const provider = makeProvider({
createRepository: (input) =>
Effect.sync(() => {
createCalls.push({
cwd: input.cwd,
repository: input.repository,
visibility: input.visibility,
});
return CLONE_URLS;
}),
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
repository: "octocat/t3code",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
});
assert.deepStrictEqual(result, {
repository: { provider: "github", ...CLONE_URLS },
remoteName: "origin",
remoteUrl: CLONE_URLS.sshUrl,
branch: "feature/remote-v1",
upstreamBranch: "origin/feature/remote-v1",
status: "pushed",
});
assert.deepStrictEqual(createCalls, [
{ cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
]);
assert.deepStrictEqual(remoteCalls, [
{ cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
]);
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
}).pipe(
Effect.provide(
makeLayer({
provider,
git: {
ensureRemote: (input) =>
Effect.sync(() => {
remoteCalls.push(input);
return "origin";
}),
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
Effect.sync(() => {
pushCalls.push({ cwd, remoteName: options?.remoteName });
return {
status: "pushed" as const,
branch: "feature/remote-v1",
upstreamBranch: "origin/feature/remote-v1",
setUpstream: true,
};
}),
},
}),
),
);
});
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.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
repository: "octocat/t3code",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
});
assert.equal(result.remoteName, "origin-1");
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
}).pipe(
Effect.provide(
makeLayer({
git: {
ensureRemote: () => Effect.succeed("origin-1"),
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
Effect.sync(() => {
pushCalls.push({ cwd, remoteName: options?.remoteName });
return {
status: "pushed" as const,
branch: "feature/remote-v1",
upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
setUpstream: true,
};
}),
},
}),
),
);
});
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.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
repository: "octocat/t3code",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
});
assert.deepStrictEqual(result, {
repository: { provider: "github", ...CLONE_URLS },
remoteName: "origin",
remoteUrl: CLONE_URLS.sshUrl,
branch: "main",
status: "remote_added",
});
assert.strictEqual(pushCalls, 0);
}).pipe(
Effect.provide(
makeLayer({
git: {
execute: (input) =>
input.args[0] === "rev-parse"
? Effect.fail(
new GitCommandError({
operation: input.operation,
command: "git rev-parse --verify HEAD",
cwd: input.cwd,
detail: "fatal: Needed a single revision",
}),
)
: Effect.succeed(processOutput()),
statusDetails: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
}),
pushCurrentBranch: () =>
Effect.sync(() => {
pushCalls += 1;
return {
status: "pushed" as const,
branch: "main",
upstreamBranch: "origin/main",
setUpstream: true,
};
}),
},
}),
),
);
});
@@ -0,0 +1,320 @@
import * as NodeOS from "node:os";
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
import {
SourceControlRepositoryError,
type SourceControlCloneRepositoryInput,
type SourceControlCloneRepositoryResult,
type SourceControlCloneProtocol,
type SourceControlProviderKind,
type SourceControlPublishRepositoryInput,
type SourceControlPublishRepositoryResult,
type SourceControlRepositoryCloneUrls,
type SourceControlRepositoryInfo,
type SourceControlRepositoryLookupInput,
} from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
export interface SourceControlRepositoryServiceShape {
readonly lookupRepository: (
input: SourceControlRepositoryLookupInput,
) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
readonly cloneRepository: (
input: SourceControlCloneRepositoryInput,
) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
readonly publishRepository: (
input: SourceControlPublishRepositoryInput,
) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
}
export class SourceControlRepositoryService extends Context.Service<
SourceControlRepositoryService,
SourceControlRepositoryServiceShape
>()("t3/source-control/SourceControlRepositoryService") {}
function detailFromUnknown(cause: unknown): string {
if (typeof cause === "object" && cause !== null) {
if ("detail" in cause && typeof cause.detail === "string" && cause.detail.length > 0) {
return cause.detail;
}
if ("message" in cause && typeof cause.message === "string" && cause.message.length > 0) {
return cause.message;
}
}
return "An unexpected source control error occurred.";
}
function repositoryError(input: {
readonly operation: string;
readonly provider: SourceControlProviderKind;
readonly detail: string;
readonly cause?: unknown;
}): SourceControlRepositoryError {
return new SourceControlRepositoryError({
provider: input.provider,
operation: input.operation,
detail: input.detail,
...(input.cause === undefined ? {} : { cause: input.cause }),
});
}
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
return Effect.mapError((cause: unknown) =>
Schema.is(SourceControlRepositoryError)(cause)
? cause
: repositoryError({
operation,
provider,
detail: detailFromUnknown(cause),
cause,
}),
);
}
function toRepositoryInfo(
provider: SourceControlProviderKind,
urls: SourceControlRepositoryCloneUrls,
): SourceControlRepositoryInfo {
return {
provider,
nameWithOwner: urls.nameWithOwner,
url: urls.url,
sshUrl: urls.sshUrl,
};
}
function selectRemoteUrl(
urls: SourceControlRepositoryCloneUrls,
protocol: SourceControlCloneProtocol | undefined,
): string {
switch (protocol ?? "auto") {
case "https":
return urls.url;
case "ssh":
case "auto":
return urls.sshUrl;
}
}
function expandHomePath(input: string, path: Path.Path): string {
if (input === "~") {
return NodeOS.homedir();
}
if (input.startsWith("~/") || input.startsWith("~\\")) {
return path.join(NodeOS.homedir(), input.slice(2));
}
return input;
}
export const make = Effect.fn("makeSourceControlRepositoryService")(function* () {
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver.GitVcsDriver;
const path = yield* Path.Path;
const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const ensureConcreteProvider = (input: {
readonly operation: string;
readonly provider: SourceControlProviderKind;
}) => {
if (input.provider !== "unknown") {
return Effect.succeed(input.provider);
}
return Effect.fail(
repositoryError({
operation: input.operation,
provider: input.provider,
detail: "Choose a source control provider before continuing.",
}),
);
};
const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
input: SourceControlRepositoryLookupInput,
) {
const providerKind = yield* ensureConcreteProvider({
operation: "lookupRepository",
provider: input.provider,
});
const provider = yield* providers.get(providerKind);
const urls = yield* provider.getRepositoryCloneUrls({
cwd: input.cwd ?? config.cwd,
repository: input.repository.trim(),
});
return toRepositoryInfo(providerKind, urls);
});
const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
function* (destinationPath: string) {
const trimmed = destinationPath.trim();
if (trimmed.length === 0) {
return yield* Effect.fail(
repositoryError({
operation: "cloneRepository",
provider: "unknown",
detail: "Choose a destination path before cloning.",
}),
);
}
return path.resolve(expandHomePath(trimmed, path));
},
);
const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
function* (destinationPath: string) {
const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
if (yield* fileSystem.exists(normalizedDestination).pipe(Effect.orElseSucceed(() => false))) {
const entries = yield* fileSystem
.readDirectory(normalizedDestination, { recursive: false })
.pipe(
Effect.mapError((cause) =>
repositoryError({
operation: "cloneRepository",
provider: "unknown",
detail: "Destination path already exists and is not a directory.",
cause,
}),
),
);
if (entries.length > 0) {
return yield* Effect.fail(
repositoryError({
operation: "cloneRepository",
provider: "unknown",
detail: "Destination path already exists and is not empty.",
}),
);
}
} else {
yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
}
return {
destinationPath: normalizedDestination,
parentPath: path.dirname(normalizedDestination),
directoryName: path.basename(normalizedDestination),
};
},
);
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
input: SourceControlCloneRepositoryInput,
) {
const preparedDestination = yield* prepareDestination(input.destinationPath);
let repository: SourceControlRepositoryInfo | null = null;
let remoteUrl = input.remoteUrl?.trim() ?? null;
let provider: SourceControlProviderKind = input.provider ?? "unknown";
if (input.provider && input.repository) {
repository = yield* lookupRepository({
provider: input.provider,
repository: input.repository,
cwd: preparedDestination.parentPath,
});
remoteUrl = selectRemoteUrl(repository, input.protocol);
provider = input.provider;
}
if (!remoteUrl) {
return yield* Effect.fail(
repositoryError({
operation: "cloneRepository",
provider,
detail: "Enter a repository path or clone URL before cloning.",
}),
);
}
yield* git.execute({
operation: "SourceControlRepositoryService.cloneRepository",
cwd: preparedDestination.parentPath,
args: ["clone", remoteUrl, preparedDestination.directoryName],
timeoutMs: 120_000,
maxOutputBytes: 256 * 1024,
});
return {
cwd: preparedDestination.destinationPath,
remoteUrl,
repository,
};
});
const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
function* (input: SourceControlPublishRepositoryInput) {
const providerKind = yield* ensureConcreteProvider({
operation: "publishRepository",
provider: input.provider,
});
const provider = yield* providers.get(providerKind);
const urls = yield* provider.createRepository({
cwd: input.cwd,
repository: input.repository.trim(),
visibility: input.visibility,
});
const remoteUrl = selectRemoteUrl(urls, input.protocol);
const remoteName = yield* git.ensureRemote({
cwd: input.cwd,
preferredName: input.remoteName?.trim() || "origin",
url: remoteUrl,
});
// An empty local repo (no commits) would make `git push HEAD:...` fail
// with an opaque "src refspec HEAD does not match any". Treat this as a
// partial success: the remote was created and wired up, but there is
// nothing to push yet.
const hasCommits = yield* git
.execute({
operation: "SourceControlRepositoryService.publishRepository.headCheck",
cwd: input.cwd,
args: ["rev-parse", "--verify", "HEAD"],
})
.pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
);
if (!hasCommits) {
const details = yield* git
.statusDetails(input.cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
remoteUrl,
branch: details?.branch ?? "main",
status: "remote_added" as const,
};
}
const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
remoteUrl,
branch: pushResult.branch,
...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
status: "pushed" as const,
};
},
);
return SourceControlRepositoryService.of({
lookupRepository: (input) =>
lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
cloneRepository: (input) =>
cloneRepository(input).pipe(
mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
),
publishRepository: (input) =>
publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
});
});
export const layer = Layer.effect(SourceControlRepositoryService, make());
@@ -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 } : {}),
};
}
@@ -0,0 +1,148 @@
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
export interface NormalizedGitLabMergeRequestRecord {
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;
}
const GitLabProjectReferenceSchema = Schema.Struct({
path_with_namespace: Schema.optional(Schema.String),
pathWithNamespace: Schema.optional(Schema.String),
namespace: Schema.optional(
Schema.NullOr(
Schema.Struct({
path: Schema.optional(Schema.String),
full_path: Schema.optional(Schema.String),
fullPath: Schema.optional(Schema.String),
}),
),
),
});
const GitLabMergeRequestSchema = Schema.Struct({
iid: PositiveInt,
title: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
source_branch: TrimmedNonEmptyString,
target_branch: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
source_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
target_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
source_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
target_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function normalizeGitLabMergeRequestState(
state: string | null | undefined,
): "open" | "closed" | "merged" {
const normalized = state?.trim().toLowerCase();
if (normalized === "merged") {
return "merged";
}
if (normalized === "closed") {
return "closed";
}
return "open";
}
function projectPathWithNamespace(
project: Schema.Schema.Type<typeof GitLabProjectReferenceSchema> | null | undefined,
): string | null {
const explicit =
trimOptionalString(project?.path_with_namespace) ??
trimOptionalString(project?.pathWithNamespace);
if (explicit) {
return explicit;
}
const namespacePath =
trimOptionalString(project?.namespace?.full_path) ??
trimOptionalString(project?.namespace?.fullPath) ??
trimOptionalString(project?.namespace?.path);
return namespacePath;
}
function ownerLoginFromPathWithNamespace(pathWithNamespace: string | null): string | null {
const [owner] = pathWithNamespace?.split("/") ?? [];
return trimOptionalString(owner);
}
function normalizeGitLabMergeRequestRecord(
raw: Schema.Schema.Type<typeof GitLabMergeRequestSchema>,
): NormalizedGitLabMergeRequestRecord {
const sourceProjectPath = projectPathWithNamespace(raw.source_project);
const targetProjectPath = projectPathWithNamespace(raw.target_project);
const isCrossRepository =
typeof raw.source_project_id === "number" && typeof raw.target_project_id === "number"
? raw.source_project_id !== raw.target_project_id
: sourceProjectPath !== null && targetProjectPath !== null
? sourceProjectPath.toLowerCase() !== targetProjectPath.toLowerCase()
: undefined;
const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath);
return {
number: raw.iid,
title: raw.title,
url: raw.web_url,
baseRefName: raw.target_branch,
headRefName: raw.source_branch,
state: normalizeGitLabMergeRequestState(raw.state),
updatedAt: raw.updated_at ?? Option.none(),
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
const decodeGitLabMergeRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeGitLabMergeRequest = decodeJsonResult(GitLabMergeRequestSchema);
const decodeGitLabMergeRequestEntry = Schema.decodeUnknownExit(GitLabMergeRequestSchema);
export const formatGitLabJsonDecodeError = formatSchemaError;
export function decodeGitLabMergeRequestListJson(
raw: string,
): Result.Result<
ReadonlyArray<NormalizedGitLabMergeRequestRecord>,
Cause.Cause<Schema.SchemaError>
> {
const result = decodeGitLabMergeRequestList(raw);
if (Result.isSuccess(result)) {
const mergeRequests: NormalizedGitLabMergeRequestRecord[] = [];
for (const entry of result.success) {
const decodedEntry = decodeGitLabMergeRequestEntry(entry);
if (Exit.isFailure(decodedEntry)) {
continue;
}
mergeRequests.push(normalizeGitLabMergeRequestRecord(decodedEntry.value));
}
return Result.succeed(mergeRequests);
}
return Result.fail(result.failure);
}
export function decodeGitLabMergeRequestJson(
raw: string,
): Result.Result<NormalizedGitLabMergeRequestRecord, Cause.Cause<Schema.SchemaError>> {
const result = decodeGitLabMergeRequest(raw);
if (Result.isSuccess(result)) {
return Result.succeed(normalizeGitLabMergeRequestRecord(result.success));
}
return Result.fail(result.failure);
}
+127 -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;
@@ -55,6 +55,7 @@ export interface GitStatusDetails {
hasUpstream: boolean;
aheadCount: number;
behindCount: number;
aheadOfDefaultCount: number;
}
export interface GitPreparedCommitContext {
@@ -133,6 +134,12 @@ export interface GitFetchRemoteBranchInput {
localBranch: string;
}
export interface GitFetchRemoteTrackingBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
@@ -158,6 +165,7 @@ export interface GitVcsDriverShape {
readonly pushCurrentBranch: (
cwd: string,
fallbackBranch: string | null,
options?: { readonly remoteName?: string | null },
) => Effect.Effect<GitPushResult, GitCommandError>;
readonly readRangeContext: (
cwd: string,
@@ -176,9 +184,13 @@ export interface GitVcsDriverShape {
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly fetchRemoteTrackingBranch: (
input: GitFetchRemoteTrackingBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
@@ -292,7 +304,7 @@ function parseGitRemoteVerboseOutput(
}
const gitCommand = (
process: VcsProcessShape,
process: VcsProcess.VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
@@ -323,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,
@@ -333,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",
@@ -346,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 } : {}),
@@ -358,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",
@@ -426,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,
@@ -526,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());
+121 -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";
@@ -102,6 +101,51 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
);
}),
);
it.effect("reports default-branch delta separately from upstream delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/synced"]);
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* git(cwd, ["add", "feature.txt"]);
yield* git(cwd, ["commit", "-m", "feature commit"]);
yield* git(cwd, ["push", "-u", "origin", "feature/synced"]);
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal(status.hasUpstream, true);
assert.equal(status.aheadCount, 0);
assert.equal(status.behindCount, 0);
assert.equal(status.aheadOfDefaultCount, 1);
}),
);
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/no-upstream"]);
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* git(cwd, ["add", "feature.txt"]);
yield* git(cwd, ["commit", "-m", "feature commit"]);
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal(status.hasUpstream, false);
assert.equal(status.aheadCount, 1);
assert.equal(status.behindCount, 0);
assert.equal(status.aheadOfDefaultCount, 1);
}),
);
});
describe("refName operations", () => {
@@ -242,5 +286,80 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
}),
);
it.effect(
"pushes upstream branches to the remote branch name, not the upstream shorthand",
() =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-remote-");
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* git(cwd, ["branch", "-M", "main"]);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", "main"]);
yield* writeTextFile(cwd, "upstream.txt", "upstream\n");
yield* driver.prepareCommitContext(cwd);
yield* driver.commit(cwd, "Add upstream update", "");
const pushed = yield* driver.pushCurrentBranch(cwd, null);
assert.deepInclude(pushed, {
status: "pushed",
branch: "main",
upstreamBranch: "origin/main",
setUpstream: false,
});
assert.equal(
yield* git(remote, ["log", "-1", "--pretty=%s", "main"]),
"Add upstream update",
);
const badBranch = yield* driver.execute({
operation: "GitVcsDriver.test.showBadRemoteBranch",
cwd: remote,
args: ["show-ref", "--verify", "--quiet", "refs/heads/origin/main"],
allowNonZeroExit: true,
timeoutMs: 10_000,
});
assert.notEqual(badBranch.exitCode, 0);
}),
);
it.effect("pushes to the requested remote instead of the primary remote", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const originRemote = yield* makeTmpDir("git-origin-remote-");
const publishRemote = yield* makeTmpDir("git-publish-remote-");
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* git(cwd, ["branch", "-M", "main"]);
yield* git(originRemote, ["init", "--bare"]);
yield* git(publishRemote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", originRemote]);
yield* git(cwd, ["remote", "add", "origin-1", publishRemote]);
const pushed = yield* driver.pushCurrentBranch(cwd, null, { remoteName: "origin-1" });
assert.deepInclude(pushed, {
status: "pushed",
branch: "main",
upstreamBranch: "origin-1/main",
setUpstream: true,
});
assert.equal(
yield* git(publishRemote, ["log", "-1", "--pretty=%s", "main"]),
"initial commit",
);
const originMain = yield* driver.execute({
operation: "GitVcsDriver.test.originMainMissing",
cwd: originRemote,
args: ["show-ref", "--verify", "--quiet", "refs/heads/main"],
allowNonZeroExit: true,
timeoutMs: 10_000,
});
assert.notEqual(originMain.exitCode, 0);
}),
);
});
});
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);
+59 -1
View File
@@ -55,6 +55,15 @@ import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentit
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,
@@ -154,6 +163,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
const serverEnvironment = yield* ServerEnvironment;
const serverAuth = yield* ServerAuth;
const sourceControlDiscovery = yield* SourceControlDiscoveryLayer.SourceControlDiscovery;
const sourceControlRepositories = yield* SourceControlRepositoryService;
const bootstrapCredentials = yield* BootstrapCredentialService;
const sessions = yield* SessionCredentialService;
const serverCommandId = (tag: string) =>
@@ -670,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({
@@ -794,6 +807,32 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
"rpc.aggregate": "server",
},
),
[WS_METHODS.sourceControlLookupRepository]: (input) =>
observeRpcEffect(
WS_METHODS.sourceControlLookupRepository,
sourceControlRepositories.lookupRepository(input),
{
"rpc.aggregate": "source-control",
},
),
[WS_METHODS.sourceControlCloneRepository]: (input) =>
observeRpcEffect(
WS_METHODS.sourceControlCloneRepository,
sourceControlRepositories.cloneRepository(input),
{
"rpc.aggregate": "source-control",
},
),
[WS_METHODS.sourceControlPublishRepository]: (input) =>
observeRpcEffect(
WS_METHODS.sourceControlPublishRepository,
sourceControlRepositories
.publishRepository(input)
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{
"rpc.aggregate": "source-control",
},
),
[WS_METHODS.projectsSearchEntries]: (input) =>
observeRpcEffect(
WS_METHODS.projectsSearchEntries,
@@ -989,6 +1028,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
version: 1 as const,
type: "keybindingsUpdated" as const,
payload: {
keybindings: event.keybindings,
issues: event.issues,
},
})),
@@ -1102,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">
+268 -6
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";
@@ -206,6 +207,7 @@ function createMockEnvironmentApi(input: {
filesystem: {
browse: input.browse,
},
sourceControl: {} as EnvironmentApi["sourceControl"],
vcs: {} as EnvironmentApi["vcs"],
git: {} as EnvironmentApi["git"],
orchestration: {
@@ -952,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,
@@ -1662,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: {
@@ -4257,8 +4394,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
@@ -4310,8 +4446,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
@@ -4384,13 +4519,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
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/");
@@ -4437,6 +4572,126 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("shows clone destination controls after resolving an add project repository", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-command-palette-add-project-remote" as MessageId,
targetText: "command palette add project remote",
}),
configureFixture: (nextFixture) => {
nextFixture.serverConfig = {
...nextFixture.serverConfig,
keybindings: [
{
command: "commandPalette.toggle",
shortcut: {
key: "k",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
},
whenAst: {
type: "not",
node: { type: "identifier", name: "terminalFocus" },
},
},
],
};
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.filesystemBrowse) {
return {
parentPath: "~/",
entries: [{ name: "Development", fullPath: "~/Development" }],
};
}
if (body._tag === WS_METHODS.sourceControlLookupRepository) {
return {
provider: "github",
nameWithOwner: "t3-oss/t3-env",
url: "https://github.com/t3-oss/t3-env",
sshUrl: "[email protected]:t3-oss/t3-env.git",
};
}
if (body._tag === WS_METHODS.sourceControlCloneRepository) {
return {
cwd: body.destinationPath,
remoteUrl: body.remoteUrl,
repository: null,
};
}
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
sequence: fixture.snapshot.snapshotSequence + 1,
};
}
return undefined;
},
});
try {
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
await palette.getByText("GitHub repository", { exact: true }).click();
const repositoryInput = await waitForCommandPaletteInput(
"Enter GitHub repository (owner/repo)",
);
await page.getByPlaceholder("Enter GitHub repository (owner/repo)").fill("t3-oss/t3-env");
await dispatchInputKey(repositoryInput, { key: "Enter" });
await vi.waitFor(
() => {
const clonePathInput = document.querySelector<HTMLInputElement>(
'input[placeholder="Enter path (e.g. ~/projects/my-app)"]',
);
expect(clonePathInput?.value).toBe("~/");
expect(document.body.textContent).toContain("Repository");
expect(document.body.textContent).toContain("t3-oss/t3-env");
expect(document.body.textContent).toContain("https://github.com/t3-oss/t3-env");
expect(document.body.textContent).toContain("Select where to clone");
expect(document.body.textContent).toContain("Development");
expect(document.body.textContent).toContain("Clone");
},
{ timeout: 8_000, interval: 16 },
);
await page
.getByPlaceholder("Enter path (e.g. ~/projects/my-app)")
.fill("~/Development/t3env");
const clonePathInput = await waitForCommandPaletteInput(
"Enter path (e.g. ~/projects/my-app)",
);
await dispatchInputKey(clonePathInput, { key: "Enter" });
await vi.waitFor(
() => {
const cloneRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.sourceControlCloneRepository,
) as { destinationPath?: string; remoteUrl?: string } | undefined;
expect(cloneRequest).toMatchObject({
remoteUrl: "[email protected]:t3-oss/t3-env.git",
destinationPath: "~/Development/t3env",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("opens add project browse mode from the sidebar add button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -4463,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("~/");
@@ -4525,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/");
@@ -4584,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");
@@ -4663,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/");
@@ -4794,6 +5053,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
.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/");
@@ -4887,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");
@@ -5004,6 +5265,7 @@ 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();
const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER);
await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/");
+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). */
+660 -49
View File
@@ -7,9 +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,
@@ -17,6 +21,7 @@ import {
CornerLeftUpIcon,
FolderIcon,
FolderPlusIcon,
LinkIcon,
MessageSquareIcon,
SettingsIcon,
SquarePenIcon,
@@ -25,6 +30,7 @@ import {
useCallback,
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -42,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,
@@ -89,6 +99,7 @@ import {
} from "./CommandPalette.logic";
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
import { ProjectFavicon } from "./ProjectFavicon";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { useServerKeybindings } from "../rpc/serverState";
@@ -104,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";
@@ -139,6 +151,181 @@ interface AddProjectEnvironmentOption {
readonly isPrimary: boolean;
}
type AddProjectRemoteProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "bitbucket" | "azure-devops"
>;
type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url";
type AddProjectCloneFlow =
| {
readonly step: "repository";
readonly environmentId: EnvironmentId;
readonly source: AddProjectRemoteSource;
}
| {
readonly step: "confirm";
readonly environmentId: EnvironmentId;
readonly source: AddProjectRemoteSource;
readonly repositoryInput: string;
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
};
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) {
case "github":
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 {
return source === "url" ? null : source;
}
function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: string): ReactNode {
switch (source) {
case "github":
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} />;
}
}
function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null {
if (!flow) return null;
if (flow.step === "confirm") return null;
if (flow.source === "url") {
return "Enter Git clone URL";
}
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 {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return "An error occurred.";
}
export function CommandPalette({ children }: { children: ReactNode }) {
const open = useCommandPaletteStore((store) => store.open);
const setOpen = useCommandPaletteStore((store) => store.setOpen);
@@ -227,6 +414,9 @@ function OpenCommandPaletteDialog() {
null,
);
const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false);
const [addProjectCloneFlow, setAddProjectCloneFlow] = useState<AddProjectCloneFlow | null>(null);
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null;
const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId);
@@ -295,7 +485,10 @@ function OpenCommandPaletteDialog() {
: null;
return getEnvironmentBrowsePlatform(os);
}, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
const isRemoteProjectCloneFlow = addProjectCloneFlow !== null;
const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
const isBrowsing =
!isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
const getAddProjectInitialQueryForEnvironment = useCallback(
(environmentId: EnvironmentId | null): string => {
@@ -541,6 +734,7 @@ function OpenCommandPaletteDialog() {
}
function popView(): void {
setAddProjectCloneFlow(null);
if (viewStack.length <= 1) {
setAddProjectEnvironmentId(null);
}
@@ -560,6 +754,7 @@ function OpenCommandPaletteDialog() {
const startAddProjectBrowse = useCallback(
(environmentId: EnvironmentId): void => {
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow(null);
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: [],
@@ -569,6 +764,158 @@ function OpenCommandPaletteDialog() {
[getAddProjectInitialQueryForEnvironment],
);
const startAddProjectClone = useCallback(
(environmentId: EnvironmentId, source: AddProjectRemoteSource): void => {
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow({ step: "repository", environmentId, source });
pushPaletteView({
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
groups: [],
initialQuery: "",
});
},
[],
);
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",
@@ -579,7 +926,7 @@ function OpenCommandPaletteDialog() {
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
startAddProjectBrowse(option.environmentId);
startAddProjectSourceSelection(option.environmentId);
},
}),
);
@@ -616,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;
}
@@ -674,29 +1021,34 @@ function OpenCommandPaletteDialog() {
});
}
if (addProjectEnvironmentOptions.length > 1) {
actionItems.push({
kind: "submenu",
value: "action:add-project",
searchTerms: ["add project", "folder", "directory", "browse", "environment"],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
});
} else {
actionItems.push({
kind: "action",
value: "action:add-project",
searchTerms: ["add project", "folder", "directory", "browse"],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
openAddProjectFlow();
},
});
}
actionItems.push({
kind: "action",
value: "action:add-project",
searchTerms: [
"add project",
"folder",
"directory",
"browse",
"clone",
"remote",
"repository",
"repo",
"git",
"github",
"gitlab",
"bitbucket",
"azure",
"devops",
"url",
"environment",
],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
openAddProjectFlow();
},
});
actionItems.push({
kind: "action",
@@ -820,6 +1172,137 @@ function OpenCommandPaletteDialog() {
],
);
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
return getAddProjectInitialQueryForEnvironment(environmentId);
}
async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
if (!addProjectCloneFlow) {
return;
}
const api = readEnvironmentApi(addProjectCloneFlow.environmentId);
if (!api) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to clone project",
description: "Environment API is not available.",
}),
);
return;
}
if (addProjectCloneFlow.step === "repository") {
const rawRepository = query.trim();
if (rawRepository.length === 0 || isRemoteProjectLookingUp) {
return;
}
const provider = remoteProjectSourceProvider(addProjectCloneFlow.source);
if (!provider) {
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository: null,
remoteUrl: rawRepository,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
return;
}
setIsRemoteProjectLookingUp(true);
try {
const repository = await api.sourceControl.lookupRepository({
provider,
repository: rawRepository,
});
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository,
remoteUrl: repository.sshUrl,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Repository lookup failed",
description: errorMessage(error),
}),
);
} finally {
setIsRemoteProjectLookingUp(false);
}
return;
}
const rawDestination = (destinationPathInput ?? query).trim();
if (rawDestination.length === 0 || isRemoteProjectCloning) {
return;
}
if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Windows-style paths are only supported on Windows.",
}),
);
return;
}
if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Relative paths require an active project.",
}),
);
return;
}
const destinationPath = resolveProjectPathForDispatch(
rawDestination,
currentProjectCwdForBrowse,
);
if (destinationPath.length === 0) {
return;
}
setIsRemoteProjectCloning(true);
try {
const result = await api.sourceControl.cloneRepository({
remoteUrl: addProjectCloneFlow.remoteUrl,
destinationPath,
});
await handleAddProject(result.cwd);
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(error),
}),
);
} finally {
setIsRemoteProjectCloning(false);
}
}
function browseTo(name: string): void {
const nextQuery = appendBrowsePathSegment(query, name);
setHighlightedItemValue(null);
@@ -858,13 +1341,38 @@ function OpenCommandPaletteDialog() {
browseUp,
browseTo,
});
const cloneDestinationBrowseGroups = useMemo(
() =>
browseGroups.map((group) =>
group.value === "directories" ? { ...group, label: "Select where to clone" } : group,
),
[browseGroups],
);
let displayedGroups = filteredGroups;
if (isBrowsing) {
const remoteProjectContext = useMemo(() => {
if (addProjectCloneFlow?.step !== "confirm") {
return null;
}
return {
title: addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.repositoryInput,
description: addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl,
icon: remoteProjectSourceIcon(addProjectCloneFlow.source, ITEM_ICON_CLASS),
};
}, [addProjectCloneFlow]);
let displayedGroups: CommandPaletteView["groups"] = filteredGroups;
if (addProjectCloneFlow?.step === "repository") {
displayedGroups = [];
} else if (addProjectCloneFlow?.step === "confirm") {
displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups;
} else if (isBrowsing) {
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
}
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
const inputPlaceholder =
remoteProjectInputPlaceholder(addProjectCloneFlow) ??
getCommandPaletteInputPlaceholder(paletteMode);
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
@@ -876,8 +1384,25 @@ function OpenCommandPaletteDialog() {
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
const useMetaForMod = isMacPlatform(navigator.platform);
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
const submitActionLabel = willCreateProjectPath ? "Create & Add" : "Add";
const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm";
const submitActionLabel = isCloneDestinationStep
? willCreateProjectPath
? "Create & Clone"
: "Clone"
: willCreateProjectPath
? "Create & Add"
: "Add";
const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter";
const remoteProjectButtonLabel = addProjectCloneFlow
? addProjectCloneFlow.source === "url"
? "Continue"
: "Lookup"
: null;
const isRemoteProjectPending = isRemoteProjectLookingUp || isRemoteProjectCloning;
const canSubmitRemoteProjectFlow =
addProjectCloneFlow?.step === "repository" &&
query.trim().length > 0 &&
!isRemoteProjectPending;
const fileManagerName = getLocalFileManagerName(navigator.platform);
const canOpenProjectFromFileManager =
isBrowsing &&
@@ -915,6 +1440,12 @@ function OpenCommandPaletteDialog() {
}
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") {
event.preventDefault();
void submitAddProjectCloneFlow();
return;
}
const shouldSubmitBrowsePath =
canSubmitBrowsePath &&
event.key === "Enter" &&
@@ -922,7 +1453,11 @@ function OpenCommandPaletteDialog() {
if (shouldSubmitBrowsePath) {
event.preventDefault();
void handleAddProject(resolvedAddProjectPath);
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
return;
}
@@ -933,6 +1468,10 @@ function OpenCommandPaletteDialog() {
}
function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
if (item.disabled) {
return;
}
if (item.kind === "submenu") {
pushView(item);
return;
@@ -999,9 +1538,9 @@ function OpenCommandPaletteDialog() {
}}
>
<Command
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
aria-label="Command palette"
autoHighlight={isBrowsing ? false : "always"}
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
mode="none"
onItemHighlighted={(value) => {
setHighlightedItemValue(typeof value === "string" ? value : null);
@@ -1011,7 +1550,15 @@ function OpenCommandPaletteDialog() {
>
<div className="relative">
<CommandInput
className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
className={
addProjectCloneFlow?.step === "repository"
? "pe-32"
: isBrowsing
? willCreateProjectPath
? "pe-36"
: "pe-16"
: undefined
}
placeholder={inputPlaceholder}
wrapperClassName={
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
@@ -1036,17 +1583,40 @@ function OpenCommandPaletteDialog() {
: {})}
onKeyDown={handleKeyDown}
/>
{isBrowsing ? (
{addProjectCloneFlow?.step === "repository" ? (
<Button
variant="outline"
size="xs"
tabIndex={-1}
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) => {
event.preventDefault();
}}
onClick={() => {
void submitAddProjectCloneFlow();
}}
title={`${remoteProjectButtonLabel ?? "Continue"} (Enter)`}
>
<span>{isRemoteProjectPending ? "Working" : remoteProjectButtonLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>Enter</Kbd>
</KbdGroup>
</Button>
) : isBrowsing ? (
<Button
variant="outline"
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})`}
disabled={relativePathNeedsActiveProject}
disabled={
relativePathNeedsActiveProject || (isCloneDestinationStep && isRemoteProjectPending)
}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -1054,11 +1624,17 @@ function OpenCommandPaletteDialog() {
if (relativePathNeedsActiveProject) {
return;
}
void handleAddProject(resolvedAddProjectPath);
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
}}
title={`${submitActionLabel} (${addShortcutLabel})`}
>
<span>{submitActionLabel}</span>
<span>
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
@@ -1066,19 +1642,47 @@ function OpenCommandPaletteDialog() {
) : null}
</div>
<CommandPanel className="max-h-[min(28rem,70vh)]">
{remoteProjectContext ? (
<div className="p-2 pb-0">
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
Repository
</div>
<div className="flex min-h-8 items-center gap-2 rounded-sm px-2 py-1.5">
{remoteProjectContext.icon}
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-foreground text-sm">
{remoteProjectContext.title}
</span>
<span className="truncate text-muted-foreground/70 text-xs">
{remoteProjectContext.description}
</span>
</span>
</div>
</div>
) : null}
<CommandPaletteResults
groups={displayedGroups}
highlightedItemValue={highlightedItemValue}
isActionsOnly={isActionsOnly}
keybindings={keybindings}
onExecuteItem={executeItem}
{...(relativePathNeedsActiveProject
? { emptyStateMessage: "Relative paths require an active project." }
: willCreateProjectPath
? {
emptyStateMessage: "Press Enter to create this folder and add it as a project.",
}
: {})}
{...(addProjectCloneFlow?.step === "repository"
? {
emptyStateMessage:
addProjectCloneFlow.source === "url"
? "Enter a Git clone URL and press Enter to continue."
: "Enter a repository path and press Enter to look it up.",
}
: addProjectCloneFlow?.step === "confirm"
? { emptyStateMessage: "Choose a destination path and press Enter to clone." }
: relativePathNeedsActiveProject
? { emptyStateMessage: "Relative paths require an active project." }
: willCreateProjectPath
? {
emptyStateMessage:
"Press Enter to create this folder and add it as a project.",
}
: {})}
/>
</CommandPanel>
<CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
@@ -1092,7 +1696,14 @@ function OpenCommandPaletteDialog() {
</Kbd>
<span className={cn("text-muted-foreground/80")}>Navigate</span>
</KbdGroup>
{!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
{addProjectCloneFlow?.step === "repository" ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>
{remoteProjectButtonLabel ?? "Continue"}
</span>
</KbdGroup>
) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>Select</span>
@@ -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}
+17 -1
View File
@@ -8,6 +8,7 @@ import {
ChevronLeftIcon,
ChevronRightIcon,
Columns2Icon,
PilcrowIcon,
Rows3Icon,
TextWrapIcon,
} from "lucide-react";
@@ -172,6 +173,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const settings = useSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
const previousDiffOpenRef = useRef(false);
@@ -277,6 +279,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
threadId: activeThreadId,
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
ignoreWhitespace: diffIgnoreWhitespace,
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
enabled: isGitRepo,
}),
@@ -317,9 +320,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
useEffect(() => {
if (diffOpen && !previousDiffOpenRef.current) {
setDiffWordWrap(settings.diffWordWrap);
setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace);
}
previousDiffOpenRef.current = diffOpen;
}, [diffOpen, settings.diffWordWrap]);
}, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]);
useEffect(() => {
if (!selectedFilePath || !patchViewportRef.current) {
@@ -551,6 +555,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
>
<TextWrapIcon className="size-3" />
</Toggle>
<Toggle
aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
variant="outline"
size="xs"
pressed={diffIgnoreWhitespace}
onPressedChange={(pressed) => {
setDiffIgnoreWhitespace(Boolean(pressed));
}}
>
<PilcrowIcon className="size-3" />
</Toggle>
</div>
</>
);
@@ -100,12 +100,14 @@ vi.mock("~/editorPreferences", () => ({
vi.mock("~/lib/gitReactQuery", () => ({
gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
gitMutationKeys: {
publishRepository: vi.fn(() => ["publish-repository"]),
pull: vi.fn(() => ["pull"]),
runStackedAction: vi.fn(() => ["run-stacked-action"]),
},
gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
invalidateGitQueries: invalidateGitQueriesSpy,
sourceControlPublishRepositoryMutationOptions: vi.fn(() => ({ __kind: "publish-repository" })),
}));
vi.mock("~/lib/gitStatusState", () => ({
@@ -280,6 +280,26 @@ describe("when: source control provider uses merge requests", () => {
});
describe("when: ref is clean, up to date, and has no open PR", () => {
it("enables create PR when synced with upstream but ahead of default", () => {
const syncedFeature = status({
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 1,
pr: null,
});
const quick = resolveQuickAction(syncedFeature, false);
assert.deepInclude(quick, {
label: "Create PR",
disabled: false,
kind: "run_action",
action: "create_pr",
});
const items = buildMenuItems(syncedFeature, false);
assert.equal(items.find((item) => item.id === "pr")?.disabled, false);
});
it("resolveQuickAction returns disabled no-action state", () => {
const quick = resolveQuickAction(
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
@@ -444,6 +464,48 @@ describe("when: working tree has local changes", () => {
},
]);
});
it("buildMenuItems enables push for ahead commits while local changes remain uncommitted", () => {
const items = buildMenuItems(
status({
refName: "feature/test",
hasWorkingTreeChanges: true,
aheadCount: 1,
workingTree: {
files: [{ path: ".vercel/project.json", insertions: 1, deletions: 0 }],
insertions: 1,
deletions: 0,
},
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: false,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: on default ref without open PR", () => {
@@ -668,7 +730,7 @@ describe("when: ref has no upstream configured", () => {
});
});
it("resolveQuickAction disables push-and-pr flows when no origin remote exists", () => {
it("resolveQuickAction publishes when no origin remote exists", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
@@ -680,10 +742,9 @@ describe("when: ref has no upstream configured", () => {
false,
);
assert.deepEqual(quick, {
kind: "show_hint",
label: "Push",
hint: 'Add an "origin" remote before pushing or creating a pull request.',
disabled: true,
kind: "open_publish",
label: "Publish repository",
disabled: false,
});
});
@@ -717,7 +778,7 @@ describe("when: ref has no upstream configured", () => {
]);
});
it("buildMenuItems disables push and create PR when no origin remote exists", () => {
it("buildMenuItems hides push and create PR when no origin remote exists", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
false,
@@ -732,22 +793,6 @@ describe("when: ref has no upstream configured", () => {
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
@@ -26,7 +26,7 @@ export interface GitActionMenuItem {
export interface GitQuickAction {
label: string;
disabled: boolean;
kind: "run_action" | "run_pull" | "open_pr" | "show_hint";
kind: "run_action" | "run_pull" | "open_pr" | "open_publish" | "show_hint";
action?: GitStackedAction;
hint?: string;
}
@@ -103,12 +103,12 @@ export function buildMenuItems(
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isBehind = gitStatus.behindCount > 0;
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
const canCommit = !isBusy && hasChanges;
const canPush =
!isBusy &&
hasBranch &&
!hasChanges &&
!isBehind &&
gitStatus.aheadCount > 0 &&
(gitStatus.hasUpstream || canPushWithoutUpstream);
@@ -117,20 +117,26 @@ export function buildMenuItems(
hasBranch &&
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
hasDefaultBranchDelta &&
!isBehind &&
(gitStatus.hasUpstream || canPushWithoutUpstream);
const canOpenPr = !isBusy && hasOpenPr;
const commitItem: GitActionMenuItem = {
id: "commit",
label: "Commit",
disabled: !canCommit,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
};
if (!hasPrimaryRemote) {
return [commitItem];
}
return [
{
id: "commit",
label: "Commit",
disabled: !canCommit,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
commitItem,
{
id: "push",
label: "Push",
@@ -181,6 +187,7 @@ export function resolveQuickAction(
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isAhead = gitStatus.aheadCount > 0;
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
const isBehind = gitStatus.behindCount > 0;
const isDiverged = isAhead && isBehind;
const terminology = resolveChangeRequestTerminology(gitStatus);
@@ -215,10 +222,9 @@ export function resolveQuickAction(
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
}
return {
label: "Push",
disabled: true,
kind: "show_hint",
hint: `Add an "origin" remote before pushing or creating a ${terminology.singular}.`,
label: "Publish repository",
disabled: false,
kind: "open_publish",
};
}
if (!isAhead) {
@@ -286,6 +292,15 @@ export function resolveQuickAction(
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
}
if (hasDefaultBranchDelta && !isDefaultRef) {
return {
label: `Create ${terminology.shortLabel}`,
disabled: false,
kind: "run_action",
action: "create_pr",
};
}
return {
label: "Commit",
disabled: true,
+753 -2
View File
@@ -3,11 +3,33 @@ import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
SourceControlCloneProtocol,
SourceControlProviderDiscoveryItem,
SourceControlProviderKind,
SourceControlPublishRepositoryResult,
SourceControlRepositoryVisibility,
VcsStatusResult,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { Option } from "effect";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { flushSync } from "react-dom";
import {
CheckIcon,
ChevronDownIcon,
CloudUploadIcon,
ExternalLinkIcon,
GitCommitIcon,
InfoIcon,
LockIcon,
GlobeIcon,
} from "lucide-react";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "~/components/Icons";
import { RadioGroup } from "~/components/ui/radio-group";
import { Spinner } from "~/components/ui/spinner";
import { cn } from "~/lib/utils";
import {
buildGitActionProgressStages,
buildMenuItems,
@@ -21,6 +43,7 @@ import {
resolveQuickAction,
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
import { AnimatedHeight } from "./AnimatedHeight";
import { Button } from "~/components/ui/button";
import { Checkbox } from "~/components/ui/checkbox";
import {
@@ -33,19 +56,23 @@ import {
DialogTitle,
} from "~/components/ui/dialog";
import { Group, GroupSeparator } from "~/components/ui/group";
import { Input } from "~/components/ui/input";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { stackedThreadToast, toastManager, type ThreadToastData } from "~/components/ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { openInPreferredEditor } from "~/editorPreferences";
import {
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
sourceControlPublishRepositoryMutationOptions,
} from "~/lib/gitReactQuery";
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { useSourceControlDiscovery } from "~/lib/sourceControlDiscoveryState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
@@ -70,6 +97,11 @@ interface PendingDefaultBranchAction {
filePaths?: string[];
}
type PublishProviderKind = Extract<
SourceControlProviderKind,
"github" | "gitlab" | "bitbucket" | "azure-devops"
>;
type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
@@ -97,6 +129,88 @@ interface RunGitActionWithToastInput {
const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250;
const PUBLISH_PROVIDER_OPTIONS = [
{
value: "github",
label: "GitHub",
description: "github.com",
host: "github.com",
pathPlaceholder: "owner/repo",
Icon: GitHubIcon,
},
{
value: "gitlab",
label: "GitLab",
description: "gitlab.com",
host: "gitlab.com",
pathPlaceholder: "group/project",
Icon: GitLabIcon,
},
{
value: "bitbucket",
label: "Bitbucket",
description: "bitbucket.org",
host: "bitbucket.org",
pathPlaceholder: "workspace/repository",
Icon: BitbucketIcon,
},
{
value: "azure-devops",
label: "Azure DevOps",
description: "dev.azure.com",
host: "dev.azure.com",
pathPlaceholder: "project/repository",
Icon: AzureDevOpsIcon,
},
] as const satisfies ReadonlyArray<{
readonly value: PublishProviderKind;
readonly label: string;
readonly description: string;
readonly host: string;
readonly pathPlaceholder: string;
readonly Icon: typeof GitHubIcon;
}>;
function publishProviderOption(provider: PublishProviderKind) {
return (
PUBLISH_PROVIDER_OPTIONS.find((option) => option.value === provider) ??
PUBLISH_PROVIDER_OPTIONS[0]
);
}
function isPublishProviderKind(
provider: SourceControlProviderKind,
): provider is PublishProviderKind {
return PUBLISH_PROVIDER_OPTIONS.some((option) => option.value === provider);
}
function getPublishProviderReadiness(input: {
provider: PublishProviderKind;
sourceControlProviders: ReadonlyArray<SourceControlProviderDiscoveryItem>;
}): { readonly ready: boolean; readonly hint: string | null } {
const discovered = input.sourceControlProviders.find(
(provider) => provider.kind === input.provider,
);
if (!discovered) {
return {
ready: false,
hint: "Provider status unavailable. Open Settings -> Source Control and rescan.",
};
}
if (discovered.status !== "available") {
return { ready: false, hint: discovered.installHint };
}
if (discovered.auth.status === "unauthenticated") {
return {
ready: false,
hint:
Option.getOrNull(discovered.auth.detail) ??
`${discovered.label} is not authenticated. Open Settings -> Source Control for setup guidance.`,
};
}
return { ready: true, hint: null };
}
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
if (startedAtMs === null) {
return undefined;
@@ -211,6 +325,7 @@ function GitQuickActionIcon({
}) {
const iconClassName = "size-3.5";
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
@@ -223,6 +338,613 @@ function GitQuickActionIcon({
return <InfoIcon className={iconClassName} />;
}
interface PublishRepositoryDialogProps {
readonly open: boolean;
readonly onOpenChange: (open: boolean) => void;
readonly environmentId: ScopedThreadRef["environmentId"] | null;
readonly gitCwd: string;
}
function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const queryClient = useQueryClient();
const navigate = useNavigate();
const sourceControlDiscovery = useSourceControlDiscovery();
const [publishProvider, setPublishProvider] = useState<PublishProviderKind>("github");
const [publishRepository, setPublishRepository] = useState("");
const [publishVisibility, setPublishVisibility] =
useState<SourceControlRepositoryVisibility>("private");
const [publishRemoteName, setPublishRemoteName] = useState("origin");
const [publishProtocol, setPublishProtocol] = useState<SourceControlCloneProtocol>("ssh");
const [publishWizardStep, setPublishWizardStep] = useState(0);
const [publishAdvancedOpen, setPublishAdvancedOpen] = useState(false);
const [publishError, setPublishError] = useState<string | null>(null);
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
null,
);
const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false);
const publishRepositoryMutation = useMutation(
sourceControlPublishRepositoryMutationOptions({
environmentId: props.environmentId,
cwd: props.gitCwd,
queryClient,
}),
);
const publishAccountByProvider = useMemo(() => {
const accounts: Record<PublishProviderKind, string | null> = {
github: null,
gitlab: null,
bitbucket: null,
"azure-devops": null,
};
for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
if (isPublishProviderKind(provider.kind)) {
accounts[provider.kind] = Option.getOrNull(provider.auth.account);
}
}
return accounts;
}, [sourceControlDiscovery.data]);
const publishProviderReadiness = useMemo(() => {
const sourceControlProviders = sourceControlDiscovery.data?.sourceControlProviders ?? [];
return Object.fromEntries(
PUBLISH_PROVIDER_OPTIONS.map((option) => [
option.value,
getPublishProviderReadiness({
provider: option.value,
sourceControlProviders,
}),
]),
) as Record<PublishProviderKind, { readonly ready: boolean; readonly hint: string | null }>;
}, [sourceControlDiscovery.data]);
const hasReadyPublishProvider = useMemo(
() => PUBLISH_PROVIDER_OPTIONS.some((option) => publishProviderReadiness[option.value].ready),
[publishProviderReadiness],
);
const sortedPublishProviderOptions = useMemo(
() =>
PUBLISH_PROVIDER_OPTIONS.toSorted((left, right) => {
const leftReady = publishProviderReadiness[left.value].ready;
const rightReady = publishProviderReadiness[right.value].ready;
if (leftReady !== rightReady) {
return leftReady ? -1 : 1;
}
return left.label.localeCompare(right.label);
}),
[publishProviderReadiness],
);
const selectedPublishProviderReadiness = publishProviderReadiness[publishProvider];
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
? `${publishAccountByProvider[publishProvider]}/`
: "";
const currentPublishProvider = publishProviderOption(publishProvider);
const publishHost = currentPublishProvider.host;
const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;
const publishProviderLabel = currentPublishProvider.label;
const publishWizardSteps = ["Provider", "Repository", "Summary"] as const;
const publishWizardStepSummaries = [
publishProviderLabel,
publishResult?.repository.nameWithOwner ?? null,
null,
] as const;
useEffect(() => {
if (!props.open || hasUserEditedPublishRepository) {
return;
}
setPublishRepository(publishRepositoryPrefill);
}, [hasUserEditedPublishRepository, props.open, publishRepositoryPrefill]);
const canSubmitPublishRepository = useMemo(() => {
if (!selectedPublishProviderReadiness.ready) return false;
if (publishRepositoryMutation.isPending) return false;
const repositoryParts = publishRepository.trim().split("/");
const owner = repositoryParts[0]?.trim() ?? "";
const rest = repositoryParts.slice(1);
const name = rest.join("/").trim();
return owner.length > 0 && name.length > 0;
}, [publishRepository, publishRepositoryMutation.isPending, selectedPublishProviderReadiness]);
useEffect(() => {
if (!props.open) {
return;
}
if (publishProviderReadiness[publishProvider].ready) {
return;
}
const firstReadyProvider = PUBLISH_PROVIDER_OPTIONS.find(
(option) => publishProviderReadiness[option.value].ready,
);
if (firstReadyProvider) {
setPublishProvider(firstReadyProvider.value);
}
}, [props.open, publishProvider, publishProviderReadiness]);
const submitPublishRepository = useCallback(() => {
if (!canSubmitPublishRepository) {
return;
}
setPublishError(null);
void publishRepositoryMutation
.mutateAsync({
provider: publishProvider,
repository: publishRepository.trim(),
visibility: publishVisibility,
remoteName: publishRemoteName.trim() || "origin",
protocol: publishProtocol,
})
.then((result) => {
flushSync(() => {
setPublishResult(result);
setPublishWizardStep(2);
});
void refreshGitStatus({ environmentId: props.environmentId, cwd: props.gitCwd }).catch(
() => undefined,
);
})
.catch((err: unknown) => {
setPublishError(err instanceof Error ? err.message : "An error occurred.");
});
}, [
canSubmitPublishRepository,
props.environmentId,
props.gitCwd,
publishProtocol,
publishProvider,
publishRemoteName,
publishRepository,
publishRepositoryMutation,
publishVisibility,
]);
const resetState = useCallback(() => {
setPublishRemoteName("origin");
setPublishRepository("");
setHasUserEditedPublishRepository(false);
setPublishWizardStep(0);
setPublishAdvancedOpen(false);
setPublishError(null);
setPublishResult(null);
}, []);
const handleOpenChange = useCallback(
(open: boolean) => {
props.onOpenChange(open);
if (!open) {
resetState();
}
},
[props, resetState],
);
const openSourceControlSettings = useCallback(() => {
handleOpenChange(false);
void navigate({ to: "/settings/source-control" });
}, [handleOpenChange, navigate]);
return (
<Dialog open={props.open} onOpenChange={handleOpenChange}>
<DialogPopup className="max-w-xl overflow-hidden">
<div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
<DialogHeader className="border-b border-border/70 bg-background">
<DialogTitle>Publish repository</DialogTitle>
<DialogDescription>
Pick where to host it, then point us at a repo to push to.
</DialogDescription>
<div className="grid grid-cols-3 gap-2">
{publishWizardSteps.map((label, index) => {
const isComplete = index < publishWizardStep;
const isClickable =
publishWizardStep !== 2 &&
index < publishWizardSteps.length - 1 &&
index <= publishWizardStep;
return (
<button
key={label}
type="button"
onClick={isClickable ? () => setPublishWizardStep(index) : undefined}
disabled={!isClickable}
className={cn(
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === publishWizardStep
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: isComplete
? "border-border bg-background"
: "border-border bg-muted/40",
!isClickable && "cursor-default",
)}
>
<span
aria-hidden
className={cn(
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
isComplete
? "border-primary bg-primary text-primary-foreground"
: index === publishWizardStep
? "border-primary bg-background"
: "border-muted-foreground/35 bg-background",
)}
>
{isComplete ? <CheckIcon className="size-3" /> : null}
</span>
<span className="text-[10px] font-medium uppercase text-muted-foreground">
Step {index + 1}
</span>
<span className="truncate text-xs font-semibold text-foreground">
{label}
{isComplete && publishWizardStepSummaries[index]
? `: ${publishWizardStepSummaries[index]}`
: ""}
</span>
</button>
);
})}
</div>
</DialogHeader>
<DialogPanel className="space-y-5 border-b border-border/70 bg-muted/20 px-6 py-5">
<AnimatedHeight>
<div className={cn("space-y-2", publishWizardStep !== 0 && "hidden")}>
<span
id="publish-provider-cards-label"
className="text-xs font-medium text-foreground"
>
Provider
</span>
<RadioGroup
value={publishProvider}
onValueChange={(value) => setPublishProvider(value as PublishProviderKind)}
aria-labelledby="publish-provider-cards-label"
className="grid grid-cols-2 gap-2.5"
>
{sortedPublishProviderOptions.map((option) => {
const readiness = publishProviderReadiness[option.value];
const isSelected = publishProvider === option.value && readiness.ready;
if (!readiness.ready) {
return (
<div
key={option.value}
className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55"
>
<option.Icon
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>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="xs"
className="h-5 rounded-[.25rem] px-1.5 text-[10px] text-warning-foreground"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
openSourceControlSettings();
}}
>
Setup Required
</Button>
}
/>
<TooltipPopup side="top" align="end" className="max-w-72">
{readiness.hint ??
"Open Settings -> Source Control to configure this provider."}
</TooltipPopup>
</Tooltip>
</div>
);
}
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",
)}
>
<option.Icon className="size-5 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<div className={cn("space-y-5", publishWizardStep !== 1 && "hidden")}>
<div className="space-y-2">
<label
htmlFor="publish-repository-path"
className="text-xs font-medium text-foreground"
>
Repository
</label>
<div className="flex items-stretch overflow-hidden rounded-md border border-input bg-background focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-ring">
<span className="flex shrink-0 items-center gap-1.5 border-r border-input bg-muted/50 px-2.5 font-mono text-xs text-muted-foreground">
<currentPublishProvider.Icon className="size-3.5" />
{publishHost}/
</span>
<input
id="publish-repository-path"
name="publish-repository-path"
value={publishRepository}
onChange={(event) => {
setPublishRepository(event.target.value);
setHasUserEditedPublishRepository(true);
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
submitPublishRepository();
}
}}
placeholder={publishPathPlaceholder}
disabled={publishRepositoryMutation.isPending}
className="w-full bg-transparent px-3 py-2 font-mono text-sm placeholder:text-muted-foreground/60 focus:outline-none"
/>
</div>
</div>
<div className="space-y-2">
<span
id="publish-visibility-cards-label"
className="text-xs font-medium text-foreground"
>
Visibility
</span>
<RadioGroup
value={publishVisibility}
onValueChange={(value) =>
setPublishVisibility(value as SourceControlRepositoryVisibility)
}
aria-labelledby="publish-visibility-cards-label"
disabled={publishRepositoryMutation.isPending}
className="grid grid-cols-2 gap-2.5"
>
{[
{
value: "private" as const,
label: "Private",
description: "Only invited people",
Icon: LockIcon,
},
{
value: "public" as const,
label: "Public",
description: "Anyone on the web",
Icon: GlobeIcon,
},
].map((option) => {
const isSelected = publishVisibility === option.value;
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-2.5 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",
)}
>
<option.Icon
className="size-4 shrink-0 text-muted-foreground"
aria-hidden
/>
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium text-foreground">
{option.label}
</span>
<span className="block text-xs text-muted-foreground">
{option.description}
</span>
</span>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<div>
<button
type="button"
onClick={() => setPublishAdvancedOpen((prev) => !prev)}
aria-expanded={publishAdvancedOpen}
className="flex items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
>
<ChevronDownIcon
className={cn(
"size-3.5 transition-transform",
publishAdvancedOpen ? "" : "-rotate-90",
)}
/>
Advanced
</button>
{publishAdvancedOpen ? (
<div className="mt-3 grid gap-3 sm:grid-cols-2">
<label className="space-y-1.5" htmlFor="publish-remote-name">
<span className="text-xs font-medium text-foreground">Remote</span>
<Input
id="publish-remote-name"
value={publishRemoteName}
onChange={(event) => setPublishRemoteName(event.target.value)}
placeholder="origin"
disabled={publishRepositoryMutation.isPending}
/>
</label>
<div className="space-y-1.5">
<span
id="publish-protocol-label"
className="text-xs font-medium text-foreground"
>
Protocol
</span>
<RadioGroup
value={publishProtocol}
onValueChange={(value) =>
setPublishProtocol(value as SourceControlCloneProtocol)
}
aria-labelledby="publish-protocol-label"
disabled={publishRepositoryMutation.isPending}
className="grid grid-cols-2 gap-2"
>
{(["ssh", "https"] as const).map((value) => {
const isSelected = publishProtocol === value;
return (
<RadioPrimitive.Root
key={value}
value={value}
className={cn(
"rounded-md border px-3 py-1.5 text-center text-sm font-medium outline-none transition",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background ring-2 ring-primary/35 text-foreground"
: "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground",
)}
>
{value === "ssh" ? "SSH" : "HTTPS"}
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
</div>
) : null}
</div>
{publishRepositoryMutation.isPending ? (
<div
role="status"
aria-live="polite"
className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground"
>
<Spinner className="size-3.5" aria-hidden />
Publishing repository to {publishProviderLabel}...
</div>
) : null}
{publishError && !publishRepositoryMutation.isPending ? (
<div
role="alert"
className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
>
<p className="font-medium">Publish failed</p>
<p className="mt-0.5 text-destructive/90">{publishError}</p>
</div>
) : null}
</div>
<div className={cn("space-y-4", publishWizardStep !== 2 && "hidden")}>
{publishResult ? (
<>
<div className="flex flex-col items-center gap-2 py-1 text-center">
<span className="grid size-8 place-items-center rounded-full bg-success/15 text-success">
<CheckIcon className="size-4" aria-hidden />
</span>
<h3 className="text-sm font-semibold text-foreground">
{publishResult.status === "pushed"
? "Repository published"
: "Repository created"}
</h3>
<p className="max-w-xs text-pretty text-xs text-muted-foreground">
{publishResult.status === "pushed"
? `${publishResult.branch} is now live on ${publishProviderLabel}.`
: `Remote "${publishResult.remoteName}" is set up. Make a commit and push it to share your code.`}
</p>
</div>
<div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2">
<currentPublishProvider.Icon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
{publishResult.repository.nameWithOwner}
</span>
</div>
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => {
const api = readLocalApi();
if (!api) return;
void api.shell.openExternal(publishResult.repository.url);
}}
>
<ExternalLinkIcon className="size-3.5" aria-hidden />
Open on {publishProviderLabel}
</Button>
</>
) : (
<div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground">
Publish result unavailable.
</div>
)}
</div>
</AnimatedHeight>
</DialogPanel>
<DialogFooter>
{publishWizardStep === 2 ? (
<Button size="sm" onClick={() => handleOpenChange(false)}>
Done
</Button>
) : (
<>
<Button
variant="outline"
size="sm"
disabled={publishRepositoryMutation.isPending}
onClick={() => {
if (publishWizardStep === 0) {
handleOpenChange(false);
return;
}
setPublishWizardStep((step) => Math.max(0, step - 1));
}}
>
{publishWizardStep === 0 ? "Cancel" : "Back"}
</Button>
{publishWizardStep < 1 ? (
<Button
size="sm"
disabled={!hasReadyPublishProvider || !selectedPublishProviderReadiness.ready}
onClick={() => setPublishWizardStep((step) => Math.min(1, step + 1))}
>
Next
</Button>
) : (
<Button
size="sm"
disabled={!canSubmitPublishRepository}
onClick={submitPublishRepository}
>
{publishRepositoryMutation.isPending ? (
<>
<Spinner className="size-3.5" aria-hidden />
Publishing...
</>
) : (
"Publish"
)}
</Button>
)}
</>
)}
</DialogFooter>
</div>
</DialogPopup>
</Dialog>
);
}
export default function GitActionsControl({
gitCwd,
activeThreadRef,
@@ -252,6 +974,7 @@ export default function GitActionsControl({
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
const [isEditingFiles, setIsEditingFiles] = useState(false);
const [isPublishDialogOpen, setIsPublishDialogOpen] = useState(false);
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
@@ -372,7 +1095,11 @@ export default function GitActionsControl({
}) > 0;
const isPullRunning =
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isPublishRunning =
useIsMutating({
mutationKey: gitMutationKeys.publishRepository(activeEnvironmentId, gitCwd),
}) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning || isPublishRunning;
const isSelectingWorktreeBase =
!activeServerThread &&
activeDraftThread?.envMode === "worktree" &&
@@ -785,6 +1512,10 @@ export default function GitActionsControl({
void openExistingPr();
return;
}
if (quickAction.kind === "open_publish") {
setIsPublishDialogOpen(true);
return;
}
if (quickAction.kind === "run_pull") {
const promise = pullMutation.mutateAsync();
void toastManager.promise<
@@ -882,6 +1613,8 @@ export default function GitActionsControl({
[gitCwd, threadToastData],
);
const canPublishRepository = isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
if (!gitCwd) return null;
return (
@@ -996,6 +1729,17 @@ export default function GitActionsControl({
</MenuItem>
);
})}
{canPublishRepository ? (
<MenuItem
disabled={isGitActionRunning}
onClick={() => {
setIsPublishDialogOpen(true);
}}
>
<CloudUploadIcon />
Publish repository...
</MenuItem>
) : null}
{gitStatusForActions?.refName === null && (
<p className="px-2 py-1.5 text-xs text-warning">
Detached HEAD: create and checkout a refName to enable push and pull request
@@ -1188,6 +1932,13 @@ export default function GitActionsControl({
</DialogPopup>
</Dialog>
<PublishRepositoryDialog
open={isPublishDialogOpen}
onOpenChange={setIsPublishDialogOpen}
environmentId={activeEnvironmentId}
gitCwd={gitCwd}
/>
<Dialog
open={pendingDefaultBranchAction !== null}
onOpenChange={(open) => {
+169 -20
View File
@@ -15,31 +15,180 @@ export const GitHubIcon: Icon = (props) => (
</svg>
);
export const GitLabIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
<path d="M22.6 9.3 20.9 4c-.2-.7-1.2-.7-1.5-.1l-2 5.4H6.6l-2-5.4c-.2-.6-1.2-.6-1.5.1L1.4 9.3c-.2.6 0 1.2.5 1.6L12 18.7l10.1-7.8c.5-.4.7-1 .5-1.6Z" />
<path d="m12 18.7 4.1-9.4H7.9L12 18.7Z" opacity=".72" />
<path d="M7.9 9.3H1.5L12 18.7 7.9 9.3ZM16.1 9.3 12 18.7l10.5-9.4h-6.4Z" opacity=".88" />
</svg>
);
export const AzureDevOpsIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
<path d="M21 5.2v12.7L16 22l-8-2.8V22l-4.9-6.4 4.9.4V4.8L16 2l5 3.2ZM16 6.4l-5 1.4v8.4l5 1.4V6.4Z" />
<path d="m8 8.4-5 .8v5.6l5 .8V8.4Z" opacity=".72" />
</svg>
);
export const BitbucketIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
<path d="M2.4 3.5c-.4 0-.7.3-.6.8L4.3 20c.1.4.4.7.8.7h13.7c.4 0 .7-.3.8-.7l2.6-15.7c.1-.5-.2-.8-.7-.8H2.4Zm12.5 11.1H9.4L8.5 8.7h7.4l-1 5.9Z" />
export const GitIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 256 256">
<path
d="M21 8.7h-5.1l-1 5.9H9.4l-4.2 5c.2.6.5 1.1 1.2 1.1h12.4c.4 0 .7-.3.8-.7L21 8.7Z"
opacity=".72"
d="M251.17 116.6 139.4 4.82a16.49 16.49 0 0 0-23.31 0l-23.21 23.2 29.44 29.45a19.57 19.57 0 0 1 24.8 24.96l28.37 28.38a19.61 19.61 0 1 1-11.75 11.06L137.28 95.4v69.64a19.62 19.62 0 1 1-16.13-.57V94.2a19.61 19.61 0 0 1-10.65-25.73L81.46 39.44 4.83 116.08a16.49 16.49 0 0 0 0 23.32L116.6 251.17a16.49 16.49 0 0 0 23.32 0l111.25-111.25a16.5 16.5 0 0 0 0-23.33"
fill="#DE4C36"
/>
</svg>
);
export const JujutsuIcon: Icon = (props) => {
const groupId = `${useId().replaceAll(":", "")}-jj-a`;
return (
<svg {...props} viewBox="0 0 1024 1024">
<defs>
<g id={groupId}>
<path
d="M380.7 632.3s-14.3 56-50.3 55.5c-12.1-.2-29-10.9-47.1-26.8-34.2 82.7-98.5 239-108.5 268.6-8.9 26.5 13 52 38.2 56 36.4 5.7 49-18.1 49-18.1s13.6 40.7 37.6 39.7c29.9-1.2 34.6-33 34.6-33s11.4 23.8 26.8 23.2c38.4-1.4 41.7-102.9 43.8-135.6 3.8-57.5 6.3-135.4 7.8-190.1-9 6.7-16.5 10.7-21.3 9.9-16.1-2.7-10.6-49.3-10.6-49.3z"
fill="#42acde"
/>
<path
d="M403.7 75.1c-89.7-.3-201.5 32.6-200.6 99.6 1.3 87.4 52.2 62.4 41.2 111.2-4.9 21.6-59.9 49.8-65.5 153.8 2.8.7 5.3 1 7.2 1.2 14.2.7 29.9-26.3 29.9-26.3s9.5 38 35 38 50.7-26.3 50.7-26.3 15 30.3 39.6 32c20 1.6 34-8 34-8s.8 15 14.6 14c13.9-1.2 37.6-27.8 37.6-27.8 16.5 30.3 31.9 21 54.7 5.1 0 0 6.2 26.6 36.8 23.7 6-.6 12.3-1 18.5-1.5l.9-11.6c2-58.8-20.4-129.8-50.4-183-21.7-38.7-52.5-83.4-49.6-107.3 3.5-28.3 46.7-28.4 46.7-28.4l-48.5-16 24-37a279.7 279.7 0 0 0-56.8-5.4Z"
fill="#2f9fdf"
/>
<path
d="M215.9 414.6s-15.7 27-30 26.3c-1.8-.1-4.3-.5-7-1.2l-.3 3c-2.3 52 7.7 100.3 29.7 132 35.1 50.7 92.6 112.6 122 113 36.1.6 50.4-55.4 50.4-55.4s-5.5 46.6 10.6 49.3c16 2.6 62.4-46.7 87.9-79.5 15.8-20.5 52-82.3 58.2-138.3-6.2.4-12.4 1-18.5 1.5-30.6 3-36.8-23.7-36.8-23.7-22.8 16-38.2 25.2-54.7-5 0 0-23.7 26.5-37.6 27.6-13.8 1.1-14.6-13.8-14.6-13.8s-14 9.5-34 8c-24.5-1.8-39.6-32.1-39.6-32.1s-25.2 26.3-50.7 26.3c-25.5 0-35-38-35-38z"
fill="#0e254f"
/>
<path
d="M309.5 418.5a1.5 1.5 0 0 0-.7 0c-.6.2-1.1.8-1.5 1.8a34.7 34.7 0 0 0 4 16.6c5.5 10.6 12.4 22 23.3 27.6 4 2 8.5 3.5 12.5 3.3a36 36 0 0 0 12.5-2.3c4-2 7.6-3.8 10.8-6.2 6-4.4 7.6-6.5 7.6-9.8 0-3.3-2.7-3.5-7.6-.5-5 3-14.6 6.1-18.8 6.1-11.2 0-21.2-8-33.1-26.4-4.3-6.6-7.1-9.9-9-10.2zm174 5c-1.2-.2-2.4.4-3.8 1.7-2.3 2.3-2.7 4-2.6 10.7.5 9 4.8 19.2 11.8 24.6 4.4 3.3 13.2 6 20.4 5.8 6.8-1.1 18.8-6.6 15.3-10.3-2-1.6-5 .7-9.9.7-10.6 0-15.3-3.4-19.6-9-3.8-5-5.4-8.7-7.2-16.8-1.1-4.6-2.6-7.1-4.4-7.4zm-67.5 2.2a1 1 0 0 0-.4 0c-.4.1-.7.4-1.2.9-2.4 2-2.5 5.1-.2 12.6a41.4 41.4 0 0 0 25.3 22c7.6 1.7 14.5.6 20.3-2.7 3.8-2.4 5.3-5 4.4-7.3-4.8-2.9-7.7-1-13.3-1A39.5 39.5 0 0 1 424 435c-4.8-5.9-7-9.3-8-9.4zm-199 .8c-1 .3-1.4 2.7-1 7.2.3 5.3 1.3 8.2 4 12 3 4.5 11.5 11 14.7 11.7 2.5 1 6.9 2.3 10.7 2.3 3.8 0 8-.6 11.2-1.3 3.2-.7 6.8-2 10.3-4l1.3-.7c4-2.1 8-5.1 10.9-7.9l1.4-1.2c6.3-5.4 9.9-10.7 9.9-14.6 0-2.4-5.3-.5-14 5-16 9.8-31.1 13.2-40.9 9l-2.2-1.3-8.8-7.7a32.9 32.9 0 0 1-3.6-4.8c-1.4-2.2-2.5-3.4-3.3-3.7a1 1 0 0 0-.5 0z"
fill="#71beea"
/>
<path
d="M221.6 468.8c-.5 0-.8.1-1.1.4-.3.2-.5.6-.6 1.2a10 10 0 0 0 .6 5.1 55 55 0 0 0 28.3 28.9 42.4 42.4 0 0 0 16.4 2c6.1-.2 12.3-1.4 16.6-3.4a48.3 48.3 0 0 0 13.7-10.6c.9-1 1.3-2 1.3-2.3 0-.6 0-.9-.3-1-.3-.3-.7-.4-1.6-.4-1.8 0-4.9.8-9.7 2.3-6.2 1.9-12.7 3-18.5 3.1-7.8.2-10.2-.4-17-3.7-4.5-2.2-12-7.7-17.7-12.8a232 232 0 0 0-7.2-6.3 63 63 0 0 0-2.4-2 12 12 0 0 0-.7-.4h-.1zm214.8 13.6c-.2 0-.5.7-.7 1.8v4a32 32 0 0 0 2.7 9.9 38.5 38.5 0 0 0 49.1 19.3c5.2-2.3 10-6.4 13-10.5 1.4-2.1 2.5-4.3 3-6.2.5-1.9.4-3.6-.3-4.9-.4-.8-.9-1.4-1.3-1.7-.3-.3-.6-.3-1-.2-.9.2-2.3 1.4-4.3 3.8-5 6.2-12.8 9.5-22.6 9.4-6.2 0-11-1.1-16-4.4-5-3.2-10.4-8.6-18-17.3-.8-1-1.7-2-2.5-2.4l-1-.6c-.1 0-.2 0 0 0zm-33.6 4.2-.6.2-1.4.7a53.5 53.5 0 0 0-4 2.5c-8 5.5-15.6 8.3-23.9 8.4-8.3 0-17.2-2.7-28-8.2a42 42 0 0 0-7.3-3c-2-.5-3.1-.5-3.6-.2-.2.1-.3.3-.4.6 0 .3 0 .8.2 1.5.4 1.3 1.4 3.1 3.1 5.5 4 5.4 10.5 10.1 19.7 14 9.3 3.9 23.8 3.5 32.4-1a42 42 0 0 0 9.1-6.5c2.6-2.6 4.5-6.5 5.3-9.6.5-1.5.6-3 .4-3.8 0-.4-.2-.7-.4-.9-.1-.2-.3-.2-.6-.2zm-132.5 30.8c-.3 0-.4 0-.5.2l-.1.5c0 .5.4 1.7 1.2 3.1a87.3 87.3 0 0 0 13.5 16.2c17 15.6 34.6 20.7 49 14.4a33.3 33.3 0 0 0 19-23c.4-2 .1-3.1-.2-3.5-.2-.2-.5-.3-1-.3l-1.7.5a24 24 0 0 0-5.7 4.6c-7.7 8-14.6 12-23 11.4-8.3-.4-18-5.2-31.7-14.3-5.2-3.4-9.4-6-12.5-7.6a15.5 15.5 0 0 0-6.3-2.2zm109.4 0c-.2 0-.3 0-.5.2-.1 0-.3.3-.4.7a9 9 0 0 0 0 3.3c.4 2.9 1.6 6.7 3.5 10.3 11 20.5 29.4 30.5 46.8 25.7a37.3 37.3 0 0 0 15.6-10c4.4-4.6 7.4-9.9 7.4-13.8 0-1.3-.1-2.3-.4-2.7 0-.3-.2-.4-.3-.4h-.5c-.6 0-1.5.4-2.7 1.2a57 57 0 0 0-4.7 3.7c-9 7.7-16.9 11.2-25.1 10-8.2-1.3-16.7-7.1-27-17.7a159.8 159.8 0 0 0-10.6-9.8 9.8 9.8 0 0 0-.9-.6l-.2-.1zm-140.2 43.5c-1 0-1.6.2-1.8.5-.2.4-.3 1 0 2.1.8 2.2 3.1 5.6 7.1 9.6a78.2 78.2 0 0 0 27.4 17.9c9.7 3.8 16.7 4.1 23.4 1.1 5.5-2.5 8.4-6.1 8.4-10.4a4 4 0 0 0-.4-2c-.3-.4-.6-.6-1-.7-.9-.1-2.5.4-4.6 1.8-2.7 2-6.4 2.3-11.3 1.2-5-1.2-11.3-3.8-19.5-8-8-4-17.5-9-21.3-11-2.9-1.4-5-2-6.4-2.1zm160.1 2.8c-.6-.1-1.7.2-3.1 1-1.4 1-3.2 2.3-5.2 4.1a58 58 0 0 1-12.7 8.7c-5.9 2.7-8.6 3.2-18.3 3.2-12.6 0-17.2-1.6-29.9-11.2a21 21 0 0 0-6.4-3.8c-.5 0-.5 0-.7.2-.2.3-.3 1-.3 2 0 2.2 1.5 5.7 3.8 9.2 2.4 3.4 5.7 7 9.2 9.5 8.1 6 14.3 7.8 26.2 7.4a34 34 0 0 0 18.3-4.1 51 51 0 0 0 13.1-9.8c3.8-3.8 6.5-8 7-10.7.4-2 .4-3.5.2-4.5a2 2 0 0 0-.5-1 1 1 0 0 0-.7-.2zm-2 21.4c-.5 0-.6 0-.8.4-.2.4-.3 1.2-.3 2.4 0 3.2 1.7 7.3 4.4 11 2.7 4 6.3 7.4 10 9.5a35 35 0 0 0 21.3 4.8c11-.9 17.8-3.4 23.8-12.6 1.5-2.5 2-4.8 1.4-6.7-.2-.7-.4-1.1-.8-1.4-.3-.2-.6-.3-1.2-.3-1 0-2.6.7-4.7 2.1-6 4.3-12 6.1-19.9 6.2-8.8 0-16.3-3-26.2-11-3.6-2.8-6-4.3-7-4.4zM290 605.5c-.6.3-.9.5-1 1a9 9 0 0 0 .1 3.3c1.8 11 13 25 24.4 30.2 8.5 4 20 4 28.5 0 7.7-3.5 16-11.1 19-17.3a25 25 0 0 0 2.2-6.3c.1-.7.1-1.3 0-1.6 0-.4-.2-.6-.4-.7-.3-.2-1.3-.2-2.8.5-1.6.7-3.6 2-6 4-10 8.2-18.6 12.1-27 11.4-8.6-.7-16.9-6-26.4-15.9a82.6 82.6 0 0 0-7.6-7.1 10 10 0 0 0-2-1.4c-.5-.2-.8-.2-1-.1z"
fill="#309fdf"
/>
<path
d="M290 125.7a61.4 61.4 0 0 0-19 2.3c-19.9 5.7-33.5 15.8-36.5 52.2-3 36.6-18 45.5-20.3 46.7 14.7 26.7 38 24.5 30.1 59-2.4 11-17.6 23.5-32.8 46.5 34-27 56.4-48 99.6-100.5 0 0 39-47.6 25.1-77a52 52 0 0 0-46.1-29.2z"
fill="#e9f2f1"
/>
<path
d="M288.5 120.8c-8.1 0-16.7 1.4-25.6 5.3-22.5 9.9-25 20.3-29.1 37a96.8 96.8 0 0 0-1.4 24.6 178 178 0 0 0-16.5-31.6s-19 19.8-36.5 18.6c-22.9-1.7-34 2-44.8 9.8-25.4 18.5-21.2 43.8-21.2 43.8s17.6-1.8 40.5 1c20.3 2.7 37.4 4.3 61.3 2.6 8.5-.6 15.8-10 19.3-19 4.5-4 2.9-22 4.8-24.5 3-3.4 8-4.7 10.6-5.2 3.7-.7 4.3 1.5 4.7 2.8a31 31 0 0 0 60.5-3.2c1-4.4 9-5 15.9-4.5 7 0 .9 15.9-1.7 22.3-5.4 13.2-24.9 39-24.9 39l124.3-85s-45.8 22-61.5 20c-19.7-2.3-25.7-34.8-43.2-44-9.9-5.1-22-9.6-35.5-9.8zm1.4 9.4a48.2 48.2 0 0 1 40.6 23.5c3.7 7.1 6.2 17-.3 20.2-7.6 3.7-14.7.7-15.5-2.8a31 31 0 0 0-30.2-24.1 30 30 0 0 0-30.8 27.4c-.4 5.2-9.1 7.7-12.7 3.7-2.7-3 1.7-16.8 3.7-22 6.2-16.2 27.8-25.7 45.2-26zm5.6 27.8a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11zm-22 29a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11zm40 523.4c-2.6-1.8-15.1 23.5-20 59-6.8 49-8.3 63.2-14.2 96-6 32.7-12.6 66.3-13.4 73.7-.6 4.8-1.7 19-.6 20.1 3.2 3.3 14.7-31.7 16.8-42 2-10.3 7.7-40.7 14.2-86.9 6.4-46.1 8.5-69.6 13.1-91.5 4.7-22 6.7-26.6 4.2-28.4zm66.3-27c-4.1-1.3-10.5 24.6-13.1 37.8-5.6 28.6-6.2 64-8.4 87a1099 1099 0 0 1-12 87.4c-2.7 15-8 29.4-9.8 44.6-1 9-5.2 26-.2 27.3 5.2 1.5 15.4-36.5 20-55.7 8.1-32.9 10.7-65.6 14.2-99.3 3.3-30.7 4.6-62.8 6.5-93.6.7-18.5 5.1-34.5 2.8-35.6z"
fill="#0e254f"
/>
</g>
</defs>
<rect width="1024" height="1024" rx="270" fill="#a7bcd9" />
<use href={`#${groupId}`} transform="matrix(-1 0 0 1 1024 0)" />
<use href={`#${groupId}`} />
</svg>
);
};
export const GitLabIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 32 32" fill="none">
<path
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
fill="#E24329"
/>
<path
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
fill="#FC6D26"
/>
<path
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
fill="#FCA326"
/>
<path
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
fill="#FC6D26"
/>
</svg>
);
export const AzureDevOpsIcon: Icon = (props) => {
const id = useId().replaceAll(":", "");
const gradientA = `${id}-azure-a`;
const gradientB = `${id}-azure-b`;
const gradientC = `${id}-azure-c`;
return (
<svg {...props} viewBox="0 0 96 96">
<defs>
<linearGradient
id={gradientA}
x1="-1032.17"
x2="-1059.21"
y1="145.31"
y2="65.43"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopColor="#114a8b" />
<stop offset="1" stopColor="#0669bc" />
</linearGradient>
<linearGradient
id={gradientB}
x1="-1023.73"
x2="-1029.98"
y1="108.08"
y2="105.97"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopOpacity=".3" />
<stop offset=".07" stopOpacity=".2" />
<stop offset=".32" stopOpacity=".1" />
<stop offset=".62" stopOpacity=".05" />
<stop offset="1" stopOpacity="0" />
</linearGradient>
<linearGradient
id={gradientC}
x1="-1027.16"
x2="-997.48"
y1="147.64"
y2="68.56"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopColor="#3ccbf4" />
<stop offset="1" stopColor="#2892df" />
</linearGradient>
</defs>
<path
fill={`url(#${gradientA})`}
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
/>
<path
fill="#0078d4"
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
/>
<path
fill={`url(#${gradientB})`}
d="M33.34 6.54a4.12 4.12 0 0 0-3.95 2.88L4.25 83.92a4.14 4.14 0 0 0 3.91 5.54h20.79a4.44 4.44 0 0 0 3.4-2.9l5.02-14.78 17.91 16.7a4.24 4.24 0 0 0 2.67.97h23.29L71.02 60.26H41.24L59.47 6.55z"
/>
<path
fill={`url(#${gradientC})`}
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
/>
</svg>
);
};
export const BitbucketIcon: Icon = (props) => {
const id = useId().replaceAll(":", "");
const gradientId = `${id}-bitbucket-a`;
return (
<svg {...props} viewBox="8.4 14.39 2481.29 2231.21">
<path fill="none" d="M989.97,1493.09h518.05l125.04-730.04H852.22L989.97,1493.09z" />
<path
fill="#2684FF"
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
/>
<linearGradient
id={gradientId}
gradientUnits="userSpaceOnUse"
x1="945.1094"
y1="1524.8389"
x2="944.4923"
y2="1524.1893"
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
>
<stop offset="0.18" stopColor="#0052CC" />
<stop offset="1" stopColor="#2684FF" />
</linearGradient>
<path
fill={`url(#${gradientId})`}
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
/>
</svg>
);
};
export const CursorIcon: Icon = ({ className, ...props }) => (
<svg
{...props}
@@ -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;
+402 -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,26 @@ export const ChatComposer = memo(
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const isMobileViewport = useMediaQuery("max-sm");
const mobileCollapsedOnlyClassName =
"sm:hidden max-sm:group-focus-within/composer:hidden max-sm:group-data-[mobile-focus-primed=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";
const mobileExpandedFlexOnlyClassName =
"max-sm:hidden max-sm:group-focus-within/composer:flex max-sm:group-data-[mobile-focus-primed=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 +949,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 +1042,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 +1575,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 +1668,7 @@ export const ChatComposer = memo(
}
}
if (key === "Enter" && !event.shiftKey) {
void onSend();
submitComposer();
return true;
}
return false;
@@ -1690,6 +1778,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 +1898,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 +1913,34 @@ export const ChatComposer = memo(
onDrop={onComposerDrop}
>
<div
ref={composerSurfaceRef}
data-mobile-focus-primed="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 +1951,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 +1964,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 +2127,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 +2286,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">
@@ -2080,8 +2375,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);
});
});
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more