Compare commits

..
Author SHA1 Message Date
Julius Marminge a251619fe0 Fix JJ rebase drift 2026-05-02 19:03:07 -07:00
Julius Marminge 0cdc89ccaf Align JJ driver with VCS provisioning 2026-05-02 19:03:07 -07:00
Julius Marminge 78c1342e98 Enable Jujutsu source control discovery 2026-05-02 19:03:07 -07:00
Julius Marminge fd90d2e79d Fix JJ branch CI test drift 2026-05-02 19:03:07 -07:00
Julius Marminge d3549003b5 Install jj in CI 2026-05-02 19:03:07 -07:00
Julius Marminge 9984fa140a Add typed jj extension surface 2026-05-02 19:03:07 -07:00
Julius Marminge 824278abfb Prefer jj detection and add ignore classifier capability
- Detect jj before git for colocated repositories
- Add ignoreClassifier to VCS capabilities
- Fix trace2 hook exit code reporting
2026-05-02 19:03:07 -07:00
Julius Marminge daf4b72617 Use effect file system and node services in VCS tests
- Replace ad hoc temp-dir handling with scoped FileSystem APIs
- Provide NodeServices in VCS driver and status broadcaster tests
- Normalize CWDs through FileSystem realpath
2026-05-02 19:03:07 -07:00
Julius Marminge 1a5be6cc2b Add JJ VCS driver support
- Detect and route jj repositories alongside git
- Thread VCS kind through status and UI labels
- Add jj driver contract coverage and shared freshness helper
2026-05-02 19:03:07 -07:00
188 changed files with 2464 additions and 16850 deletions

No files matched your search

-80
View File
@@ -93,8 +93,6 @@ Examples:
A known environment may or may not know the target `environmentId` before first successful connect.
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
### AccessEndpoint
An `AccessEndpoint` is one concrete way to reach a known environment.
@@ -110,67 +108,6 @@ A single environment may have many endpoints:
The environment stays the same. Only the access path changes.
### AdvertisedEndpoint
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
`AdvertisedEndpoint` is deliberately narrower than the full access model:
- it describes a concrete HTTP and WebSocket base URL pair
- it can mark the endpoint as default, available, or unavailable
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
When no user default is saved, endpoint selection should prefer:
1. endpoints compatible with the hosted HTTPS app
2. explicitly default endpoints
3. non-loopback endpoints
4. loopback endpoints only for same-machine clients
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
### Endpoint providers
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
The provider boundary is intentionally outside the core environment model:
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
- providers discover or synthesize endpoints
- providers return normalized `AdvertisedEndpoint` records
- the UI and pairing logic select from those records without knowing provider-specific commands
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
### Hosted pairing request
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
Example:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
Important constraints:
- the hosted app does not proxy HTTP or WebSocket traffic
- the backend must still be reachable directly from the browser
- HTTPS pages can only connect to HTTPS/WSS backends
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
- the token belongs in the URL hash so it is not sent to the hosted app origin
### RepositoryIdentity
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
@@ -214,8 +151,6 @@ Benefits:
- no client-specific process management required
- best fit for hosted or self-managed remote T3 deployments
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
### 2. Tunneled WebSocket access
Examples:
@@ -235,8 +170,6 @@ This is especially useful when:
- mobile must reach a desktop-hosted environment
- a machine should be reachable without exposing raw LAN or public ports
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
### 3. Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type.
@@ -252,8 +185,6 @@ After that, the renderer should still connect using an ordinary WebSocket URL ag
This keeps the renderer transport model consistent with every other access method.
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
## Launch methods
Launch methods answer a different question:
@@ -296,15 +227,6 @@ The recommended T3 flow is:
4. Desktop establishes local port forwarding.
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
Failure handling should be explicit:
- SSH authentication failure should surface before any environment is saved
- remote launch failure should include remote logs or the launcher command output when available
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
### 3. Client-managed local publish
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
@@ -345,8 +267,6 @@ T3 already supports a WebSocket auth token on the server. That should become a f
For publicly reachable environments, authenticated access should be treated as required.
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
## Relationship to Zed
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
+49
View File
@@ -0,0 +1,49 @@
name: Setup Jujutsu
description: Install the jj CLI from the official jj-vcs release artifacts.
inputs:
version:
description: Jujutsu release tag to install.
required: false
default: v0.40.0
runs:
using: composite
steps:
- name: Install jj
shell: bash
env:
JJ_VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
case "${RUNNER_OS}-${RUNNER_ARCH}" in
Linux-X64)
asset="jj-${JJ_VERSION}-x86_64-unknown-linux-musl.tar.gz"
;;
Linux-ARM64)
asset="jj-${JJ_VERSION}-aarch64-unknown-linux-musl.tar.gz"
;;
macOS-X64)
asset="jj-${JJ_VERSION}-x86_64-apple-darwin.tar.gz"
;;
macOS-ARM64)
asset="jj-${JJ_VERSION}-aarch64-apple-darwin.tar.gz"
;;
*)
echo "Unsupported runner for jj install: ${RUNNER_OS}-${RUNNER_ARCH}" >&2
exit 1
;;
esac
install_dir="${RUNNER_TEMP}/jj-${JJ_VERSION}"
mkdir -p "$install_dir"
curl -fsSL \
"https://github.com/jj-vcs/jj/releases/download/${JJ_VERSION}/${asset}" \
-o "${RUNNER_TEMP}/${asset}"
tar -xzf "${RUNNER_TEMP}/${asset}" -C "$install_dir"
chmod +x "${install_dir}/jj"
echo "$install_dir" >> "$GITHUB_PATH"
"${install_dir}/jj" --version
+3
View File
@@ -25,6 +25,9 @@ jobs:
with:
node-version-file: package.json
- name: Setup Jujutsu
uses: ./.github/actions/setup-jj
- name: Cache Bun and Turbo
uses: actions/cache@v5
with:
+3
View File
@@ -95,6 +95,9 @@ jobs:
with:
node-version-file: package.json
- name: Setup Jujutsu
uses: ./.github/actions/setup-jj
- name: Install dependencies
run: bun install --frozen-lockfile
-1
View File
@@ -22,4 +22,3 @@ apps/web/src/components/__screenshots__
__screenshots__/
.tanstack
squashfs-root/
.vercel
-350
View File
@@ -1,350 +0,0 @@
# Remote Endpoints and Hosted Static App Plan
## Purpose
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
```ts
type AdvertisedEndpointProvider =
| "loopback"
| "lan"
| "tailscale-ip"
| "tailscale-magicdns"
| "manual"
| "t3-tunnel";
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
type AdvertisedEndpointCompatibility = {
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
desktopApp: "compatible" | "unknown";
};
type AdvertisedEndpoint = {
id: string;
provider: AdvertisedEndpointProvider;
label: string;
httpBaseUrl: string;
wsBaseUrl: string;
visibility: AdvertisedEndpointVisibility;
compatibility: AdvertisedEndpointCompatibility;
source: "server" | "desktop" | "user";
status: "available" | "unavailable" | "unknown";
isDefault?: boolean;
};
```
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
## HTTP/WS and HTTPS/WSS Readiness
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
What is ready:
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
- Saved environments store both HTTP and WebSocket base URLs.
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
- WebSocket connections can use a dynamically issued `wsToken`.
- Server CORS support exists for browser remote auth endpoints.
What is not solved by code alone:
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
Policy:
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
- Mark endpoint compatibility at the product layer.
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
## Architecture
### Endpoint Sources
Endpoint records can come from several providers:
1. **Server runtime**
- headless bind host and port
- server-known explicit advertised host config
2. **Desktop shell**
- loopback backend URL
- LAN exposure state
- network interface discovery
- Tailscale CLI/status discovery
3. **User configuration**
- manually added hostnames
- preferred endpoint labels
- hidden/disabled endpoints
4. **Future cloud provider**
- T3 Tunnel endpoint
- billing/account status
- tunnel lifecycle state
### Endpoint Registry
Create a central runtime registry:
- `packages/contracts/src/remoteAccess.ts`
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
- `apps/server/src/remoteAccess/*` for server/headless endpoints
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
### Pairing Link Generation
Move hosted pairing link generation to endpoint-driven input:
```ts
buildHostedPairingUrl({
endpoint: AdvertisedEndpoint,
token,
});
```
Generated URL:
```text
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
```
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
## Phase 1: Endpoint Abstraction
### Goals
- Centralize URL normalization, protocol derivation, and compatibility checks.
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
- Preserve all current remote behavior.
### Tasks
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
2. Add shared helpers:
- normalize HTTP base URL
- derive WebSocket base URL
- classify loopback/private/LAN/Tailscale/public host
- classify hosted HTTPS compatibility
3. Add server endpoint discovery:
- loopback endpoint
- configured non-loopback endpoint
- explicit advertised host override
4. Add desktop endpoint discovery:
- local loopback
- LAN exposure endpoint
- endpoint status labels
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
- `app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
+1 -76
View File
@@ -22,41 +22,9 @@ If you are already running the desktop app and want to make it reachable from ot
1. Open **Settings** → **Connections**.
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
4. Use **Create Link** to generate a pairing link you can share with another device.
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
available. You can set another endpoint as the default from the expanded endpoint list.
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
automatically.
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
### Tailscale Endpoints
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
Depending on your Tailscale setup, this may include:
- the machine's `100.x.y.z` Tailnet IP
- a MagicDNS name
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
Serve to proxy HTTPS traffic to the local backend.
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
@@ -79,42 +47,14 @@ From there, connect from another device in either of these ways:
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
```bash
npx t3 serve --tailscale-serve
```
By default this configures Tailscale Serve on HTTPS port 443 and advertises
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
```bash
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
```
> Note
> The GUIs do not currently support adding projects on remote environments.
> For now, use `t3 project ...` on the server machine instead.
> Full GUI support for remote project management is coming soon.
### Option 3: Desktop-Managed SSH Launch
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
1. Open **Settings** → **Connections**.
2. Under **Remote Environments**, choose **Add environment**.
3. Select the SSH launch flow.
4. Enter the SSH target, such as `[email protected]`.
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
## How Pairing Works
The remote device does not need a long-lived secret up front.
@@ -127,20 +67,6 @@ Instead:
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
## Hosted Web App Pairing
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
@@ -158,5 +84,4 @@ Use `t3 auth --help` and the nested subcommand help pages for the full reference
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
-4
View File
@@ -15,17 +15,13 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
"electron": "40.9.3",
"electron-updater": "^6.6.2"
},
"devDependencies": {
"@t3tools/client-runtime": "workspace:*",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"tsdown": "catalog:",
@@ -52,7 +52,6 @@ const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
@@ -72,12 +71,6 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
describe("clientPersistence", () => {
+3 -12
View File
@@ -57,12 +57,6 @@ function isPersistedSavedEnvironmentStorageRecord(
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.desktopSsh === undefined ||
(Predicate.isObject(value.desktopSsh) &&
typeof value.desktopSsh.alias === "string" &&
typeof value.desktopSsh.hostname === "string" &&
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
@@ -83,7 +77,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
const nextRecord = {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -91,7 +85,6 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
@@ -141,7 +134,6 @@ export function writeSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
encryptedBearerToken,
}
: record;
@@ -197,7 +189,7 @@ export function writeSavedEnvironmentSecret(input: {
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
const nextRecord = {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -205,8 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
} satisfies PersistedSavedEnvironmentStorageRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
-83
View File
@@ -9,7 +9,6 @@ import {
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -36,8 +35,6 @@ describe("desktopSettings", () => {
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -48,16 +45,12 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
@@ -68,8 +61,6 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -77,50 +68,6 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested Tailscale Serve preference", () => {
expect(
setDesktopTailscaleServePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
{ enabled: true, port: 8443 },
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("preserves the configured Tailscale Serve port when no new port is requested", () => {
expect(
setDesktopTailscaleServePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
{ enabled: true },
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
@@ -131,8 +78,6 @@ describe("desktopSettings", () => {
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -140,8 +85,6 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
@@ -160,8 +103,6 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -180,8 +121,6 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -201,30 +140,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
tailscaleServeEnabled: true,
tailscaleServePort: 0,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
});
-33
View File
@@ -6,18 +6,12 @@ import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
@@ -41,29 +35,6 @@ export function setDesktopServerExposurePreference(
};
}
export function setDesktopTailscaleServePreference(
settings: DesktopSettings,
input: { readonly enabled: boolean; readonly port?: number },
): DesktopSettings {
const port =
input.port === undefined
? settings.tailscaleServePort
: normalizeTailscaleServePort(input.port);
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
? settings
: {
...settings,
tailscaleServeEnabled: input.enabled,
tailscaleServePort: port,
};
}
export function normalizeTailscaleServePort(value: unknown): number {
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
? value
: DEFAULT_TAILSCALE_SERVE_PORT;
}
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
@@ -86,8 +57,6 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly tailscaleServeEnabled?: unknown;
readonly tailscaleServePort?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
@@ -103,8 +72,6 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
+5 -128
View File
@@ -36,14 +36,11 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
import {
type DesktopSettings,
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -58,11 +55,7 @@ import {
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
} from "./serverExposure.ts";
import { DesktopSshEnvironmentBridge, resolveRemoteT3CliPackageSpec } from "./sshEnvironment.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
@@ -83,7 +76,6 @@ import {
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
syncShellEnvironment();
@@ -110,8 +102,6 @@ const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secr
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
@@ -120,11 +110,6 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
// Dev-only SSH launcher override. Set this to an absolute path on the SSH host
// for a built server entry, for example:
// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"
const DEV_REMOTE_T3_SERVER_ENTRY_PATH =
process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ?? "";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
@@ -312,9 +297,6 @@ function backendChildEnv(): NodeJS.ProcessEnv {
delete env.T3CODE_DESKTOP_WS_URL;
delete env.T3CODE_DESKTOP_LAN_ACCESS;
delete env.T3CODE_DESKTOP_LAN_HOST;
delete env.T3CODE_DESKTOP_HTTPS_ENDPOINTS;
delete env.T3CODE_TAILSCALE_SERVE;
delete env.T3CODE_TAILSCALE_SERVE_PORT;
return env;
}
@@ -323,32 +305,9 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
mode: desktopServerExposureMode,
endpointUrl: backendEndpointUrl,
advertisedHost: backendAdvertisedHost,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
};
}
async function getDesktopAdvertisedEndpoints() {
const exposure = resolveDesktopServerExposure({
mode: desktopServerExposureMode,
port: backendPort,
networkInterfaces: OS.networkInterfaces(),
...(backendAdvertisedHost ? { advertisedHostOverride: backendAdvertisedHost } : {}),
});
const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
port: backendPort,
exposure,
customHttpsEndpointUrls: resolveCustomHttpsEndpointUrls(),
});
const tailscaleEndpoints = await resolveTailscaleAdvertisedEndpoints({
port: backendPort,
serveEnabled: desktopSettings.tailscaleServeEnabled,
servePort: desktopSettings.tailscaleServePort,
networkInterfaces: OS.networkInterfaces(),
});
return [...coreEndpoints, ...tailscaleEndpoints];
}
function getDesktopSecretStorage() {
return {
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
@@ -362,19 +321,9 @@ function resolveAdvertisedHostOverride(): string | undefined {
return override && override.length > 0 ? override : undefined;
}
function resolveCustomHttpsEndpointUrls(): readonly string[] {
return (process.env.T3CODE_DESKTOP_HTTPS_ENDPOINTS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
}
async function applyDesktopServerExposureMode(
mode: DesktopServerExposureMode,
options?: {
readonly persist?: boolean;
readonly rejectIfUnavailable?: boolean;
},
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
): Promise<DesktopServerExposureState> {
const advertisedHostOverride = resolveAdvertisedHostOverride();
const requestedMode = mode;
@@ -412,17 +361,6 @@ async function applyDesktopServerExposureMode(
return getDesktopServerExposureState();
}
async function applyDesktopTailscaleServeEnabled(
nextSettings: DesktopSettings,
): Promise<DesktopServerExposureState> {
desktopSettings = nextSettings;
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
relaunchDesktopApp(
desktopSettings.tailscaleServeEnabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled",
);
return getDesktopServerExposureState();
}
function relaunchDesktopApp(reason: string): void {
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
setImmediate(() => {
@@ -435,7 +373,6 @@ function relaunchDesktopApp(reason: string): void {
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
);
})
.then(() => desktopSshEnvironmentBridge.dispose().catch(() => undefined))
.finally(() => {
restoreStdIoCapture?.();
if (isDevelopment) {
@@ -692,22 +629,6 @@ let updateInstallInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
const desktopSshEnvironmentBridge = new DesktopSshEnvironmentBridge({
getMainWindow: () => mainWindow,
resolveCliRunner: (): RemoteT3RunnerOptions => {
if (isDevelopment && DEV_REMOTE_T3_SERVER_ENTRY_PATH.length > 0) {
return { nodeScriptPath: DEV_REMOTE_T3_SERVER_ENTRY_PATH };
}
return {
packageSpec: resolveRemoteT3CliPackageSpec({
appVersion: app.getVersion(),
updateChannel: desktopSettings.updateChannel,
isDevelopment,
}),
};
},
});
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateInstallInFlight) return "install";
if (updateDownloadInFlight) return "download";
@@ -1259,10 +1180,7 @@ async function checkForUpdates(reason: string): Promise<boolean> {
}
}
async function downloadAvailableUpdate(): Promise<{
accepted: boolean;
completed: boolean;
}> {
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
return { accepted: false, completed: false };
}
@@ -1284,10 +1202,7 @@ async function downloadAvailableUpdate(): Promise<{
}
}
async function installDownloadedUpdate(): Promise<{
accepted: boolean;
completed: boolean;
}> {
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
return { accepted: false, completed: false };
}
@@ -1487,8 +1402,6 @@ function startBackend(): void {
t3Home: BASE_DIR,
host: backendBindHost,
desktopBootstrapToken: backendBootstrapToken,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
@@ -1734,8 +1647,6 @@ function registerIpcHandlers(): void {
},
);
desktopSshEnvironmentBridge.registerIpcHandlers(ipcMain);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
@@ -1758,31 +1669,6 @@ function registerIpcHandlers(): void {
return nextState;
});
ipcMain.removeHandler(SET_TAILSCALE_SERVE_ENABLED_CHANNEL);
ipcMain.handle(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, async (_event, rawInput: unknown) => {
if (typeof rawInput !== "object" || rawInput === null) {
throw new Error("Invalid Tailscale Serve input.");
}
const input = rawInput as {
readonly enabled?: unknown;
readonly port?: unknown;
};
if (typeof input.enabled !== "boolean") {
throw new Error("Invalid Tailscale Serve input.");
}
const nextSettings = setDesktopTailscaleServePreference(desktopSettings, {
enabled: input.enabled,
...(typeof input.port === "number" ? { port: input.port } : {}),
});
if (nextSettings === desktopSettings) {
return getDesktopServerExposureState();
}
return applyDesktopTailscaleServeEnabled(nextSettings);
});
ipcMain.removeHandler(GET_ADVERTISED_ENDPOINTS_CHANNEL);
ipcMain.handle(GET_ADVERTISED_ENDPOINTS_CHANNEL, async () => getDesktopAdvertisedEndpoints());
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -2073,10 +1959,7 @@ function createWindow(): BrowserWindow {
const externalUrl = getSafeExternalUrl(params.linkURL);
if (externalUrl) {
menuTemplate.push(
{
label: "Copy Link",
click: () => clipboard.writeText(params.linkURL),
},
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
{ type: "separator" },
);
}
@@ -2136,9 +2019,6 @@ function createWindow(): BrowserWindow {
}
window.on("closed", () => {
desktopSshEnvironmentBridge.cancelPendingPasswordPrompts(
"SSH authentication was cancelled because the app window closed.",
);
if (mainWindow === window) {
mainWindow = null;
}
@@ -2230,7 +2110,6 @@ app.on("before-quit", () => {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
});
@@ -2280,7 +2159,6 @@ if (process.platform !== "win32") {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
@@ -2291,7 +2169,6 @@ if (process.platform !== "win32") {
writeDesktopLogHeader("SIGTERM received");
clearUpdatePollTimer();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
-59
View File
@@ -22,36 +22,8 @@ const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-re
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
function unwrapEnsureSshEnvironmentResult(result: unknown) {
if (
typeof result === "object" &&
result !== null &&
"type" in result &&
result.type === SSH_PASSWORD_PROMPT_CANCELLED_RESULT
) {
const message =
"message" in result && typeof result.message === "string"
? result.message
: "SSH authentication cancelled.";
throw new Error(message);
}
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
}
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
@@ -79,39 +51,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
ensureSshEnvironment: async (target, options) =>
unwrapEnsureSshEnvironmentResult(
await ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
onSshPasswordPrompt: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
if (typeof request !== "object" || request === null) return;
listener(request as Parameters<typeof listener>[0]);
};
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
};
},
resolveSshPasswordPrompt: (requestId, password) =>
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
setTailscaleServeEnabled: (input) =>
ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
+1 -120
View File
@@ -1,10 +1,6 @@
import { describe, expect, it } from "vitest";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
resolveLanAdvertisedHost,
} from "./serverExposure.ts";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -78,121 +74,6 @@ describe("resolveLanAdvertisedHost", () => {
});
});
describe("resolveDesktopCoreAdvertisedEndpoints", () => {
it("advertises loopback and LAN endpoints without provider-specific assumptions", () => {
const exposure = resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
});
expect(
resolveDesktopCoreAdvertisedEndpoints({
port: 3773,
exposure,
customHttpsEndpointUrls: [
"https://desktop.example.ts.net",
"http://desktop.example.test:3773",
"not-a-url",
],
}),
).toEqual([
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
description: "Loopback endpoint for this desktop app.",
},
{
id: "desktop-lan:http://192.168.1.44:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://192.168.1.44:3773/",
wsBaseUrl: "ws://192.168.1.44:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
},
{
id: "manual:https://desktop.example.ts.net",
label: "Custom HTTPS",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "https://desktop.example.ts.net/",
wsBaseUrl: "wss://desktop.example.ts.net/",
reachability: "public",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
},
{
id: "manual:http://desktop.example.test:3773",
label: "Custom endpoint",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://desktop.example.test:3773/",
wsBaseUrl: "ws://desktop.example.test:3773/",
reachability: "public",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured endpoint for this desktop backend.",
},
]);
});
});
describe("resolveDesktopServerExposure", () => {
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
expect(
+1 -109
View File
@@ -1,13 +1,5 @@
import type { NetworkInterfaceInfo } from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
} from "@t3tools/contracts";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -21,26 +13,6 @@ export interface DesktopServerExposure {
readonly advertisedHost: string | null;
}
export interface DesktopAdvertisedEndpointInput {
readonly port: number;
readonly exposure: DesktopServerExposure;
readonly customHttpsEndpointUrls?: readonly string[];
}
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
};
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
};
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
@@ -49,14 +21,6 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
const isUsableLanIpv4Address = (address: string): boolean =>
!address.startsWith("127.") && !address.startsWith("169.254.");
function isHttpsEndpointUrl(value: string): boolean {
try {
return new URL(value).protocol === "https:";
} catch {
return false;
}
}
export function resolveLanAdvertisedHost(
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
explicitHost: string | undefined,
@@ -114,75 +78,3 @@ export function resolveDesktopServerExposure(input: {
advertisedHost,
};
}
function createDesktopEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
source: "desktop-core",
});
}
function createManualEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
source: "user",
});
}
export function resolveDesktopCoreAdvertisedEndpoints(
input: DesktopAdvertisedEndpointInput,
): readonly AdvertisedEndpoint[] {
const endpoints: AdvertisedEndpoint[] = [
createDesktopEndpoint({
id: `desktop-loopback:${input.port}`,
label: "This machine",
httpBaseUrl: input.exposure.localHttpUrl,
reachability: "loopback",
status: "available",
description: "Loopback endpoint for this desktop app.",
}),
];
if (input.exposure.endpointUrl) {
endpoints.push(
createDesktopEndpoint({
id: `desktop-lan:${input.exposure.endpointUrl}`,
label: "Local network",
httpBaseUrl: input.exposure.endpointUrl,
reachability: "lan",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
}),
);
}
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
try {
const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
endpoints.push(
createManualEndpoint({
id: `manual:${customEndpointUrl}`,
label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
httpBaseUrl: customEndpointUrl,
reachability: "public",
...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
status: "unknown",
description: isHttpsEndpoint
? "User-configured HTTPS endpoint for this desktop backend."
: "User-configured endpoint for this desktop backend.",
}),
);
} catch {
// Ignore malformed user-configured endpoints without dropping valid endpoints.
}
}
return endpoints;
}
-98
View File
@@ -1,98 +0,0 @@
import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
import { discoverDesktopSshHosts, isSshPasswordPromptCancellation } from "./sshEnvironment.ts";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
FS.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempHomeDir(): string {
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-env-test-"));
tempDirectories.push(directory);
return directory;
}
describe("sshEnvironment", () => {
it("treats password prompt timeouts as cancellable authentication prompts", () => {
expect(
isSshPasswordPromptCancellation(
new SshPasswordPromptError({
message: "SSH authentication timed out for devbox.",
}),
),
).toBe(true);
});
it("wires desktop host discovery through the ssh package runtime", async () => {
const homeDir = makeTempHomeDir();
const sshDir = Path.join(homeDir, ".ssh");
FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true });
FS.writeFileSync(
Path.join(sshDir, "config"),
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
"utf8",
);
FS.writeFileSync(
Path.join(sshDir, "config.d", "team.conf"),
[
"Host staging",
" HostName staging.example.com",
"Host *",
" ServerAliveInterval 30",
"",
].join("\n"),
"utf8",
);
FS.writeFileSync(
Path.join(sshDir, "known_hosts"),
[
"known.example.com ssh-ed25519 AAAA",
"|1|hashed|entry ssh-ed25519 AAAA",
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
"",
].join("\n"),
"utf8",
);
await expect(discoverDesktopSshHosts({ homeDir })).resolves.toEqual([
{
alias: "bastion.example.com",
hostname: "bastion.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
source: "ssh-config",
},
{
alias: "known.example.com",
hostname: "known.example.com",
username: null,
port: null,
source: "known-hosts",
},
{
alias: "staging",
hostname: "staging",
username: null,
port: null,
source: "ssh-config",
},
]);
});
});
-420
View File
@@ -1,420 +0,0 @@
import * as Crypto from "node:crypto";
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import type {
AuthBearerBootstrapResult,
AuthSessionState,
AuthWebSocketTokenResult,
DesktopDiscoveredSshHost,
DesktopSshEnvironmentTarget,
DesktopSshPasswordPromptRequest,
ExecutionEnvironmentDescriptor,
} from "@t3tools/contracts";
import {
SshPasswordPrompt,
type SshPasswordPromptShape,
type SshPasswordRequest,
} from "@t3tools/ssh/auth";
import { discoverSshHosts } from "@t3tools/ssh/config";
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
import {
fetchLoopbackSshJson,
SshEnvironmentManager,
type RemoteT3RunnerOptions,
} from "@t3tools/ssh/tunnel";
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
export { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
interface DesktopSshEnvironmentManagerOptions {
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
}
const sshRuntime = ManagedRuntime.make(
Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, NetService.layer),
);
function createDesktopSshRuntime(
passwordPrompt: SshPasswordPromptShape,
scope: Scope.Scope,
options: DesktopSshEnvironmentManagerOptions,
) {
return ManagedRuntime.make(
Layer.mergeAll(
NodeServices.layer,
NodeHttpClient.layerUndici,
NetService.layer,
Layer.succeed(Scope.Scope, scope),
Layer.succeed(SshPasswordPrompt, SshPasswordPrompt.of(passwordPrompt)),
SshEnvironmentManager.layer({
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
...(options.resolveCliRunner === undefined
? {}
: { resolveCliRunner: options.resolveCliRunner }),
}),
),
);
}
export async function discoverDesktopSshHosts(input?: {
readonly homeDir?: string;
}): Promise<readonly DesktopDiscoveredSshHost[]> {
return await sshRuntime.runPromise(discoverSshHosts(input ?? {}));
}
export class DesktopSshEnvironmentManager {
private readonly runtime: ReturnType<typeof createDesktopSshRuntime>;
private readonly scope: Scope.Scope;
constructor(options: DesktopSshEnvironmentManagerOptions = {}) {
const passwordPrompt: SshPasswordPromptShape = {
isAvailable: options.passwordProvider !== undefined,
request: (request) => {
const passwordProvider = options.passwordProvider;
if (!passwordProvider) {
return Effect.succeed(null);
}
return Effect.tryPromise({
try: () => passwordProvider(request),
catch: (cause) =>
new SshPasswordPromptError({
message: cause instanceof Error ? cause.message : "SSH password prompt failed.",
cause,
}),
});
},
};
this.scope = Effect.runSync(Scope.make());
this.runtime = createDesktopSshRuntime(passwordPrompt, this.scope, options);
}
async discoverHosts(): Promise<readonly DesktopDiscoveredSshHost[]> {
return await discoverDesktopSshHosts();
}
async ensureEnvironment(
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) {
return await this.runtime.runPromise(
Effect.service(SshEnvironmentManager).pipe(
Effect.flatMap((manager) => manager.ensureEnvironment(target, options)),
),
);
}
async disconnectEnvironment(target: DesktopSshEnvironmentTarget): Promise<void> {
await this.runtime.runPromise(
Effect.service(SshEnvironmentManager).pipe(
Effect.flatMap((manager) => manager.disconnectEnvironment(target)),
),
);
}
async dispose(): Promise<void> {
await this.runtime.runPromise(Scope.close(this.scope, Exit.void));
await this.runtime.dispose();
}
}
function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarget | null {
if (typeof rawTarget !== "object" || rawTarget === null) {
return null;
}
const target = rawTarget as Partial<DesktopSshEnvironmentTarget>;
if (typeof target.alias !== "string" || typeof target.hostname !== "string") {
return null;
}
if (
target.username !== null &&
target.username !== undefined &&
typeof target.username !== "string"
) {
return null;
}
if (target.port !== null && target.port !== undefined && !Number.isInteger(target.port)) {
return null;
}
const alias = target.alias.trim();
const hostname = target.hostname.trim();
if (alias.length === 0 || hostname.length === 0) {
return null;
}
return {
alias,
hostname,
username: target.username?.trim() || null,
port: target.port ?? null,
};
}
/** Minimal subset of Electron's BrowserWindow used by the SSH bridge. */
export interface DesktopSshBridgeWindow {
isDestroyed(): boolean;
isMinimized(): boolean;
restore(): void;
focus(): void;
readonly webContents: {
send(channel: string, ...args: readonly unknown[]): void;
};
}
/** Minimal subset of Electron's ipcMain used by the SSH bridge. */
export interface DesktopSshBridgeIpcMain {
removeHandler(channel: string): void;
handle(
channel: string,
listener: (event: unknown, ...args: readonly unknown[]) => unknown | Promise<unknown>,
): void;
}
export interface DesktopSshEnvironmentBridgeOptions {
readonly getMainWindow: () => DesktopSshBridgeWindow | null;
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
readonly passwordPromptTimeoutMs?: number;
}
interface PendingSshPasswordPrompt {
readonly resolve: (password: string | null) => void;
readonly reject: (error: Error) => void;
readonly timeout: ReturnType<typeof setTimeout>;
}
export function isSshPasswordPromptCancellation(error: unknown): error is SshPasswordPromptError {
const message = error instanceof SshPasswordPromptError ? error.message.toLowerCase() : "";
return (
error instanceof SshPasswordPromptError &&
(message.includes("cancelled") || message.includes("timed out"))
);
}
/**
* Wires the SSH environment manager to Electron IPC, owning the renderer-facing
* password prompt state so `main.ts` only needs to register, cancel, and dispose.
*/
export class DesktopSshEnvironmentBridge {
private readonly options: DesktopSshEnvironmentBridgeOptions;
private readonly manager: DesktopSshEnvironmentManager;
private readonly pendingPrompts = new Map<string, PendingSshPasswordPrompt>();
private readonly passwordPromptTimeoutMs: number;
constructor(options: DesktopSshEnvironmentBridgeOptions) {
this.options = options;
this.passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
this.manager = new DesktopSshEnvironmentManager({
passwordProvider: (request) => this.requestPasswordFromRenderer(request),
...(options.resolveCliPackageSpec === undefined
? {}
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
...(options.resolveCliRunner === undefined
? {}
: { resolveCliRunner: options.resolveCliRunner }),
});
}
registerIpcHandlers(ipcMain: DesktopSshBridgeIpcMain): void {
ipcMain.removeHandler(DISCOVER_SSH_HOSTS_CHANNEL);
ipcMain.handle(DISCOVER_SSH_HOSTS_CHANNEL, async () => this.manager.discoverHosts());
ipcMain.removeHandler(ENSURE_SSH_ENVIRONMENT_CHANNEL);
ipcMain.handle(ENSURE_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget, rawOptions) => {
const target = getSafeDesktopSshTarget(rawTarget);
if (!target) {
throw new Error("Invalid desktop SSH target.");
}
const issuePairingToken =
typeof rawOptions === "object" &&
rawOptions !== null &&
"issuePairingToken" in rawOptions &&
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
try {
return await this.manager.ensureEnvironment(target, {
issuePairingToken,
});
} catch (error) {
if (isSshPasswordPromptCancellation(error)) {
return {
type: SSH_PASSWORD_PROMPT_CANCELLED_RESULT,
message: error.message,
};
}
throw error;
}
});
ipcMain.removeHandler(DISCONNECT_SSH_ENVIRONMENT_CHANNEL);
ipcMain.handle(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget) => {
const target = getSafeDesktopSshTarget(rawTarget);
if (!target) {
throw new Error("Invalid desktop SSH target.");
}
await this.manager.disconnectEnvironment(target);
});
ipcMain.removeHandler(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL);
ipcMain.handle(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, async (_event, rawHttpBaseUrl) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<ExecutionEnvironmentDescriptor>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/.well-known/t3/environment",
}),
),
);
ipcMain.removeHandler(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL);
ipcMain.handle(
BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
async (_event, rawHttpBaseUrl, rawCredential) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<AuthBearerBootstrapResult>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/bootstrap/bearer",
method: "POST",
body: { credential: rawCredential },
}),
),
);
ipcMain.removeHandler(FETCH_SSH_SESSION_STATE_CHANNEL);
ipcMain.handle(
FETCH_SSH_SESSION_STATE_CHANNEL,
async (_event, rawHttpBaseUrl, rawBearerToken) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<AuthSessionState>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/session",
bearerToken: rawBearerToken,
}),
),
);
ipcMain.removeHandler(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL);
ipcMain.handle(
ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
async (_event, rawHttpBaseUrl, rawBearerToken) =>
sshRuntime.runPromise(
fetchLoopbackSshJson<AuthWebSocketTokenResult>({
httpBaseUrl: rawHttpBaseUrl,
pathname: "/api/auth/ws-token",
method: "POST",
bearerToken: rawBearerToken,
}),
),
);
ipcMain.removeHandler(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL);
ipcMain.handle(
RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
async (_event, rawRequestId, rawPassword) => {
if (typeof rawRequestId !== "string" || rawRequestId.trim().length === 0) {
throw new Error("Invalid SSH password prompt id.");
}
if (rawPassword !== null && typeof rawPassword !== "string") {
throw new Error("Invalid SSH password prompt response.");
}
const pending = this.pendingPrompts.get(rawRequestId);
if (!pending) {
throw new Error("SSH password prompt expired. Try connecting again.");
}
clearTimeout(pending.timeout);
this.pendingPrompts.delete(rawRequestId);
pending.resolve(rawPassword);
},
);
}
cancelPendingPasswordPrompts(reason: string): void {
for (const [requestId, pending] of this.pendingPrompts) {
clearTimeout(pending.timeout);
this.pendingPrompts.delete(requestId);
pending.reject(new Error(reason));
}
}
async dispose(): Promise<void> {
this.cancelPendingPasswordPrompts("SSH environment bridge disposed.");
await this.manager.dispose();
}
private async requestPasswordFromRenderer(input: SshPasswordRequest): Promise<string | null> {
const window = this.options.getMainWindow();
if (!window || window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
const request: DesktopSshPasswordPromptRequest = {
requestId: Crypto.randomUUID(),
destination: input.destination,
username: input.username,
prompt: input.prompt,
expiresAt: new Date(Date.now() + this.passwordPromptTimeoutMs).toISOString(),
};
return await new Promise<string | null>((resolve, reject) => {
const rejectPrompt = (error: Error) => {
clearTimeout(timeout);
this.pendingPrompts.delete(request.requestId);
reject(error);
};
const timeout = setTimeout(() => {
this.pendingPrompts.delete(request.requestId);
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
}, this.passwordPromptTimeoutMs);
timeout.unref();
this.pendingPrompts.set(request.requestId, { resolve, reject, timeout });
try {
if (window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
if (window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
if (window.isMinimized()) {
window.restore();
}
if (window.isDestroyed()) {
throw new Error("T3 Code window is not available for SSH authentication.");
}
window.focus();
} catch (error) {
rejectPrompt(
error instanceof Error
? error
: new Error("T3 Code window is not available for SSH authentication."),
);
}
});
}
}
@@ -1,122 +0,0 @@
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
import {
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
resolveTailscaleAdvertisedEndpoints,
} from "./tailscaleEndpointProvider.ts";
describe("tailscale endpoint provider", () => {
it("detects Tailnet IPv4 addresses", () => {
expect(isTailscaleIpv4Address("100.64.0.1")).toBe(true);
expect(isTailscaleIpv4Address("100.127.255.254")).toBe(true);
expect(isTailscaleIpv4Address("100.128.0.1")).toBe(false);
expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false);
});
it("parses MagicDNS names from tailscale status", async () => {
expect(
Effect.runSync(
parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })),
),
).toBe("desktop.tail.ts.net");
expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull();
await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined();
});
it("resolves Tailscale endpoints as add-on advertised endpoints", async () => {
await expect(
resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {
tailscale0: [
{
address: "100.100.100.100",
family: "IPv4",
internal: false,
netmask: "255.192.0.0",
cidr: "100.100.100.100/10",
mac: "00:00:00:00:00:00",
},
],
},
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
}),
).resolves.toEqual([
{
id: "tailscale-ip:http://100.100.100.100:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.100.100.100:3773/",
wsBaseUrl: "ws://100.100.100.100:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "Reachable from devices on the same Tailnet.",
},
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "requires-configuration",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "unavailable",
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
},
]);
});
it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => {
await expect(
resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
serveEnabled: true,
probe: async () => true,
}),
).resolves.toEqual([
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "HTTPS endpoint served by Tailscale Serve.",
},
]);
});
});
@@ -1,142 +0,0 @@
import type { NetworkInterfaceInfo } from "node:os";
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
probeTailscaleHttpsEndpoint,
readTailscaleStatus,
} from "@t3tools/tailscale";
import { Effect, Layer } from "effect";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici);
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
};
function createTailscaleEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: TAILSCALE_ENDPOINT_PROVIDER,
source: "desktop-addon",
});
}
export function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
if (!interfaceAddresses) continue;
for (const address of interfaceAddresses) {
if (address.internal) continue;
if (address.family !== "IPv4") continue;
if (!isTailscaleIpv4Address(address.address)) continue;
if (seen.has(address.address)) continue;
seen.add(address.address);
endpoints.push(
createTailscaleEndpoint({
id: `tailscale-ip:http://${address.address}:${input.port}`,
label: "Tailscale IP",
httpBaseUrl: `http://${address.address}:${input.port}`,
reachability: "private-network",
status: "available",
description: "Reachable from devices on the same Tailnet.",
}),
);
}
}
return endpoints;
}
export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: {
readonly dnsName: string | null;
readonly serveEnabled: boolean;
readonly servePort?: number;
readonly probe?: (baseUrl: string) => Promise<boolean>;
}): Promise<AdvertisedEndpoint | null> {
if (!input.dnsName) {
return null;
}
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: input.dnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
});
const isReachable = input.serveEnabled
? await (input.probe?.(httpBaseUrl) ??
Effect.runPromise(
probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
Effect.provide(TailscaleDesktopLayer),
),
))
: false;
return createTailscaleEndpoint({
id: `tailscale-magicdns:${httpBaseUrl}`,
label: "Tailscale HTTPS",
httpBaseUrl,
reachability: "private-network",
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
status: isReachable ? "available" : "unavailable",
description: isReachable
? "HTTPS endpoint served by Tailscale Serve."
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
});
}
export async function resolveTailscaleAdvertisedEndpoints(input: {
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
readonly statusJson?: string | null;
readonly probe?: (baseUrl: string) => Promise<boolean>;
}): Promise<readonly AdvertisedEndpoint[]> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const dnsName =
input.statusJson === undefined
? await Effect.runPromise(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
Effect.provide(TailscaleDesktopLayer),
),
)
: input.statusJson
? await Effect.runPromise(
parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(null)),
),
)
: null;
const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({
dnsName,
serveEnabled: input.serveEnabled === true,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
...(input.probe === undefined ? {} : { probe: input.probe }),
});
return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints;
}
@@ -331,6 +331,7 @@ export const makeOrchestrationIntegrationHarness = (
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
@@ -506,7 +506,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
ignoreWhitespace: false,
});
assert.equal(incrementalDiff.includes("README.md"), true);
@@ -515,7 +514,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
fallbackFromToHead: false,
ignoreWhitespace: false,
});
assert.equal(fullDiff.includes("README.md"), true);
-1
View File
@@ -40,7 +40,6 @@
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
@@ -48,7 +48,6 @@ describe("CheckpointDiffQueryLive", () => {
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
@@ -69,14 +68,9 @@ describe("CheckpointDiffQueryLive", () => {
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
@@ -108,7 +102,6 @@ describe("CheckpointDiffQueryLive", () => {
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
@@ -120,7 +113,6 @@ describe("CheckpointDiffQueryLive", () => {
cwd: "/tmp/workspace",
fromCheckpointRef: expectedFromRef,
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
@@ -131,67 +123,6 @@ describe("CheckpointDiffQueryLive", () => {
});
});
it("defaults to hide whitespace changes", async () => {
const projectId = ProjectId.make("project-default-whitespace");
const threadId = ThreadId.make("thread-default-whitespace");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ ignoreWhitespace });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
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,7 +24,6 @@ const make = Effect.gen(function* () {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
@@ -132,7 +131,6 @@ const make = Effect.gen(function* () {
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
@@ -159,7 +157,6 @@ const make = Effect.gen(function* () {
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace ?? true,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
return {
@@ -114,7 +114,6 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: true,
});
expect(diff).toContain("diff --git");
@@ -122,80 +121,5 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
expect(diff).toContain("+line 04999");
}),
);
it.effect("can hide indentation churn when changes wrap existing lines", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const componentPath = path.join(tmp, "Component.tsx");
yield* writeTextFile(
componentPath,
[
"export function View() {",
" return (",
" <section>",
" <h1>Title</h1>",
" <p>Body</p>",
" </section>",
" );",
"}",
"",
].join("\n"),
);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: fromCheckpointRef,
});
yield* writeTextFile(
componentPath,
[
"export function View() {",
" return (",
" <section>",
" {isReady ? (",
" <div>",
" <h1>Title</h1>",
" <p>Body</p>",
" </div>",
" ) : null}",
" </section>",
" );",
"}",
"",
].join("\n"),
);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: toCheckpointRef,
});
const normalDiff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: false,
});
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
ignoreWhitespace: true,
});
expect(normalDiff).toContain("diff --git");
expect(normalDiff).toContain("- <h1>Title</h1>");
expect(normalDiff).toContain("+ <h1>Title</h1>");
expect(whitespaceIgnoredDiff).toContain("diff --git");
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
expect(whitespaceIgnoredDiff).toContain("+ <div>");
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
}),
);
});
});
@@ -259,20 +259,10 @@ const makeCheckpointStore = Effect.gen(function* () {
});
}
const diffArgs = [
"diff",
"--patch",
"--minimal",
"--no-color",
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
fromCommitOid,
toCommitOid,
];
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: diffArgs,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
@@ -32,7 +32,6 @@ export interface DiffCheckpointsInput {
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly fallbackFromToHead?: boolean;
readonly ignoreWhitespace: boolean;
}
export interface DeleteCheckpointRefsInput {
-36
View File
@@ -46,8 +46,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -89,8 +87,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -112,8 +108,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(true),
logWebSocketEvents: Option.some(true),
tailscaleServeEnabled: Option.some(true),
tailscaleServePort: Option.some(8443),
},
Option.some("Debug"),
).pipe(
@@ -155,8 +149,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
});
}),
);
@@ -169,8 +161,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
@@ -186,8 +176,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(false),
logWebSocketEvents: Option.some(false),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -224,8 +212,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -243,8 +229,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
@@ -262,8 +246,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -299,8 +281,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(join(baseDir, "dev"), resolved.stateDir);
}),
@@ -325,8 +305,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -368,8 +346,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: false,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
@@ -385,8 +361,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.some("Debug"),
).pipe(
@@ -425,8 +399,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -460,8 +432,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -493,8 +463,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -517,8 +485,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
{
@@ -556,8 +522,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
-2
View File
@@ -76,8 +76,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
} satisfies ServerConfigShape;
});
-47
View File
@@ -78,8 +78,6 @@ const BootstrapEnvelopeSchema = Schema.Struct({
desktopBootstrapToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
tailscaleServePort: Schema.optional(PortSchema),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
@@ -128,17 +126,6 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withAlias("log-ws-events"),
Flag.optional,
);
const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
Flag.withDescription(
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
),
Flag.optional,
);
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
Flag.optional,
);
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
@@ -187,14 +174,6 @@ const EnvServerConfig = Config.all({
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
interface CliServerFlags {
@@ -208,8 +187,6 @@ interface CliServerFlags {
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
readonly tailscaleServeEnabled: Option.Option<boolean>;
readonly tailscaleServePort: Option.Option<number>;
}
interface CliAuthLocationFlags {
@@ -256,8 +233,6 @@ export const resolveServerConfig = (
bootstrapFd: flags.bootstrapFd ?? Option.none(),
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
} satisfies CliServerFlags;
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
@@ -348,22 +323,6 @@ export const resolveServerConfig = (
),
() => Boolean(devUrl),
);
const tailscaleServeEnabled = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServeEnabled,
Option.fromUndefinedOr(env.tailscaleServeEnabled),
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
),
() => false,
);
const tailscaleServePort = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServePort,
Option.fromUndefinedOr(env.tailscaleServePort),
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
),
() => 443,
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
@@ -406,8 +365,6 @@ export const resolveServerConfig = (
desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
tailscaleServePort,
};
return config;
@@ -429,8 +386,6 @@ const resolveCliAuthConfig = (
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
cliLogLevel,
);
@@ -811,8 +766,6 @@ const sharedServerCommandFlags = {
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
tailscaleServeEnabled: tailscaleServeFlag,
tailscaleServePort: tailscaleServePortFlag,
} as const;
const authLocationFlags = sharedServerLocationFlags;
-4
View File
@@ -65,8 +65,6 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly desktopBootstrapToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
}
export const deriveServerPaths = Effect.fn(function* (
@@ -160,8 +158,6 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
@@ -30,8 +30,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
+3 -7
View File
@@ -580,13 +580,6 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCliError({
operation: "createRepository",
detail: `Unexpected repository create: ${input.repository}`,
}),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
@@ -876,6 +869,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
kind: "unknown",
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
@@ -906,6 +900,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
kind: "unknown",
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
@@ -3193,6 +3188,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
exitCode: 0,
}),
expect.objectContaining({
kind: "action_finished",
+1
View File
@@ -724,6 +724,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
: null;
return {
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
isRepo: details.isRepo,
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
hasPrimaryRemote: details.hasOriginRemote,
@@ -26,6 +26,7 @@ describe("GitWorkflowService", () => {
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
assert.deepStrictEqual(status, {
kind: "unknown",
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
@@ -52,6 +53,7 @@ describe("GitWorkflowService", () => {
const status = yield* workflow.status({ cwd: "/not-a-repo" });
assert.deepStrictEqual(status, {
kind: "unknown",
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
+66 -72
View File
@@ -3,6 +3,7 @@ import { Context, Effect, Layer } from "effect";
import {
GitManagerError,
GitCommandError,
type VcsDriverKind,
type VcsSwitchRefInput,
type VcsSwitchRefResult,
type VcsCreateRefInput,
@@ -29,6 +30,7 @@ import {
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
export interface GitWorkflowServiceShape {
readonly status: (
@@ -91,31 +93,7 @@ const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =
detail,
});
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
return {
isRepo: false,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
};
}
function nonRepositoryStatus(): VcsStatusResult {
return {
...nonRepositoryLocalStatus(),
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
};
}
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
function nonRepositoryListRefs(): VcsListRefsResult {
return {
@@ -127,6 +105,16 @@ function nonRepositoryListRefs(): VcsListRefsResult {
};
}
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
kind,
isRepo,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: emptyWorkingTree,
});
export const make = Effect.fn("makeGitWorkflowService")(function* () {
const registry = yield* VcsDriverRegistry;
const git = yield* GitVcsDriver;
@@ -180,33 +168,6 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
}
});
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
function* (operation: string, cwd: string) {
const handle = yield* registry
.detect({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (!handle) {
return false;
}
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
}
return true;
},
);
const detectGitRepositoryForCommand = Effect.fn(
"GitWorkflowService.detectGitRepositoryForCommand",
)(function* (operation: string, cwd: string) {
@@ -242,27 +203,60 @@ export const make = Effect.fn("makeGitWorkflowService")(function* () {
(input: Input) =>
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
const localStatus: GitWorkflowServiceShape["localStatus"] = Effect.fn(
"GitWorkflowService.localStatus",
)(function* (input) {
const handle = yield* registry
.detect({ cwd: input.cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
"GitWorkflowService.localStatus",
input.cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (!handle) {
return nonGitLocalStatus("unknown", false);
}
if (handle.kind === "git") {
return yield* gitManager.localStatus(input);
}
return nonGitLocalStatus(handle.kind, true);
});
const remoteStatus: GitWorkflowServiceShape["remoteStatus"] = Effect.fn(
"GitWorkflowService.remoteStatus",
)(function* (input) {
const handle = yield* registry
.detect({ cwd: input.cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
"GitWorkflowService.remoteStatus",
input.cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle?.kind === "git") {
return yield* gitManager.remoteStatus(input);
}
return null;
});
const status: GitWorkflowServiceShape["status"] = Effect.fn("GitWorkflowService.status")(
function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
return mergeGitStatusParts(local, remote);
},
);
return GitWorkflowService.of({
status: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
),
),
localStatus: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository
? gitManager.localStatus(input)
: Effect.succeed(nonRepositoryLocalStatus()),
),
),
remoteStatus: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? gitManager.remoteStatus(input) : Effect.succeed(null),
),
),
status,
localStatus,
remoteStatus,
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
+277 -13
View File
@@ -13,10 +13,14 @@ 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,
@@ -44,20 +48,278 @@ import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import {
DEFAULT_KEYBINDINGS,
DEFAULT_RESOLVED_KEYBINDINGS,
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
} from "@t3tools/shared/keybindings";
export {
DEFAULT_KEYBINDINGS,
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
};
type WhenToken =
| { type: "identifier"; value: string }
| { type: "not" }
| { type: "and" }
| { type: "or" }
| { type: "lparen" }
| { type: "rparen" };
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" },
{ key: "mod+shift+[", command: "thread.previous" },
{ key: "mod+shift+]", command: "thread.next" },
...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
})),
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
key: `mod+${index + 1}`,
command,
when: "modelPickerOpen",
})),
];
function normalizeKeyToken(token: string): string {
if (token === "space") return " ";
if (token === "esc") return "escape";
return token;
}
/** @internal - Exported for testing */
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
const rawTokens = value
.toLowerCase()
.split("+")
.map((token) => token.trim());
const tokens = [...rawTokens];
let trailingEmptyCount = 0;
while (tokens[tokens.length - 1] === "") {
trailingEmptyCount += 1;
tokens.pop();
}
if (trailingEmptyCount > 0) {
tokens.push("+");
}
if (tokens.some((token) => token.length === 0)) {
return null;
}
if (tokens.length === 0) return null;
let key: string | null = null;
let metaKey = false;
let ctrlKey = false;
let shiftKey = false;
let altKey = false;
let modKey = false;
for (const token of tokens) {
switch (token) {
case "cmd":
case "meta":
metaKey = true;
break;
case "ctrl":
case "control":
ctrlKey = true;
break;
case "shift":
shiftKey = true;
break;
case "alt":
case "option":
altKey = true;
break;
case "mod":
modKey = true;
break;
default: {
if (key !== null) return null;
key = normalizeKeyToken(token);
}
}
}
if (key === null) return null;
return {
key,
metaKey,
ctrlKey,
shiftKey,
altKey,
modKey,
};
}
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
const tokens: WhenToken[] = [];
let index = 0;
while (index < expression.length) {
const current = expression[index];
if (!current) break;
if (/\s/.test(current)) {
index += 1;
continue;
}
if (expression.startsWith("&&", index)) {
tokens.push({ type: "and" });
index += 2;
continue;
}
if (expression.startsWith("||", index)) {
tokens.push({ type: "or" });
index += 2;
continue;
}
if (current === "!") {
tokens.push({ type: "not" });
index += 1;
continue;
}
if (current === "(") {
tokens.push({ type: "lparen" });
index += 1;
continue;
}
if (current === ")") {
tokens.push({ type: "rparen" });
index += 1;
continue;
}
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
if (!identifier) {
return null;
}
tokens.push({ type: "identifier", value: identifier[0] });
index += identifier[0].length;
}
return tokens;
}
function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
const tokens = tokenizeWhenExpression(expression);
if (!tokens || tokens.length === 0) return null;
let index = 0;
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
const token = tokens[index];
if (!token) return null;
if (token.type === "identifier") {
index += 1;
return { type: "identifier", name: token.value };
}
if (token.type === "lparen") {
index += 1;
const expressionNode = parseOr(depth + 1);
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
}
index += 1;
return expressionNode;
}
return null;
};
const parseUnary = (depth: number): KeybindingWhenNode | null => {
let notCount = 0;
while (tokens[index]?.type === "not") {
index += 1;
notCount += 1;
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
}
let node = parsePrimary(depth);
if (!node) return null;
while (notCount > 0) {
node = { type: "not", node };
notCount -= 1;
}
return node;
};
const parseAnd = (depth: number): KeybindingWhenNode | null => {
let left = parseUnary(depth);
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary(depth);
if (!right) return null;
left = { type: "and", left, right };
}
return left;
};
const parseOr = (depth: number): KeybindingWhenNode | null => {
let left = parseAnd(depth);
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd(depth);
if (!right) return null;
left = { type: "or", left, right };
}
return left;
};
const ast = parseOr(0);
if (!ast || index !== tokens.length) return null;
return ast;
}
/** @internal - Exported for testing */
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
const shortcut = parseKeybindingShortcut(rule.key);
if (!shortcut) return null;
if (rule.when !== undefined) {
const whenAst = parseKeybindingWhenExpression(rule.when);
if (!whenAst) return null;
return {
command: rule.command,
shortcut,
whenAst,
};
}
return {
command: rule.command,
shortcut,
};
}
export function compileResolvedKeybindingsConfig(
config: KeybindingsConfig,
): ResolvedKeybindingsConfig {
const compiled: Mutable<ResolvedKeybindingsConfig> = [];
for (const rule of config) {
const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
if (result._tag === "Success") {
compiled.push(result.value);
}
}
return compiled;
}
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
Schema.decodeTo(
@@ -150,6 +412,8 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
}
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
@@ -291,6 +291,7 @@ describe("CheckpointReactor", () => {
}).pipe(
Effect.as({
isRepo: true,
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
@@ -237,7 +237,6 @@ const make = Effect.gen(function* () {
fromCheckpointRef,
toCheckpointRef: targetCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace: false,
})
.pipe(
Effect.map((diff) =>
@@ -240,6 +240,7 @@ describe("ProviderCommandReactor", () => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "renamed-branch",
@@ -1,385 +0,0 @@
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationEvent,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asCommandId = (value: string): CommandId => CommandId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
async function projectEvents(
readModel: OrchestrationReadModel,
events: ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
): Promise<OrchestrationReadModel> {
let next = readModel;
let sequence = readModel.snapshotSequence;
for (const event of events) {
sequence += 1;
const sequencedEvent = {
...event,
sequence,
} as OrchestrationEvent;
next = await Effect.runPromise(projectEvent(next, sequencedEvent));
}
return next;
}
async function seedReadModel(): Promise<OrchestrationReadModel> {
const createdAt = "2026-01-01T00:00:00.000Z";
return projectEvents(createEmptyReadModel(createdAt), [
{
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-branch"),
type: "project.created",
occurredAt: createdAt,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-branch"),
title: "Project Branch",
workspaceRoot: "/tmp/project-branch",
defaultModelSelection: null,
scripts: [],
createdAt,
updatedAt: createdAt,
},
},
{
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.created",
occurredAt: createdAt,
commandId: asCommandId("cmd-thread-create"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
projectId: asProjectId("project-branch"),
title: "Source Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: "feature/source",
worktreePath: "/tmp/project-branch-worktree",
createdAt,
updatedAt: createdAt,
},
},
{
eventId: asEventId("evt-message-user"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:01:00.000Z",
commandId: asCommandId("cmd-message-user"),
causationEventId: null,
correlationId: asCommandId("cmd-message-user"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-user"),
role: "user",
text: "hello",
attachments: [
{
type: "image",
id: "thread-source-00000000-0000-4000-8000-000000000001",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 123,
},
],
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:01:00.000Z",
updatedAt: "2026-01-01T00:01:00.000Z",
},
},
{
eventId: asEventId("evt-message-assistant"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:02:00.000Z",
commandId: asCommandId("cmd-message-assistant"),
causationEventId: null,
correlationId: asCommandId("cmd-message-assistant"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-assistant"),
role: "assistant",
text: "partial response",
turnId: asTurnId("turn-source"),
streaming: true,
createdAt: "2026-01-01T00:02:00.000Z",
updatedAt: "2026-01-01T00:02:00.000Z",
},
},
{
eventId: asEventId("evt-activity-tool"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.activity-appended",
occurredAt: "2026-01-01T00:03:00.000Z",
commandId: asCommandId("cmd-activity-tool"),
causationEventId: null,
correlationId: asCommandId("cmd-activity-tool"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
activity: {
id: asEventId("activity-tool-source"),
tone: "tool",
kind: "tool.completed",
summary: "Read file",
payload: {
toolCallId: "tool-call-source",
detail: "read README.md",
requestId: "source-request-id",
},
turnId: asTurnId("turn-source"),
sequence: 10,
createdAt: "2026-01-01T00:03:00.000Z",
},
},
},
]);
}
describe("decideOrchestrationCommand thread.branch", () => {
it("creates a branched thread and copies transcript messages and activities", async () => {
const readModel = await seedReadModel();
const decided = await Effect.runPromise(
decideOrchestrationCommand({
readModel,
command: {
type: "thread.branch",
commandId: asCommandId("cmd-thread-branch"),
sourceThreadId: asThreadId("thread-source"),
threadId: asThreadId("thread-branch"),
createdAt: "2026-01-01T01:00:00.000Z",
},
}),
);
const events = Array.isArray(decided) ? decided : [decided];
expect(events.map((event) => event.type)).toEqual([
"thread.created",
"thread.message-sent",
"thread.message-sent",
"thread.activity-appended",
]);
const created = events[0];
expect(created?.type).toBe("thread.created");
if (created?.type !== "thread.created") {
throw new Error("Expected first event to create a thread.");
}
expect(created.payload).toMatchObject({
threadId: asThreadId("thread-branch"),
projectId: asProjectId("project-branch"),
title: "Source Thread (Branched)",
runtimeMode: "approval-required",
branch: "feature/source",
worktreePath: "/tmp/project-branch-worktree",
});
const copiedMessages = events.filter((event) => event.type === "thread.message-sent");
expect(copiedMessages.every((event) => event.type === "thread.message-sent")).toBe(true);
for (const event of copiedMessages) {
if (event.type !== "thread.message-sent") {
throw new Error("Expected copied event to be a message.");
}
expect(event.payload.threadId).toBe(asThreadId("thread-branch"));
expect(event.payload.turnId).toBeNull();
expect(event.payload.streaming).toBe(false);
expect(event.payload.messageId).not.toBe(asMessageId("message-user"));
expect(event.payload.messageId).not.toBe(asMessageId("message-assistant"));
expect(event.payload.attachments).toBeUndefined();
expect(event.causationEventId).toBe(created.eventId);
}
const copiedActivity = events.find((event) => event.type === "thread.activity-appended");
expect(copiedActivity?.type).toBe("thread.activity-appended");
if (copiedActivity?.type !== "thread.activity-appended") {
throw new Error("Expected copied tool activity.");
}
expect(copiedActivity.payload.threadId).toBe(asThreadId("thread-branch"));
expect(copiedActivity.payload.activity.id).not.toBe(asEventId("activity-tool-source"));
expect(copiedActivity.payload.activity.turnId).toBeNull();
expect(copiedActivity.payload.activity).toMatchObject({
tone: "tool",
kind: "tool.completed",
summary: "Read file",
payload: {
toolCallId: "tool-call-source",
detail: "read README.md",
},
});
expect(copiedActivity.payload.activity.payload).not.toMatchObject({
requestId: "source-request-id",
});
expect(copiedActivity.causationEventId).toBe(created.eventId);
const branchedReadModel = await projectEvents(readModel, events);
const branchedThread = branchedReadModel.threads.find(
(thread) => thread.id === asThreadId("thread-branch"),
);
expect(branchedThread?.messages.map((message) => message.text)).toEqual([
"hello",
"partial response",
]);
expect(branchedThread?.messages.every((message) => message.turnId === null)).toBe(true);
expect(branchedThread?.messages.every((message) => !message.streaming)).toBe(true);
expect(branchedThread?.activities.map((activity) => activity.summary)).toEqual(["Read file"]);
expect(branchedThread?.activities.every((activity) => activity.turnId === null)).toBe(true);
});
it("branches through a selected completed assistant message", async () => {
const readModel = await projectEvents(await seedReadModel(), [
{
eventId: asEventId("evt-message-assistant-complete"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:02:30.000Z",
commandId: asCommandId("cmd-message-assistant-complete"),
causationEventId: null,
correlationId: asCommandId("cmd-message-assistant-complete"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-assistant"),
role: "assistant",
text: "",
turnId: asTurnId("turn-source"),
streaming: false,
createdAt: "2026-01-01T00:02:30.000Z",
updatedAt: "2026-01-01T00:02:30.000Z",
},
},
{
eventId: asEventId("evt-later-message-user"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:04:00.000Z",
commandId: asCommandId("cmd-later-message-user"),
causationEventId: null,
correlationId: asCommandId("cmd-later-message-user"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-later-user"),
role: "user",
text: "later prompt",
turnId: null,
streaming: false,
createdAt: "2026-01-01T00:04:00.000Z",
updatedAt: "2026-01-01T00:04:00.000Z",
},
},
{
eventId: asEventId("evt-later-activity-tool"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.activity-appended",
occurredAt: "2026-01-01T00:05:00.000Z",
commandId: asCommandId("cmd-later-activity-tool"),
causationEventId: null,
correlationId: asCommandId("cmd-later-activity-tool"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
activity: {
id: asEventId("activity-later-tool"),
tone: "tool",
kind: "tool.completed",
summary: "Edited file",
payload: {
toolCallId: "tool-call-later",
detail: "edit src/index.ts",
},
turnId: asTurnId("turn-later"),
sequence: 20,
createdAt: "2026-01-01T00:05:00.000Z",
},
},
},
{
eventId: asEventId("evt-later-message-assistant"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-source"),
type: "thread.message-sent",
occurredAt: "2026-01-01T00:06:00.000Z",
commandId: asCommandId("cmd-later-message-assistant"),
causationEventId: null,
correlationId: asCommandId("cmd-later-message-assistant"),
metadata: {},
payload: {
threadId: asThreadId("thread-source"),
messageId: asMessageId("message-later-assistant"),
role: "assistant",
text: "later response",
turnId: asTurnId("turn-later"),
streaming: false,
createdAt: "2026-01-01T00:06:00.000Z",
updatedAt: "2026-01-01T00:06:00.000Z",
},
},
]);
const decided = await Effect.runPromise(
decideOrchestrationCommand({
readModel,
command: {
type: "thread.branch",
commandId: asCommandId("cmd-thread-branch-message"),
sourceThreadId: asThreadId("thread-source"),
sourceMessageId: asMessageId("message-assistant"),
threadId: asThreadId("thread-branch-message"),
createdAt: "2026-01-01T01:00:00.000Z",
},
}),
);
const events = Array.isArray(decided) ? decided : [decided];
const branchedReadModel = await projectEvents(readModel, events);
const branchedThread = branchedReadModel.threads.find(
(thread) => thread.id === asThreadId("thread-branch-message"),
);
expect(branchedThread?.messages.map((message) => message.text)).toEqual([
"hello",
"partial response",
]);
expect(branchedThread?.activities.map((activity) => activity.summary)).toEqual(["Read file"]);
expect(branchedThread?.messages.every((message) => message.turnId === null)).toBe(true);
expect(branchedThread?.activities.every((activity) => activity.turnId === null)).toBe(true);
});
});
+4 -177
View File
@@ -1,9 +1,7 @@
import {
EventId,
MessageId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect } from "effect";
@@ -20,15 +18,6 @@ import {
import { projectEvent } from "./projector.ts";
const nowIso = () => new Date().toISOString();
const timestampOffsetIso = (baseIso: string, offsetMs: number) =>
new Date(new Date(baseIso).getTime() + offsetMs).toISOString();
const sanitizeCopiedActivityPayload = (payload: unknown): unknown => {
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
return payload;
}
const { requestId: _requestId, ...rest } = payload as Record<string, unknown>;
return rest;
};
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
aggregateKind: "thread",
@@ -244,168 +233,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.branch": {
const sourceThread = yield* requireThread({
readModel,
command,
threadId: command.sourceThreadId,
});
yield* requireProject({
readModel,
command,
projectId: sourceThread.projectId,
});
yield* requireThreadAbsent({
readModel,
command,
threadId: command.threadId,
});
const sourceMessageIndex =
command.sourceMessageId === undefined
? -1
: sourceThread.messages.findIndex((message) => message.id === command.sourceMessageId);
if (command.sourceMessageId !== undefined && sourceMessageIndex === -1) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Message '${command.sourceMessageId}' does not exist on source thread '${command.sourceThreadId}'.`,
});
}
const sourceMessage =
sourceMessageIndex >= 0 ? sourceThread.messages[sourceMessageIndex] : undefined;
if (sourceMessage !== undefined && sourceMessage.role !== "assistant") {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Message '${sourceMessage.id}' is not an assistant message and cannot be used as a branch point.`,
});
}
if (sourceMessage !== undefined && sourceMessage.streaming) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `Assistant message '${sourceMessage.id}' is still streaming and cannot be used as a branch point.`,
});
}
const threadCreatedEvent: PlannedOrchestrationEvent = {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
type: "thread.created",
payload: {
threadId: command.threadId,
projectId: sourceThread.projectId,
title: command.title ?? `${sourceThread.title} (Branched)`,
modelSelection: sourceThread.modelSelection,
runtimeMode: sourceThread.runtimeMode,
interactionMode: sourceThread.interactionMode,
branch: sourceThread.branch,
worktreePath: sourceThread.worktreePath,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
const copiedThreadEvents: PlannedOrchestrationEvent[] = [];
const sourceMessages =
sourceMessageIndex >= 0
? sourceThread.messages.slice(0, sourceMessageIndex + 1)
: sourceThread.messages;
const includedTurnIds = new Set(
sourceMessages.flatMap((message) => (message.turnId === null ? [] : [message.turnId])),
);
const sourceActivities =
sourceMessage === undefined
? sourceThread.activities
: sourceThread.activities.filter((activity) => {
if (activity.turnId !== null && includedTurnIds.has(activity.turnId)) {
return true;
}
return activity.createdAt <= sourceMessage.updatedAt;
});
const sourceEntries = [
...sourceMessages.map((message, sourceIndex) => ({
kind: "message" as const,
createdAt: message.createdAt,
sourceIndex,
message,
})),
...sourceActivities.map((activity, sourceIndex) => ({
kind: "activity" as const,
createdAt: activity.createdAt,
sourceIndex,
activity,
})),
].toSorted((left, right) => {
const createdAtComparison = left.createdAt.localeCompare(right.createdAt);
if (createdAtComparison !== 0) {
return createdAtComparison;
}
if (left.kind !== right.kind) {
return left.kind === "message" ? -1 : 1;
}
return left.sourceIndex - right.sourceIndex;
});
for (const [index, sourceEntry] of sourceEntries.entries()) {
const copiedAt = timestampOffsetIso(command.createdAt, index + 1);
const eventBase = withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: copiedAt,
commandId: command.commandId,
});
const copiedBase = {
eventId: eventBase.eventId,
aggregateKind: eventBase.aggregateKind,
aggregateId: eventBase.aggregateId,
occurredAt: eventBase.occurredAt,
commandId: eventBase.commandId,
causationEventId: threadCreatedEvent.eventId,
correlationId: eventBase.correlationId,
metadata: eventBase.metadata,
};
if (sourceEntry.kind === "message") {
copiedThreadEvents.push({
...copiedBase,
type: "thread.message-sent",
payload: {
threadId: command.threadId,
messageId: MessageId.make(crypto.randomUUID()),
role: sourceEntry.message.role,
text: sourceEntry.message.text,
turnId: null,
streaming: false,
createdAt: copiedAt,
updatedAt: copiedAt,
},
});
continue;
}
copiedThreadEvents.push({
...copiedBase,
type: "thread.activity-appended",
payload: {
threadId: command.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
tone: sourceEntry.activity.tone,
kind: sourceEntry.activity.kind,
summary: sourceEntry.activity.summary,
payload: sanitizeCopiedActivityPayload(sourceEntry.activity.payload),
turnId: null,
sequence: index,
createdAt: copiedAt,
},
},
});
}
return [threadCreatedEvent, ...copiedThreadEvents];
}
case "thread.delete": {
yield* requireThread({
readModel,
+36 -48
View File
@@ -54,6 +54,17 @@ import { vi } from "vitest";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
const testGitRepository = (rootPath: string) => ({
kind: "git" as const,
rootPath,
metadataPath: null,
freshness: {
source: "live-local" as const,
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
});
import type { ServerConfigShape } from "./config.ts";
import { deriveServerPaths, ServerConfig } from "./config.ts";
import { makeRoutesLayer } from "./server.ts";
@@ -75,7 +86,6 @@ 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,
@@ -118,10 +128,6 @@ import {
} from "./vcs/VcsDriverRegistry.ts";
import { layer as VcsProvisioningServiceLayer } from "./vcs/VcsProvisioningService.ts";
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
import {
SourceControlRepositoryService,
type SourceControlRepositoryServiceShape,
} from "./sourceControl/SourceControlRepositoryService.ts";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
@@ -218,8 +224,10 @@ const browserOtlpTracingLayer = Layer.mergeAll(
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
);
const makeAuthTestLayer = () =>
ServerAuthLive.pipe(Layer.provide(SqlitePersistenceMemory), Layer.provide(ServerSecretStoreLive));
const authTestLayer = ServerAuthLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStoreLive),
);
const makeBrowserOtlpPayload = (spanName: string) =>
Effect.gen(function* () {
@@ -333,7 +341,6 @@ const buildAppUnderTest = (options?: {
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
gitManager?: Partial<GitManagerShape>;
sourceControlRepositoryService?: Partial<SourceControlRepositoryServiceShape>;
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
terminalManager?: Partial<TerminalManagerShape>;
@@ -377,8 +384,6 @@ const buildAppUnderTest = (options?: {
desktopBootstrapToken: defaultDesktopBootstrapToken,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
...options?.config,
};
const layerConfig = Layer.succeed(ServerConfig, config);
@@ -551,11 +556,6 @@ const buildAppUnderTest = (options?: {
Layer.provide(gitVcsDriverLayer),
Layer.provide(gitWorkflowLayer),
Layer.provide(vcsProvisioningLayer),
Layer.provide(
Layer.mock(SourceControlRepositoryService)({
...options?.layers?.sourceControlRepositoryService,
}),
),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provide(
Layer.mock(ProjectSetupScriptRunner)({
@@ -654,7 +654,7 @@ const buildAppUnderTest = (options?: {
...options?.layers?.repositoryIdentityResolver,
}),
),
Layer.provideMerge(makeAuthTestLayer()),
Layer.provideMerge(authTestLayer),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(layerConfig),
@@ -2022,7 +2022,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.deepEqual(second, {
version: 1,
type: "keybindingsUpdated",
payload: { keybindings: [], issues: [] },
payload: { issues: [] },
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -2384,6 +2384,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest({
layers: {
vcsDriver: {
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
isInsideWorkTree: () => Effect.succeed(true),
},
gitManager: {
invalidateLocalStatus: () => Effect.void,
invalidateRemoteStatus: () => Effect.void,
@@ -2391,6 +2395,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
@@ -2407,6 +2412,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
status: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
@@ -2520,9 +2526,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
createRef: (input) => Effect.succeed({ refName: input.refName }),
switchRef: (input) => Effect.succeed({ refName: input.refName }),
},
vcsDriver: {
isInsideWorkTree: () => Effect.succeed(true),
},
},
});
@@ -2663,6 +2666,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
@@ -2684,6 +2688,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
statusCalls += 1;
return {
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
@@ -2740,6 +2745,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
@@ -2761,6 +2767,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
statusCalls += 1;
return {
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
@@ -2798,6 +2805,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest({
layers: {
vcsDriver: {
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
},
gitVcsDriver: {
pullCurrentBranch: () =>
Effect.succeed({
@@ -2812,6 +2822,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
@@ -2851,6 +2862,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
layers: {
vcsDriver: {
isInsideWorkTree: () => Effect.succeed(true),
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
},
gitManager: {
invalidateLocalStatus: () => Effect.void,
@@ -2858,6 +2870,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
@@ -2927,6 +2940,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
layers: {
vcsDriver: {
isInsideWorkTree: () => Effect.succeed(true),
detectRepository: () => Effect.succeed(testGitRepository("/tmp/repo")),
},
gitManager: {
invalidateLocalStatus: () => Effect.void,
@@ -2937,6 +2951,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.andThen(
Effect.succeed({
isRepo: true,
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
@@ -3111,34 +3126,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc orchestration shell snapshot errors", () =>
Effect.gen(function* () {
const projectionError = new PersistenceSqlError({
operation: "ProjectionSnapshotQuery.getShellSnapshot:test",
detail: "failed to read projection shell snapshot",
});
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getShellSnapshot: () => Effect.fail(projectionError),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(Stream.runCollect),
).pipe(Effect.result),
);
assertTrue(result._tag === "Failure");
assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
assertTrue(result.failure.cause instanceof Error);
assert.include(result.failure.cause.message, projectionError.message);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("enriches replayed project events with repository identity metadata", () =>
Effect.gen(function* () {
const repositoryIdentity = {
@@ -3631,6 +3618,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "t3code/bootstrap-refName",
+6 -66
View File
@@ -54,7 +54,6 @@ 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";
@@ -83,7 +82,6 @@ import {
orchestrationSnapshotRouteLayer,
} from "./orchestration/http.ts";
import { NetService } from "@t3tools/shared/Net";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
@@ -163,15 +161,15 @@ const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProjectConfig.layer),
);
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
const GitManagerLayerLive = GitManager.layer.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
Layer.provideMerge(
SourceControlProviderRegistry.layer.pipe(
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
Layer.provideMerge(VcsDriverRegistryLayerLive),
),
),
Layer.provideMerge(TextGeneration.layer),
);
@@ -185,17 +183,11 @@ 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))),
);
@@ -335,57 +327,6 @@ export const makeServerLayer = Layer.unwrap(
() => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
),
);
const tailscaleServeLayer = config.tailscaleServeEnabled
? Layer.effectDiscard(
Effect.acquireRelease(
Effect.gen(function* () {
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
return null;
}
const localPort = address.port;
return yield* ensureTailscaleServe({
localPort,
servePort: config.tailscaleServePort,
localHost: "127.0.0.1",
}).pipe(
Effect.as({ localPort, servePort: config.tailscaleServePort }),
Effect.tap(() =>
Effect.logInfo("Tailscale Serve configured", {
localPort,
servePort: config.tailscaleServePort,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to configure Tailscale Serve", {
cause,
localPort,
servePort: config.tailscaleServePort,
}).pipe(Effect.as(null)),
),
);
}),
(configured) =>
configured
? disableTailscaleServe({ servePort: configured.servePort }).pipe(
Effect.tap(() =>
Effect.logInfo("Tailscale Serve disabled", {
servePort: configured.servePort,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to disable Tailscale Serve", {
cause,
servePort: configured.servePort,
}),
),
)
: Effect.void,
),
)
: Layer.empty;
const serverApplicationLayer = Layer.mergeAll(
HttpRouter.serve(makeRoutesLayer, {
@@ -393,7 +334,6 @@ export const makeServerLayer = Layer.unwrap(
}),
httpListeningLayer,
runtimeStateLayer,
tailscaleServeLayer,
);
return serverApplicationLayer.pipe(
@@ -211,58 +211,6 @@ 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(
+1 -57
View File
@@ -1,10 +1,6 @@
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import {
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
} from "@t3tools/contracts";
import { TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import {
@@ -66,12 +62,6 @@ export interface GitHubCliShape {
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
@@ -170,43 +160,6 @@ function normalizeRepositoryCloneUrls(
};
}
/**
* `gh repo create` prints the canonical URL of the new repository on stdout
* (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
* follow-up `gh repo view`, which can race GitHub's GraphQL eventual
* consistency window and falsely report the just-created repo as missing.
*/
function deriveRepositoryCloneUrlsFromCreateOutput(
stdout: string,
repository: string,
): GitHubRepositoryCloneUrls {
const fallbackHost = "github.com";
const match = stdout.match(/https?:\/\/[^\s]+/);
if (match) {
const cleaned = match[0].replace(/\.git$/, "");
try {
const parsed = new URL(cleaned);
const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
const segments = pathname.split("/").filter(Boolean);
if (segments.length === 2) {
const nameWithOwner = `${segments[0]}/${segments[1]}`;
return {
nameWithOwner,
url: `${parsed.origin}/${nameWithOwner}`,
sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
};
}
} catch {
// Fall through to the input-derived defaults below.
}
}
return {
nameWithOwner: repository,
url: `https://${fallbackHost}/${repository}`,
sshUrl: `git@${fallbackHost}:${repository}.git`,
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
@@ -328,15 +281,6 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
),
Effect.map(normalizeRepositoryCloneUrls),
),
createRepository: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "create", input.repository, `--${input.visibility}`],
}).pipe(
Effect.map((result) =>
deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
),
),
createPullRequest: (input) =>
execute({
cwd: input.cwd,
@@ -130,10 +130,6 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
github
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
github
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
github
.getDefaultBranch(input)
@@ -175,7 +175,7 @@ layer("GitLabCli.layer", (it) => {
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/t3code",
url: "https://gitlab.com/octocat/t3code",
url: "https://gitlab.com/octocat/t3code.git",
sshUrl: "[email protected]:octocat/t3code.git",
});
}),
@@ -217,67 +217,6 @@ layer("GitLabCli.layer", (it) => {
}),
);
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("")));
+3 -79
View File
@@ -1,6 +1,6 @@
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import {
decodeGitLabMergeRequestJson,
@@ -66,12 +66,6 @@ export interface GitLabCliShape {
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;
@@ -167,16 +161,12 @@ 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,
url: raw.http_url_to_repo || raw.web_url,
sshUrl: raw.ssh_url_to_repo,
};
}
@@ -184,7 +174,7 @@ function normalizeRepositoryCloneUrls(
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
operation: "getRepositoryCloneUrls" | "getDefaultBranch",
invalidDetail: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
@@ -238,19 +228,6 @@ function toSummaryWithOptionalUpdatedAt(
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;
@@ -343,59 +320,6 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
),
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({
@@ -92,10 +92,6 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
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)
@@ -73,7 +73,7 @@ Logged in to github.com account juliusmarminge (keyring)
})),
[
{ kind: "git", implemented: true, status: "available" },
{ kind: "jj", implemented: false, status: "missing" },
{ kind: "jj", implemented: true, status: "missing" },
],
);
assert.deepStrictEqual(
@@ -115,9 +115,6 @@ Logged in to github.com account juliusmarminge (keyring)
},
],
);
const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
assert.ok(bitbucket);
assert.strictEqual("executable" in bitbucket, false);
}).pipe(Effect.provide(testLayer));
});
@@ -207,9 +204,9 @@ Logged in as bitbucket-user
},
{
kind: "bitbucket",
auth: "unknown",
account: Option.none(),
detail: Option.some("Bitbucket provider support is not available yet."),
auth: "authenticated",
account: Option.some("bitbucket-user"),
detail: Option.none(),
},
],
);
@@ -13,22 +13,20 @@ import * as VcsProcess from "../vcs/VcsProcess.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;
readonly authArgs: ReadonlyArray<string>;
readonly parseAuth: (input: AuthProbeInput) => SourceControlProviderAuth;
};
interface AuthProbeInput {
@@ -40,7 +38,7 @@ interface AuthProbeInput {
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>;
@@ -62,7 +60,7 @@ const VCS_PROBES: ReadonlyArray<VcsProbe> = [
label: "Jujutsu",
executable: "jj",
versionArgs: ["--version"],
implemented: false,
implemented: true,
installHint: "Install Jujutsu with `brew install jj` or from https://github.com/jj-vcs/jj.",
},
];
@@ -103,8 +101,12 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
{
kind: "bitbucket",
label: "Bitbucket",
executable: "bb",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseBitbucketAuth,
implemented: false,
installHint: "Bitbucket provider support is not available yet.",
installHint: "Install a Bitbucket CLI (`bb`) and authenticate it for your Bitbucket workspace.",
},
];
@@ -264,6 +266,37 @@ function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
});
}
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>;
}
@@ -281,27 +314,12 @@ export const layer = Layer.effect(
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
input: DiscoveryProbe & { readonly kind: Kind },
): 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
): Effect.Effect<DiscoveryProbeResult<Kind>> =>
process
.run({
operation: "source-control.discovery.probe",
command: executable,
args: versionArgs,
command: input.executable,
args: input.versionArgs,
cwd: config.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
@@ -313,7 +331,7 @@ export const layer = Layer.effect(
({
kind: input.kind,
label: input.label,
executable,
executable: input.executable,
implemented: input.implemented,
status: "available" as const,
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
@@ -327,7 +345,7 @@ export const layer = Layer.effect(
Effect.succeed({
kind: input.kind,
label: input.label,
executable,
executable: input.executable,
implemented: input.implemented,
status: "missing" as const,
version: Option.none<string>(),
@@ -336,22 +354,10 @@ export const layer = Layer.effect(
} satisfies DiscoveryProbeResult<Kind>),
),
);
};
const probeProvider = (input: ProviderProbe) =>
probe(input).pipe(
Effect.flatMap((item) => {
const executable = input.executable;
const authArgs = input.authArgs;
const parseAuth = input.parseAuth;
if (!executable || !authArgs || !parseAuth) {
return Effect.succeed({
...item,
auth: unknownAuth(input.installHint),
} satisfies SourceControlProviderDiscoveryItem);
}
if (item.status !== "available") {
return Effect.succeed({
...item,
@@ -362,8 +368,8 @@ export const layer = Layer.effect(
return process
.run({
operation: "source-control.discovery.auth",
command: executable,
args: authArgs,
command: input.executable,
args: input.authArgs,
cwd: config.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
@@ -375,7 +381,7 @@ export const layer = Layer.effect(
(result) =>
({
...item,
auth: parseAuth(result),
auth: input.parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
@@ -6,7 +6,6 @@ import type {
SourceControlProviderInfo,
SourceControlProviderKind,
SourceControlRepositoryCloneUrls,
SourceControlRepositoryVisibility,
} from "@t3tools/contracts";
export interface SourceControlProviderContext {
@@ -51,11 +50,6 @@ 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;
@@ -58,7 +58,6 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
getChangeRequest: () => unsupported("getChangeRequest"),
createChangeRequest: () => unsupported("createChangeRequest"),
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
createRepository: () => unsupported("createRepository"),
getDefaultBranch: () => unsupported("getDefaultBranch"),
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
});
@@ -1,322 +0,0 @@
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 {
GitVcsDriver,
type ExecuteGitResult,
type GitVcsDriverShape,
} from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
import type { SourceControlProviderShape } from "./SourceControlProvider.ts";
import { SourceControlRepositoryService, layer } from "./SourceControlRepositoryService.ts";
const CLONE_URLS = {
nameWithOwner: "octocat/t3code",
url: "https://github.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
};
function makeProvider(
overrides: Partial<SourceControlProviderShape> = {},
): 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(): ExecuteGitResult {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
function makeLayer(input: {
readonly provider?: SourceControlProviderShape;
readonly git?: Partial<GitVcsDriverShape>;
}) {
return layer.pipe(
Layer.provide(
Layer.mock(SourceControlProviderRegistry)({
get: () => Effect.succeed(input.provider ?? makeProvider()),
}),
),
Layer.provide(
Layer.mock(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;
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;
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;
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;
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;
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,
};
}),
},
}),
),
);
});
@@ -1,320 +0,0 @@
import OS 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 { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { 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 OS.homedir();
}
if (input.startsWith("~/") || input.startsWith("~\\")) {
return path.join(OS.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;
const path = yield* Path.Path;
const providers = yield* 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());
+2 -11
View File
@@ -1,4 +1,4 @@
import { Context, DateTime, Effect, Layer, Option } from "effect";
import { Context, Effect, Layer, Option } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -20,6 +20,7 @@ import {
} from "@t3tools/contracts";
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
import { nowFreshness } from "./VcsFreshness.ts";
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
export interface ExecuteGitInput {
@@ -165,7 +166,6 @@ export interface GitVcsDriverShape {
readonly pushCurrentBranch: (
cwd: string,
fallbackBranch: string | null,
options?: { readonly remoteName?: string | null },
) => Effect.Effect<GitPushResult, GitCommandError>;
readonly readRangeContext: (
cwd: string,
@@ -221,15 +221,6 @@ const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
"core.untrackedCache=false",
] as const;
const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {
const now = yield* DateTime.now;
return {
source: "live-local" as const,
observedAt: now,
expiresAt: Option.none(),
};
});
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
@@ -326,41 +326,5 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
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);
}),
);
});
});
+3 -19
View File
@@ -449,7 +449,7 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_exit") {
hookStartByChildKey.delete(childKey);
const code = traceRecord.success.exitCode;
const code = traceRecord.success.code;
const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
const now = yield* DateTime.now;
const durationMs = started
@@ -1341,6 +1341,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const status: GitVcsDriverShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
kind: "git" as const,
isRepo: details.isRepo,
hasPrimaryRemote: details.hasOriginRemote,
isDefaultRef: details.isDefaultBranch,
@@ -1431,7 +1432,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
});
const pushCurrentBranch: GitVcsDriverShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")(
function* (cwd, fallbackBranch, options) {
function* (cwd, fallbackBranch) {
const details = yield* statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
@@ -1443,23 +1444,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
);
}
const requestedRemoteName = options?.remoteName?.trim() || null;
if (requestedRemoteName) {
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, [
"push",
"-u",
requestedRemoteName,
`HEAD:refs/heads/${publishBranch}`,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: `${requestedRemoteName}/${publishBranch}`,
setUpstream: true,
};
}
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
if (hasNoLocalDelta) {
if (details.hasUpstream) {
+193
View File
@@ -0,0 +1,193 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { describe } from "vitest";
import type { VcsError } from "@t3tools/contracts";
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
import { VcsProcess, layer as VcsProcessLayer } from "./VcsProcess.ts";
import * as JjVcsDriver from "./JjVcsDriver.ts";
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
const JjContractLayer = JjVcsDriver.vcsLayer.pipe(
Layer.provideMerge(VcsProcessLayer),
Layer.provideMerge(NodeServices.layer),
);
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
calls.map((call) => [call.command].concat(call.args));
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(exitCode),
stdout,
stderr,
stdoutTruncated: false,
stderrTruncated: false,
});
const runJj = (cwd: string, args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const process = yield* VcsProcess;
yield* process.run({
operation: "JjVcsDriver.contract.jj",
command: "jj",
cwd,
args,
timeoutMs: 10_000,
});
});
type JjContractError = PlatformError.PlatformError | VcsError;
runVcsDriverContractSuite<VcsProcess, JjContractError>({
name: "JJ",
kind: "jj",
layer: JjContractLayer,
fixture: {
createRepo: (cwd) => runJj(cwd, ["git", "init", "--colocate"]),
writeFile: (cwd, relativePath, contents) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const absolutePath = path.join(cwd, relativePath);
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
yield* fileSystem.writeFileString(absolutePath, contents);
}),
ignorePath: (cwd, pattern) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
}),
},
});
describe("JjVcsDriver", () => {
it.effect("detects repository identity with jj root", () => {
const calls: VcsProcessInput[] = [];
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
const identity = yield* driver.detectRepository("/repo/src");
assert.equal(identity?.kind, "jj");
assert.equal(identity?.rootPath, "/repo");
assert.equal(identity?.metadataPath, "/repo/.jj");
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
return processOutput("/repo\n");
}),
}),
NodeServices.layer,
),
),
);
});
it.effect("lists workspace files using jj file list", () => {
let observedInput: VcsProcessInput | null = null;
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
const result = yield* driver.listWorkspaceFiles("/repo");
assert.deepStrictEqual(result.paths, ["README.md", "src/index.ts"]);
assert.deepStrictEqual(observedInput?.args, ["--no-pager", "file", "list"]);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedInput = input;
return processOutput("README.md\nsrc/index.ts\n");
}),
}),
NodeServices.layer,
),
),
);
});
it.effect("filters paths with the git ignore oracle", () => {
const calls: VcsProcessInput[] = [];
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
const result = yield* driver.filterIgnoredPaths("/repo", [
"keep.ts",
"debug.log",
"src/index.ts",
]);
assert.deepStrictEqual(result, ["keep.ts", "src/index.ts"]);
assert.equal(calls[0]?.command, "git");
assert.deepStrictEqual(calls[0]?.args.slice(-2), ["init", "--bare"]);
assert.equal(calls[1]?.command, "git");
assert.deepStrictEqual(calls[1]?.args.slice(-4), [
"check-ignore",
"--no-index",
"-z",
"--stdin",
]);
assert.equal(calls[1]?.stdin, "keep.ts\0debug.log\0src/index.ts\0");
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
if (input.command === "git" && input.args.includes("check-ignore")) {
return processOutput("debug.log\0");
}
return processOutput("");
}),
}),
NodeServices.layer,
),
),
);
});
it.effect("forwards execute env to the VCS process", () => {
let observedEnv: NodeJS.ProcessEnv | undefined;
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
yield* driver.execute({
operation: "JjVcsDriver.test.env",
cwd: "/repo",
args: ["status"],
env: {
JJ_CONFIG: "/tmp/t3-jj-config.toml",
},
});
assert.deepStrictEqual(observedEnv, {
JJ_CONFIG: "/tmp/t3-jj-config.toml",
});
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedEnv = input.env;
return processOutput("");
}),
}),
NodeServices.layer,
),
),
);
});
});
+517
View File
@@ -0,0 +1,517 @@
import { Context, Effect, FileSystem, Layer, Option } from "effect";
import { VcsOutputDecodeError, VcsProcessExitError, type VcsError } from "@t3tools/contracts";
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
import { nowFreshness } from "./VcsFreshness.ts";
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
export interface JjVcsDriverShape extends VcsDriverShape {
readonly capabilities: VcsDriverShape["capabilities"] & {
readonly kind: "jj";
readonly supportsBookmarks: true;
readonly supportsAtomicSnapshot: true;
readonly supportsWorktrees: false;
readonly ignoreClassifier: "git-compatible-fallback";
};
readonly currentChange: (cwd: string) => Effect.Effect<JjCurrentChange | null, VcsError>;
readonly listBookmarks: (cwd: string) => Effect.Effect<ReadonlyArray<JjBookmark>, VcsError>;
readonly listWorkspaces: (cwd: string) => Effect.Effect<ReadonlyArray<JjWorkspace>, VcsError>;
}
export interface JjCurrentChange {
readonly changeId: string;
readonly commitId: string | null;
readonly description: string | null;
}
export interface JjBookmark {
readonly name: string;
readonly target: string | null;
}
export interface JjWorkspace {
readonly name: string;
readonly path: string | null;
}
export class JjVcsDriver extends Context.Service<JjVcsDriver, JjVcsDriverShape>()(
"t3/vcs/JjVcsDriver",
) {}
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
if (truncated && parts[parts.length - 1]?.length) {
parts.pop();
}
return parts.filter((value) => value.length > 0);
}
function splitLineSeparatedPaths(input: string, truncated: boolean): string[] {
const lines = input.split(/\r?\n/g);
if (truncated && lines[lines.length - 1]?.length) {
lines.pop();
}
return lines.map((line) => line.trim()).filter((line) => line.length > 0);
}
function parseJjRemoteList(output: string): Array<{ name: string; url: string }> {
return output
.split(/\r?\n/g)
.map((line) => line.trim())
.flatMap((line) => {
if (line.length === 0) {
return [];
}
const [name, ...urlParts] = line.split(/\s+/g);
const url = urlParts.join(" ").trim();
return name && url ? [{ name, url }] : [];
});
}
function parseNullRecord(record: string): string[] {
return record.split("\0").map((value) => value.trim());
}
function decodeJjCurrentChange(raw: string, cwd: string): JjCurrentChange | null {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return null;
}
const [changeId, commitId, description] = parseNullRecord(trimmed);
if (!changeId) {
throw new VcsOutputDecodeError({
operation: "JjVcsDriver.currentChange",
command: "jj log",
cwd,
detail: "jj current change output did not include a change id",
});
}
return {
changeId,
commitId: commitId || null,
description: description || null,
};
}
function decodeJjBookmarkList(raw: string): ReadonlyArray<JjBookmark> {
return raw
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const [name, target] = parseNullRecord(line);
return {
name: name ?? line,
target: target || null,
};
});
}
function decodeJjWorkspaceList(raw: string): ReadonlyArray<JjWorkspace> {
return raw
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const [name, path] = parseNullRecord(line);
return {
name: name ?? line,
path: path || null,
};
});
}
function chunkPathsForCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
const chunks: string[][] = [];
let chunk: string[] = [];
let chunkBytes = 0;
for (const relativePath of relativePaths) {
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
if (chunk.length > 0 && chunkBytes + relativePathBytes > CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
chunk.push(relativePath);
chunkBytes += relativePathBytes;
if (chunkBytes >= CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
}
if (chunk.length > 0) {
chunks.push(chunk);
}
return chunks;
}
const processCommand = (
process: VcsProcessShape,
command: string,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: {
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
},
) =>
process.run({
operation,
command,
args,
cwd,
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
...(options?.env !== undefined ? { env: options.env } : {}),
...(options?.allowNonZeroExit !== undefined
? { allowNonZeroExit: options.allowNonZeroExit }
: {}),
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
...(options?.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
: {}),
});
const jjCommand = (
process: VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: {
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
},
) => processCommand(process, "jj", operation, cwd, ["--no-pager", ...args], options);
const gitCommand = (
process: VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: Parameters<typeof processCommand>[5],
) => processCommand(process, "git", operation, cwd, args, options);
function fileSystemError(operation: string, cwd: string, detail: string, cause: unknown) {
return new VcsOutputDecodeError({
operation,
command: "git check-ignore",
cwd,
detail,
cause,
});
}
const makeScopedTempGitDir = (fileSystem: FileSystem.FileSystem, operation: string, cwd: string) =>
fileSystem
.makeTempDirectoryScoped({ prefix: "t3-jj-check-ignore-" })
.pipe(
Effect.mapError((cause) =>
fileSystemError(operation, cwd, "failed to create temp git dir", cause),
),
);
export const makeVcsDriverShape = Effect.fn("makeJjVcsDriverShape")(function* () {
const process = yield* VcsProcess;
const fileSystem = yield* FileSystem.FileSystem;
const capabilities = {
kind: "jj" as const,
supportsWorktrees: false as const,
supportsBookmarks: true as const,
supportsAtomicSnapshot: true as const,
supportsPushDefaultRemote: false as const,
ignoreClassifier: "git-compatible-fallback" as const,
};
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
jjCommand(process, "JjVcsDriver.isInsideWorkTree", cwd, ["root"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 4_096,
}).pipe(
Effect.map((result) => result.exitCode === 0 && result.stdout.trim().length > 0),
Effect.catch(() => Effect.succeed(false)),
);
const execute: VcsDriverShape["execute"] = (input) =>
jjCommand(process, input.operation, input.cwd, input.args, {
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.env !== undefined ? { env: input.env } : {}),
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
...(input.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
: {}),
});
const initRepository: VcsDriverShape["initRepository"] = (input) =>
jjCommand(process, "JjVcsDriver.initRepository", input.cwd, ["git", "init"]);
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
function* (cwd) {
const root = yield* jjCommand(process, "JjVcsDriver.detectRepository.root", cwd, ["root"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 4_096,
}).pipe(Effect.catch(() => Effect.succeed(null)));
if (!root || root.exitCode !== 0) {
return null;
}
const rootPath = root.stdout.trim();
if (rootPath.length === 0) {
return null;
}
return {
kind: "jj" as const,
rootPath,
metadataPath: `${rootPath.replace(/[\\/]$/g, "")}/.jj`,
freshness: yield* nowFreshness(),
};
},
);
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
jjCommand(process, "JjVcsDriver.listWorkspaceFiles", cwd, ["file", "list"], {
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
}).pipe(
Effect.flatMap((result) =>
result.exitCode === 0
? Effect.gen(function* () {
return {
paths: splitLineSeparatedPaths(result.stdout, result.stdoutTruncated),
truncated: result.stdoutTruncated,
freshness: yield* nowFreshness(),
};
})
: Effect.fail(
new VcsProcessExitError({
operation: "JjVcsDriver.listWorkspaceFiles",
command: "jj file list",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "jj file list failed",
}),
),
),
);
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
const result = yield* jjCommand(
process,
"JjVcsDriver.listRemotes",
cwd,
["git", "remote", "list"],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
},
);
if (result.exitCode !== 0) {
return {
remotes: [],
freshness: yield* nowFreshness(),
};
}
return {
remotes: parseJjRemoteList(result.stdout).map((remote) => ({
name: remote.name,
url: remote.url,
pushUrl: Option.none(),
isPrimary: remote.name === "origin",
})),
freshness: yield* nowFreshness(),
};
});
const currentChange: JjVcsDriverShape["currentChange"] = (cwd) =>
jjCommand(
process,
"JjVcsDriver.currentChange",
cwd,
[
"log",
"-r",
"@",
"--no-graph",
"--template",
'change_id ++ "\\0" ++ commit_id ++ "\\0" ++ description.first_line()',
],
{
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
},
).pipe(Effect.map((result) => decodeJjCurrentChange(result.stdout, cwd)));
const listBookmarks: JjVcsDriverShape["listBookmarks"] = (cwd) =>
jjCommand(
process,
"JjVcsDriver.listBookmarks",
cwd,
["bookmark", "list", "--template", 'name ++ "\\0" ++ target.commit_id() ++ "\\n"'],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 256 * 1024,
},
).pipe(
Effect.map((result) => (result.exitCode === 0 ? decodeJjBookmarkList(result.stdout) : [])),
);
const listWorkspaces: JjVcsDriverShape["listWorkspaces"] = (cwd) =>
jjCommand(
process,
"JjVcsDriver.listWorkspaces",
cwd,
["workspace", "list", "--template", 'name ++ "\\0" ++ root ++ "\\n"'],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 256 * 1024,
},
).pipe(
Effect.map((result) => (result.exitCode === 0 ? decodeJjWorkspaceList(result.stdout) : [])),
);
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
function* (cwd, relativePaths) {
if (relativePaths.length === 0) {
return relativePaths;
}
const operation = "JjVcsDriver.filterIgnoredPaths";
const ignoredPaths = new Set<string>();
yield* Effect.scoped(
Effect.gen(function* () {
const gitDir = yield* makeScopedTempGitDir(fileSystem, operation, cwd);
const initResult = yield* gitCommand(
process,
operation,
cwd,
["--git-dir", gitDir, "init", "--bare"],
{
allowNonZeroExit: true,
},
);
if (initResult.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation,
command: "git init --bare",
cwd,
exitCode: initResult.exitCode,
detail: initResult.stderr.trim() || "git init --bare failed",
});
}
for (const chunk of chunkPathsForCheckIgnore(relativePaths)) {
const result = yield* gitCommand(
process,
operation,
cwd,
[
"--git-dir",
gitDir,
"--work-tree",
cwd,
"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,
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 {
capabilities,
execute,
initRepository,
detectRepository,
isInsideWorkTree,
listWorkspaceFiles,
listRemotes,
filterIgnoredPaths,
currentChange,
listBookmarks,
listWorkspaces,
} satisfies JjVcsDriverShape;
});
export const makeJjVcsDriver = Effect.fn("makeJjVcsDriver")(function* () {
const driver = yield* makeVcsDriverShape();
return JjVcsDriver.of(driver);
});
export const makeVcsDriver = Effect.fn("makeJjGenericVcsDriver")(function* () {
const driver = yield* makeVcsDriverShape();
return VcsDriver.of(driver);
});
export const layer = Layer.effect(JjVcsDriver, makeJjVcsDriver());
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
+80 -3
View File
@@ -1,3 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -7,10 +8,13 @@ import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "./VcsPr
import { VcsProjectConfig } from "./VcsProjectConfig.ts";
import { VcsDriverRegistry, make as makeVcsDriverRegistry } from "./VcsDriverRegistry.ts";
const processOutput = (stdout: string): VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
calls.map((call) => [call.command].concat(call.args));
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(exitCode),
stdout,
stderr: "",
stderr,
stdoutTruncated: false,
stderrTruncated: false,
});
@@ -28,6 +32,7 @@ describe("VcsDriverRegistry", () => {
run: () => Effect.succeed(processOutput("")),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
@@ -65,6 +70,7 @@ describe("VcsDriverRegistry", () => {
}),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
@@ -84,4 +90,75 @@ describe("VcsDriverRegistry", () => {
);
}).pipe(Effect.provide(layer));
});
it.effect("resolves an explicitly requested jj repository", () => {
const calls: VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
const command = input.args.join(" ");
if (input.command === "jj" && command === "--no-pager root") {
return processOutput("/repo\n");
}
return processOutput("", 1, "not found");
}),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const handle = yield* registry.resolve({ cwd: "/repo", requestedKind: "jj" });
assert.equal(handle.kind, "jj");
assert.equal(handle.repository.rootPath, "/repo");
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
}).pipe(Effect.provide(layer));
});
it.effect("prefers jj auto-detection before git for colocated repositories", () => {
const calls: VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
const command = input.args.join(" ");
if (input.command === "jj" && command === "--no-pager root") {
return processOutput("/repo\n");
}
if (input.command === "git") {
return processOutput("true\n");
}
return processOutput("", 1, "not found");
}),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const handle = yield* registry.resolve({ cwd: "/repo" });
assert.equal(handle.kind, "jj");
assert.equal(handle.repository.rootPath, "/repo");
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
}).pipe(Effect.provide(layer));
});
});
+8
View File
@@ -3,6 +3,7 @@ import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import * as JjVcsDriver from "./JjVcsDriver.ts";
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
import type { VcsDriverShape } from "./VcsDriver.ts";
@@ -66,8 +67,10 @@ function parseDetectionCacheKey(key: string): {
export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
const git = yield* GitVcsDriver.makeVcsDriverShape();
const jj = yield* JjVcsDriver.makeVcsDriverShape();
const drivers: Partial<Record<VcsDriverKind, VcsDriverShape>> = {
git,
jj,
};
const get: VcsDriverRegistryShape["get"] = (kind) => {
@@ -107,6 +110,11 @@ export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
return yield* detectWithDriver(requestedKind, driver, input.cwd);
}
const jjDetected = yield* detectWithDriver("jj", jj, input.cwd);
if (jjDetected) {
return jjDetected;
}
return yield* detectWithDriver("git", git, input.cwd);
});
+10
View File
@@ -0,0 +1,10 @@
import { DateTime, Effect, Option } from "effect";
export const nowFreshness = Effect.fn("VcsFreshness.nowFreshness")(function* () {
const now = yield* DateTime.now;
return {
source: "live-local" as const,
observedAt: now,
expiresAt: Option.none(),
};
});
@@ -16,6 +16,7 @@ import {
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
const baseLocalStatus: VcsStatusLocalResult = {
kind: "git",
isRepo: true,
sourceControlProvider: {
kind: "github",
@@ -49,29 +50,30 @@ function makeTestLayer(state: {
localInvalidationCalls: number;
remoteInvalidationCalls: number;
}) {
return VcsStatusBroadcasterLayer.pipe(
Layer.provide(
Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
});
return VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
}
@@ -188,31 +190,31 @@ describe("VcsStatusBroadcaster", () => {
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>);
const testLayer = VcsStatusBroadcasterLayer.pipe(
Layer.provide(
Layer.mock(GitWorkflowService)({
localStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>),
),
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
return Effect.gen(function* () {
@@ -235,7 +237,7 @@ describe("VcsStatusBroadcaster", () => {
assert.deepStrictEqual(seenCwds, [realPath, realPath]);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
}).pipe(Effect.provide(Layer.mergeAll(testLayer, NodeServices.layer)));
}).pipe(Effect.provide(testLayer));
});
it.effect("streams a local snapshot first and remote updates later", () => {
@@ -289,40 +291,40 @@ describe("VcsStatusBroadcaster", () => {
};
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>);
const testLayer = VcsStatusBroadcasterLayer.pipe(
Layer.provide(
Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>),
),
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
return Effect.gen(function* () {
+9 -14
View File
@@ -1,9 +1,8 @@
import { realpathSync } from "node:fs";
import {
Duration,
Effect,
Exit,
FileSystem,
Fiber,
Layer,
PubSub,
@@ -69,18 +68,11 @@ function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
export const layer = Layer.effect(
VcsStatusBroadcaster,
Effect.gen(function* () {
const workflow = yield* GitWorkflowService;
const fileSystem = yield* FileSystem.FileSystem;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<VcsStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
@@ -91,6 +83,9 @@ export const layer = Layer.effect(
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const normalizeCwd = (cwd: string) =>
fileSystem.realPath(cwd).pipe(Effect.catch(() => Effect.succeed(cwd)));
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
cwd: string,
) {
@@ -198,7 +193,7 @@ export const layer = Layer.effect(
const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
"VcsStatusBroadcaster.getStatus",
)(function* (input) {
const cwd = normalizeCwd(input.cwd);
const cwd = yield* normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(cwd),
getOrLoadRemoteStatus(cwd),
@@ -209,7 +204,7 @@ export const layer = Layer.effect(
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshLocalStatus",
)(function* (rawCwd) {
const cwd = normalizeCwd(rawCwd);
const cwd = yield* normalizeCwd(rawCwd);
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
@@ -226,7 +221,7 @@ export const layer = Layer.effect(
const refreshStatus: VcsStatusBroadcasterShape["refreshStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = normalizeCwd(rawCwd);
const cwd = yield* normalizeCwd(rawCwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(cwd),
refreshRemoteStatus(cwd),
@@ -312,7 +307,7 @@ export const layer = Layer.effect(
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const cwd = normalizeCwd(input.cwd);
const cwd = yield* normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
@@ -56,9 +56,11 @@ export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInp
yield* input.fixture.createRepo(cwd);
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
const fileSystem = yield* FileSystem.FileSystem;
const realCwd = yield* fileSystem.realPath(cwd);
const identity = yield* driver.detectRepository(cwd);
assert.equal(identity?.kind, input.kind);
assert.isTrue(identity?.rootPath.endsWith(cwd));
assert.isTrue(identity?.rootPath.endsWith(realCwd));
assert.equal(identity?.freshness.source, "live-local");
assert.isTrue(DateTime.isDateTime(identity?.freshness.observedAt));
assert.isTrue(Option.isNone(identity?.freshness.expiresAt ?? Option.none()));
-32
View File
@@ -55,7 +55,6 @@ 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 VcsProcess from "./vcs/VcsProcess.ts";
import {
BootstrapCredentialService,
@@ -155,7 +154,6 @@ 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) =>
@@ -672,9 +670,6 @@ 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({
@@ -799,32 +794,6 @@ 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,
@@ -1020,7 +989,6 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
version: 1 as const,
type: "keybindingsUpdated" as const,
payload: {
keybindings: event.keybindings,
issues: event.issues,
},
})),
@@ -10,12 +10,6 @@ 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 {
+3 -14
View File
@@ -19,14 +19,6 @@ 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;
@@ -45,7 +37,7 @@ function hasWindow(): boolean {
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
const nextRecord = {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -53,7 +45,6 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readBrowserClientSettings(): ClientSettings | null {
@@ -144,7 +135,6 @@ export function writeBrowserSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
bearerToken,
}
: toPersistedSavedEnvironmentRecord(record);
@@ -176,7 +166,7 @@ export function writeBrowserSavedEnvironmentSecret(
return record;
}
found = true;
const nextRecord = {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -184,8 +174,7 @@ export function writeBrowserSavedEnvironmentSecret(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken: secret,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
} satisfies BrowserSavedEnvironmentRecord;
}),
});
return found;
+13 -29
View File
@@ -80,6 +80,8 @@ 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
@@ -91,34 +93,6 @@ 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>
@@ -126,7 +100,17 @@ 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"
>
{triggerContent}
{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>
</>
)}
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</MenuTrigger>
<MenuPopup align="start" side="top" className="w-64">
@@ -24,6 +24,7 @@ import { parsePullRequestReference } from "../pullRequestReference";
import { getSourceControlPresentation } from "../sourceControlPresentation";
import { useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { resolveVcsTerms } from "../vcsPresentation";
import {
deriveLocalBranchNameFromRemoteRef,
resolveBranchSelectionTarget,
@@ -67,10 +68,11 @@ function getBranchTriggerLabel(input: {
activeWorktreePath: string | null;
effectiveEnvMode: "local" | "worktree";
resolvedActiveBranch: string | null;
refNoun: string;
}): string {
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch, refNoun } = input;
if (!resolvedActiveBranch) {
return "Select ref";
return `Select ${refNoun}`;
}
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
return `From ${resolvedActiveBranch}`;
@@ -202,6 +204,7 @@ export function BranchToolbarBranchSelector({
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
const vcsTerms = resolveVcsTerms(branchStatusQuery.data?.kind);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
@@ -295,11 +298,11 @@ export function BranchToolbarBranchSelector({
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
const branchStatusText = isBranchesSearchPending
? "Loading refs..."
? `Loading ${vcsTerms.refNounPlural}...`
: isFetchingNextPage
? "Loading more refs..."
? `Loading more ${vcsTerms.refNounPlural}...`
: hasNextPage
? `Showing ${refs.length} of ${totalBranchCount} refs`
? `Showing ${refs.length} of ${totalBranchCount} ${vcsTerms.refNounPlural}`
: null;
// ---------------------------------------------------------------------------
@@ -363,7 +366,7 @@ export function BranchToolbarBranchSelector({
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to switch ref.",
title: `Failed to switch ${vcsTerms.refNoun}.`,
description: toBranchActionErrorMessage(error),
}),
);
@@ -395,7 +398,7 @@ export function BranchToolbarBranchSelector({
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to create and switch ref.",
title: `Failed to create and switch ${vcsTerms.refNoun}.`,
description: toBranchActionErrorMessage(error),
}),
);
@@ -494,6 +497,7 @@ export function BranchToolbarBranchSelector({
activeWorktreePath,
effectiveEnvMode,
resolvedActiveBranch,
refNoun: vcsTerms.refNoun,
});
function renderPickerItem(itemValue: string, index: number) {
@@ -535,7 +539,9 @@ export function BranchToolbarBranchSelector({
value={itemValue}
onClick={() => createRef(trimmedBranchQuery)}
>
<span className="truncate">Create new ref &quot;{trimmedBranchQuery}&quot;</span>
<span className="truncate">
Create new {vcsTerms.refNoun} &quot;{trimmedBranchQuery}&quot;
</span>
</ComboboxItem>
);
}
+6 -195
View File
@@ -206,7 +206,6 @@ function createMockEnvironmentApi(input: {
filesystem: {
browse: input.browse,
},
sourceControl: {} as EnvironmentApi["sourceControl"],
vcs: {} as EnvironmentApi["vcs"],
git: {} as EnvironmentApi["git"],
orchestration: {
@@ -1663,74 +1662,6 @@ 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: {
@@ -4326,7 +4257,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
@@ -4378,7 +4310,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
await waitForServerConfigToApply();
await waitForCommandPaletteShortcutLabel();
const palette = page.getByTestId("command-palette");
await openCommandPaletteFromTrigger();
@@ -4451,13 +4384,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]);
await waitForServerConfigToApply();
await 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/");
@@ -4504,126 +4437,6 @@ 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,
@@ -4976,7 +4789,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
await expect.element(palette).toBeInTheDocument();
await palette.getByText("Add project", { exact: true }).click();
await palette.getByText("Local folder", { exact: true }).click();
await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument();
await expect
.element(palette.getByText("This device", { exact: true }).first())
@@ -5192,7 +5004,6 @@ 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/");
+83 -361
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, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
import { ChevronDownIcon } from "lucide-react";
import { cn, randomUUID } from "~/lib/utils";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
@@ -121,7 +121,6 @@ import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import {
reconnectSavedEnvironment,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
@@ -149,7 +148,6 @@ 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,
@@ -182,13 +180,6 @@ 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).]";
@@ -196,11 +187,6 @@ 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">;
@@ -869,78 +855,6 @@ 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,
@@ -1141,120 +1055,6 @@ 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,
@@ -1658,7 +1458,8 @@ export default function ChatView(props: ChatViewProps) {
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const vcsKind = gitStatusQuery.data?.kind ?? null;
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -2336,7 +2137,7 @@ export default function ChatView(props: ChatViewProps) {
: (activeThread?.branch ?? null);
const sendEnvMode = resolveSendEnvMode({
requestedEnvMode: envMode,
isGitRepo,
isGitRepo: isVcsRepo,
});
useEffect(() => {
@@ -2554,13 +2355,6 @@ 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;
@@ -2596,8 +2390,6 @@ export default function ChatView(props: ChatViewProps) {
},
[
activeThread,
activeEnvironmentUnavailable,
activeEnvironmentUnavailableLabel,
environmentId,
isConnecting,
isRevertingCheckpoint,
@@ -2610,15 +2402,7 @@ export default function ChatView(props: ChatViewProps) {
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const api = readEnvironmentApi(environmentId);
if (
!api ||
!activeThread ||
isSendBusy ||
isConnecting ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
)
return;
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (activePendingProgress) {
onAdvanceActivePendingUserInput();
return;
@@ -3239,7 +3023,6 @@ export default function ChatView(props: ChatViewProps) {
!isServerThread ||
isSendBusy ||
isConnecting ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
) {
return;
@@ -3354,7 +3137,6 @@ export default function ChatView(props: ChatViewProps) {
activeThreadBranch,
activeThread,
beginLocalDispatch,
activeEnvironmentUnavailable,
isConnecting,
isSendBusy,
isServerThread,
@@ -3489,62 +3271,6 @@ export default function ChatView(props: ChatViewProps) {
}
void onRevertToTurnCountRef.current(targetTurnCount);
}, []);
const activeThreadValueRef = useRef(activeThread);
activeThreadValueRef.current = activeThread;
const onBranchAssistantMessage = useCallback(
async (messageId: MessageId) => {
const thread = activeThreadValueRef.current;
if (!thread || !isServerThread) {
return;
}
if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
setThreadError(
thread.id,
`Reconnect ${activeEnvironmentUnavailableLabel} before branching this message.`,
);
return;
}
const api = readEnvironmentApi(thread.environmentId);
if (!api) {
setThreadError(thread.id, "Thread API unavailable.");
return;
}
const branchThreadId = newThreadId();
try {
await api.orchestration.dispatchCommand({
type: "thread.branch",
commandId: newCommandId(),
sourceThreadId: thread.id,
sourceMessageId: messageId,
threadId: branchThreadId,
title: `${thread.title} (Branched)`,
createdAt: new Date().toISOString(),
});
await navigate({
to: "/$environmentId/$threadId",
params: {
environmentId: thread.environmentId,
threadId: branchThreadId,
},
});
} catch (error) {
setThreadError(
thread.id,
error instanceof Error ? error.message : "Failed to branch from this message.",
);
}
},
[
activeEnvironmentUnavailable,
activeEnvironmentUnavailableLabel,
isServerThread,
navigate,
setThreadError,
],
);
// Empty state: no active thread
if (!activeThread) {
@@ -3572,7 +3298,8 @@ export default function ChatView(props: ChatViewProps) {
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
isGitRepo={isGitRepo}
isVcsRepo={isVcsRepo}
vcsKind={vcsKind}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
@@ -3624,7 +3351,6 @@ export default function ChatView(props: ChatViewProps) {
onOpenTurnDiff={onOpenTurnDiff}
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
onRevertUserMessage={onRevertUserMessage}
onBranchAssistantMessage={onBranchAssistantMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
markdownCwd={gitCwd ?? undefined}
@@ -3653,88 +3379,80 @@ export default function ChatView(props: ChatViewProps) {
<div
className={cn(
"pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-1.5 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-2",
isGitRepo
isVcsRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
<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 && (
<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}
/>
{isVcsRepo && (
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
@@ -3752,8 +3470,12 @@ export default function ChatView(props: ChatViewProps) {
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
{...(hasMultipleEnvironments
? {
availableEnvironments: logicalProjectEnvironments,
onEnvironmentChange,
}
: {})}
/>
)}
</div>
+44 -538
View File
@@ -7,8 +7,6 @@ import {
type FilesystemBrowseResult,
type ProjectId,
ProviderInstanceId,
type SourceControlProviderKind,
type SourceControlRepositoryInfo,
} from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
@@ -19,7 +17,6 @@ import {
CornerLeftUpIcon,
FolderIcon,
FolderPlusIcon,
LinkIcon,
MessageSquareIcon,
SettingsIcon,
SquarePenIcon,
@@ -92,7 +89,6 @@ import {
} from "./CommandPalette.logic";
import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { GitHubIcon, GitLabIcon } from "./Icons";
import { ProjectFavicon } from "./ProjectFavicon";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { useServerKeybindings } from "../rpc/serverState";
@@ -143,70 +139,6 @@ interface AddProjectEnvironmentOption {
readonly isPrimary: boolean;
}
type AddProjectRemoteProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
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> = ["github", "gitlab", "url"];
function remoteProjectSourceLabel(source: AddProjectRemoteSource): string {
switch (source) {
case "github":
return "GitHub";
case "gitlab":
return "GitLab";
case "url":
return "Git 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 "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 (owner/repo)`;
}
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);
@@ -295,9 +227,6 @@ 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);
@@ -366,10 +295,7 @@ function OpenCommandPaletteDialog() {
: null;
return getEnvironmentBrowsePlatform(os);
}, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]);
const isRemoteProjectCloneFlow = addProjectCloneFlow !== null;
const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
const isBrowsing =
!isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
const isBrowsing = isFilesystemBrowseQuery(query, browseEnvironmentPlatform);
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
const getAddProjectInitialQueryForEnvironment = useCallback(
(environmentId: EnvironmentId | null): string => {
@@ -615,7 +541,6 @@ function OpenCommandPaletteDialog() {
}
function popView(): void {
setAddProjectCloneFlow(null);
if (viewStack.length <= 1) {
setAddProjectEnvironmentId(null);
}
@@ -635,7 +560,6 @@ function OpenCommandPaletteDialog() {
const startAddProjectBrowse = useCallback(
(environmentId: EnvironmentId): void => {
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow(null);
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: [],
@@ -645,19 +569,6 @@ 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 addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
(option) => ({
kind: "action",
@@ -684,156 +595,6 @@ function OpenCommandPaletteDialog() {
[addProjectEnvironmentItems],
);
const addProjectRemoteEnvironmentGroups = useMemo<
Record<AddProjectRemoteSource, CommandPaletteView["groups"]>
>(() => {
const buildGroups = (source: AddProjectRemoteSource): CommandPaletteView["groups"] => [
{
value: `environments:${source}`,
label: "Environments",
items: addProjectEnvironmentOptions.map((option) => ({
kind: "action" as const,
value: `action:add-project:${source}:environment:${option.environmentId}`,
searchTerms: [
option.label,
option.environmentId,
option.isPrimary ? "this device" : "",
remoteProjectSourceLabel(source),
],
title: option.label,
description: option.isPrimary ? "This device" : option.environmentId,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
keepOpen: true,
run: async () => {
startAddProjectClone(option.environmentId, source);
},
})),
},
];
return {
github: buildGroups("github"),
gitlab: buildGroups("gitlab"),
url: buildGroups("url"),
};
}, [addProjectEnvironmentOptions, startAddProjectClone]);
const openAddProjectCloneFlow = useCallback(
(source: AddProjectRemoteSource) => {
if (addProjectEnvironmentOptions.length > 1) {
pushPaletteView({
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
groups: addProjectRemoteEnvironmentGroups[source],
});
return;
}
const environmentId = defaultAddProjectEnvironmentId;
if (!environmentId) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to clone project",
description: "No environment is available.",
}),
);
return;
}
startAddProjectClone(environmentId, source);
},
[
addProjectEnvironmentOptions.length,
addProjectRemoteEnvironmentGroups,
defaultAddProjectEnvironmentId,
startAddProjectClone,
],
);
const addProjectSourceGroups = useMemo<CommandPaletteView["groups"]>(() => {
const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
if (addProjectEnvironmentOptions.length > 1) {
sourceItems.push({
kind: "submenu",
value: "action:add-project:local",
searchTerms: ["local", "folder", "directory", "browse", "environment"],
title: "Local folder",
description: "Browse a folder on disk",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
});
} else {
sourceItems.push({
kind: "action",
value: "action:add-project:local",
searchTerms: ["local", "folder", "directory", "browse"],
title: "Local folder",
description: "Browse a folder on disk",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
const environmentId = defaultAddProjectEnvironmentId;
if (!environmentId) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to browse projects",
description: "No environment is available.",
}),
);
return;
}
startAddProjectBrowse(environmentId);
},
});
}
for (const source of REMOTE_PROJECT_SOURCES) {
const label = remoteProjectSourceLabel(source);
const title = source === "url" ? "Git URL" : `${label} repository`;
const description =
source === "url" ? "Clone from a remote URL" : `Clone ${label} owner/repo`;
if (addProjectEnvironmentOptions.length > 1) {
sourceItems.push({
kind: "submenu",
value: `action:add-project:${source}`,
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
title,
description,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
groups: addProjectRemoteEnvironmentGroups[source],
});
continue;
}
sourceItems.push({
kind: "action",
value: `action:add-project:${source}`,
searchTerms: ["clone", "remote", "repository", "repo", "git", label],
title,
description,
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
keepOpen: true,
run: async () => {
openAddProjectCloneFlow(source);
},
});
}
return [{ value: "sources", label: "Sources", items: sourceItems }];
}, [
addProjectEnvironmentGroups,
addProjectEnvironmentOptions.length,
addProjectRemoteEnvironmentGroups,
defaultAddProjectEnvironmentId,
openAddProjectCloneFlow,
startAddProjectBrowse,
]);
const openAddProjectFlow = useCallback(() => {
if (addProjectEnvironmentOptions.length > 1) {
pushPaletteView({
@@ -913,29 +674,29 @@ function OpenCommandPaletteDialog() {
});
}
actionItems.push({
kind: "submenu",
value: "action:add-project",
searchTerms: [
"add project",
"folder",
"directory",
"browse",
"clone",
"remote",
"repository",
"repo",
"git",
"github",
"gitlab",
"url",
"environment",
],
title: "Add project",
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectSourceGroups,
});
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",
@@ -1059,137 +820,6 @@ 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);
@@ -1228,38 +858,13 @@ function OpenCommandPaletteDialog() {
browseUp,
browseTo,
});
const cloneDestinationBrowseGroups = useMemo(
() =>
browseGroups.map((group) =>
group.value === "directories" ? { ...group, label: "Select where to clone" } : group,
),
[browseGroups],
);
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) {
let displayedGroups = filteredGroups;
if (isBrowsing) {
displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups;
}
const inputPlaceholder =
remoteProjectInputPlaceholder(addProjectCloneFlow) ??
getCommandPaletteInputPlaceholder(paletteMode);
const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse";
const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false;
const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject;
@@ -1271,25 +876,8 @@ function OpenCommandPaletteDialog() {
(hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null);
const useMetaForMod = isMacPlatform(navigator.platform);
const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl";
const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm";
const submitActionLabel = isCloneDestinationStep
? willCreateProjectPath
? "Create & Clone"
: "Clone"
: willCreateProjectPath
? "Create & Add"
: "Add";
const submitActionLabel = 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 &&
@@ -1327,12 +915,6 @@ 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" &&
@@ -1340,11 +922,7 @@ function OpenCommandPaletteDialog() {
if (shouldSubmitBrowsePath) {
event.preventDefault();
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
void handleAddProject(resolvedAddProjectPath);
return;
}
@@ -1421,9 +999,9 @@ function OpenCommandPaletteDialog() {
}}
>
<Command
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}-${addProjectCloneFlow?.step ?? "none"}`}
key={`${viewStack.length}-${browseGeneration}-${isBrowsing}`}
aria-label="Command palette"
autoHighlight={isBrowsing || isRemoteProjectCloneFlow ? false : "always"}
autoHighlight={isBrowsing ? false : "always"}
mode="none"
onItemHighlighted={(value) => {
setHighlightedItemValue(typeof value === "string" ? value : null);
@@ -1433,15 +1011,7 @@ function OpenCommandPaletteDialog() {
>
<div className="relative">
<CommandInput
className={
addProjectCloneFlow?.step === "repository"
? "pe-32"
: isBrowsing
? willCreateProjectPath
? "pe-36"
: "pe-16"
: undefined
}
className={isBrowsing ? (willCreateProjectPath ? "pe-36" : "pe-16") : undefined}
placeholder={inputPlaceholder}
wrapperClassName={
isSubmenu ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto" : undefined
@@ -1466,28 +1036,7 @@ function OpenCommandPaletteDialog() {
: {})}
onKeyDown={handleKeyDown}
/>
{addProjectCloneFlow?.step === "repository" ? (
<Button
variant="outline"
size="xs"
tabIndex={-1}
className="absolute end-2.5 top-1/2 gap-1.5 pe-1 ps-2 -translate-y-1/2"
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 ? (
{isBrowsing ? (
<Button
variant="outline"
size="xs"
@@ -1497,9 +1046,7 @@ function OpenCommandPaletteDialog() {
hasHighlightedBrowseItem ? "gap-1" : "gap-1.5",
)}
aria-label={`${submitActionLabel} (${addShortcutLabel})`}
disabled={
relativePathNeedsActiveProject || (isCloneDestinationStep && isRemoteProjectPending)
}
disabled={relativePathNeedsActiveProject}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -1507,17 +1054,11 @@ function OpenCommandPaletteDialog() {
if (relativePathNeedsActiveProject) {
return;
}
if (isCloneDestinationStep) {
void submitAddProjectCloneFlow(resolvedAddProjectPath);
} else {
void handleAddProject(resolvedAddProjectPath);
}
void handleAddProject(resolvedAddProjectPath);
}}
title={`${submitActionLabel} (${addShortcutLabel})`}
>
<span>
{isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel}
</span>
<span>{submitActionLabel}</span>
<KbdGroup className="pointer-events-none -me-0.5 items-center gap-1">
<Kbd>{hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"}</Kbd>
</KbdGroup>
@@ -1525,47 +1066,19 @@ 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}
{...(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.",
}
: {})}
{...(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">
@@ -1579,14 +1092,7 @@ function OpenCommandPaletteDialog() {
</Kbd>
<span className={cn("text-muted-foreground/80")}>Navigate</span>
</KbdGroup>
{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 ? (
{!canSubmitBrowsePath || hasHighlightedBrowseItem ? (
<KbdGroup className="items-center gap-1.5">
<Kbd>Enter</Kbd>
<span className={cn("text-muted-foreground/80")}>Select</span>
+7 -21
View File
@@ -8,7 +8,6 @@ import {
ChevronLeftIcon,
ChevronRightIcon,
Columns2Icon,
PilcrowIcon,
Rows3Icon,
TextWrapIcon,
} from "lucide-react";
@@ -36,6 +35,7 @@ import { createThreadSelectorByRef } from "../storeSelectors";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { resolveVcsTerms } from "../vcsPresentation";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
@@ -173,7 +173,6 @@ 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);
@@ -203,7 +202,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
environmentId: activeThread?.environmentId ?? null,
cwd: activeCwd ?? null,
});
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
const vcsTerms = resolveVcsTerms(gitStatusQuery.data?.kind);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -279,9 +279,8 @@ 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,
enabled: isVcsRepo,
}),
);
const selectedTurnCheckpointDiff = selectedTurn
@@ -320,10 +319,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
useEffect(() => {
if (diffOpen && !previousDiffOpenRef.current) {
setDiffWordWrap(settings.diffWordWrap);
setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace);
}
previousDiffOpenRef.current = diffOpen;
}, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]);
}, [diffOpen, settings.diffWordWrap]);
useEffect(() => {
if (!selectedFilePath || !patchViewportRef.current) {
@@ -555,18 +553,6 @@ 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>
</>
);
@@ -577,9 +563,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Select a thread to inspect turn diffs.
</div>
) : !isGitRepo ? (
) : !isVcsRepo ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Turn diffs are unavailable because this project is not a git repository.
Turn diffs are unavailable because this project is not a {vcsTerms.repositoryNoun}.
</div>
) : orderedTurnDiffSummaries.length === 0 ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
@@ -100,14 +100,12 @@ 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", () => ({
@@ -115,6 +113,7 @@ vi.mock("~/lib/gitStatusState", () => ({
resetGitStatusStateForTests: () => undefined,
useGitStatus: vi.fn(() => ({
data: {
kind: "git",
isRepo: true,
sourceControlProvider: {
kind: "github",
@@ -13,6 +13,7 @@ import {
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
return {
kind: "git",
isRepo: true,
hasPrimaryRemote: true,
isDefaultRef: false,
@@ -730,7 +731,7 @@ describe("when: ref has no upstream configured", () => {
});
});
it("resolveQuickAction publishes when no origin remote exists", () => {
it("resolveQuickAction disables push-and-pr flows when no origin remote exists", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
@@ -742,9 +743,10 @@ describe("when: ref has no upstream configured", () => {
false,
);
assert.deepEqual(quick, {
kind: "open_publish",
label: "Publish repository",
disabled: false,
kind: "show_hint",
label: "Push",
hint: 'Add an "origin" remote before pushing or creating a pull request.',
disabled: true,
});
});
@@ -778,7 +780,7 @@ describe("when: ref has no upstream configured", () => {
]);
});
it("buildMenuItems hides push and create PR when no origin remote exists", () => {
it("buildMenuItems disables push and create PR when no origin remote exists", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
false,
@@ -793,6 +795,22 @@ 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" | "open_publish" | "show_hint";
kind: "run_action" | "run_pull" | "open_pr" | "show_hint";
action?: GitStackedAction;
hint?: string;
}
@@ -122,21 +122,15 @@ export function buildMenuItems(
(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 [
commitItem,
{
id: "commit",
label: "Commit",
disabled: !canCommit,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
@@ -222,9 +216,10 @@ export function resolveQuickAction(
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
}
return {
label: "Publish repository",
disabled: false,
kind: "open_publish",
label: "Push",
disabled: true,
kind: "show_hint",
hint: `Add an "origin" remote before pushing or creating a ${terminology.singular}.`,
};
}
if (!isAhead) {
+27 -551
View File
@@ -3,30 +3,11 @@ import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
SourceControlCloneProtocol,
SourceControlProviderKind,
SourceControlPublishRepositoryResult,
SourceControlRepositoryVisibility,
VcsStatusResult,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { Option } from "effect";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import {
CheckIcon,
ChevronDownIcon,
CloudUploadIcon,
ExternalLinkIcon,
GitCommitIcon,
InfoIcon,
LockIcon,
GlobeIcon,
} from "lucide-react";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { GitHubIcon, GitLabIcon } from "~/components/Icons";
import { RadioGroup } from "~/components/ui/radio-group";
import { Spinner } from "~/components/ui/spinner";
import { cn } from "~/lib/utils";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import {
buildGitActionProgressStages,
buildMenuItems,
@@ -52,18 +33,9 @@ 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 {
Select,
SelectGroup,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import { Textarea } from "~/components/ui/textarea";
import { stackedThreadToast, toastManager, type ThreadToastData } from "~/components/ui/toast";
import { openInPreferredEditor } from "~/editorPreferences";
@@ -72,10 +44,8 @@ import {
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";
@@ -84,6 +54,7 @@ import { readLocalApi } from "~/localApi";
import { getSourceControlPresentation } from "~/sourceControlPresentation";
import { useStore } from "~/store";
import { createThreadSelectorByRef } from "~/storeSelectors";
import { resolveVcsActionPresentation, resolveVcsTerms } from "~/vcsPresentation";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -100,8 +71,6 @@ interface PendingDefaultBranchAction {
filePaths?: string[];
}
type PublishProviderKind = Extract<SourceControlProviderKind, "github" | "gitlab">;
type GitActionToastId = ReturnType<typeof toastManager.add>;
interface ActiveGitActionProgress {
@@ -243,7 +212,6 @@ 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} />;
@@ -285,35 +253,8 @@ 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 [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 [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const sourceControlDiscovery = useSourceControlDiscovery();
const publishAccountByProvider = useMemo(() => {
const accounts: Record<PublishProviderKind, string | null> = { github: null, gitlab: null };
for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
if (provider.kind === "github" || provider.kind === "gitlab") {
accounts[provider.kind] = Option.getOrNull(provider.auth.account);
}
}
return accounts;
}, [sourceControlDiscovery.data]);
const publishRepositoryPrefill = publishAccountByProvider[publishProvider]
? `${publishAccountByProvider[publishProvider]}/`
: "";
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
let runGitActionWithToast: (input: RunGitActionWithToastInput) => Promise<void>;
@@ -403,8 +344,12 @@ export default function GitActionsControl({
const SourceControlIcon = sourceControlPresentation.Icon;
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const vcsKind = gitStatus?.kind ?? null;
const vcsTerms = resolveVcsTerms(vcsKind);
const vcsActionPresentation = resolveVcsActionPresentation(vcsKind);
const supportsGitWorkflowActions = !isRepo || vcsActionPresentation.supportsGitWorkflowActions;
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
const gitStatusForActions = gitStatus;
const gitStatusForActions = supportsGitWorkflowActions ? gitStatus : null;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
@@ -425,13 +370,6 @@ export default function GitActionsControl({
const pullMutation = useMutation(
gitPullMutationOptions({ environmentId: activeEnvironmentId, cwd: gitCwd, queryClient }),
);
const publishRepositoryMutation = useMutation(
sourceControlPublishRepositoryMutationOptions({
environmentId: activeEnvironmentId,
cwd: gitCwd,
queryClient,
}),
);
const isRunStackedActionRunning =
useIsMutating({
@@ -439,11 +377,7 @@ export default function GitActionsControl({
}) > 0;
const isPullRunning =
useIsMutating({ mutationKey: gitMutationKeys.pull(activeEnvironmentId, gitCwd) }) > 0;
const isPublishRunning =
useIsMutating({
mutationKey: gitMutationKeys.publishRepository(activeEnvironmentId, gitCwd),
}) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning || isPublishRunning;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isSelectingWorktreeBase =
!activeServerThread &&
activeDraftThread?.envMode === "worktree" &&
@@ -510,13 +444,6 @@ export default function GitActionsControl({
};
}, [updateActiveProgressToast]);
useEffect(() => {
if (!isPublishDialogOpen || hasUserEditedPublishRepository) {
return;
}
setPublishRepository(publishRepositoryPrefill);
}, [isPublishDialogOpen, hasUserEditedPublishRepository, publishRepositoryPrefill]);
useEffect(() => {
if (gitCwd === null) {
return;
@@ -863,10 +790,6 @@ 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<
@@ -964,47 +887,6 @@ export default function GitActionsControl({
[gitCwd, threadToastData],
);
const canPublishRepository = isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
const canSubmitPublishRepository = (() => {
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;
})();
const publishHost = publishProvider === "github" ? "github.com" : "gitlab.com";
const publishPathPlaceholder = publishProvider === "github" ? "owner/repo" : "group/project";
const publishProviderLabel = publishProvider === "github" ? "GitHub" : "GitLab";
const submitPublishRepository = () => {
if (!canSubmitPublishRepository) {
return;
}
setPublishError(null);
void publishRepositoryMutation
.mutateAsync({
provider: publishProvider,
repository: publishRepository.trim(),
visibility: publishVisibility,
remoteName: publishRemoteName.trim() || "origin",
protocol: publishProtocol,
})
.then((result) => {
setPublishResult(result);
setPublishWizardStep(2);
void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
() => undefined,
);
})
.catch((err: unknown) => {
setPublishError(err instanceof Error ? err.message : "An error occurred.");
});
};
if (!gitCwd) return null;
return (
@@ -1018,6 +900,25 @@ export default function GitActionsControl({
>
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
</Button>
) : !supportsGitWorkflowActions ? (
<Popover>
<PopoverTrigger
openOnHover
render={
<Button
aria-disabled="true"
className="cursor-not-allowed opacity-70"
size="xs"
variant="outline"
/>
}
>
{vcsTerms.systemName} {vcsTerms.repositoryNoun}
</PopoverTrigger>
<PopoverPopup tooltipStyle side="bottom" align="end">
{vcsActionPresentation.unsupportedGitWorkflowDescription}
</PopoverPopup>
</Popover>
) : (
<Group aria-label="Git actions" className="shrink-0">
{quickActionDisabledReason ? (
@@ -1119,17 +1020,6 @@ 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
@@ -1322,420 +1212,6 @@ export default function GitActionsControl({
</DialogPopup>
</Dialog>
<Dialog
open={isPublishDialogOpen}
onOpenChange={(open) => {
setIsPublishDialogOpen(open);
if (!open) {
setPublishRemoteName("origin");
setPublishRepository("");
setHasUserEditedPublishRepository(false);
setPublishWizardStep(0);
setPublishAdvancedOpen(false);
setPublishError(null);
setPublishResult(null);
}
}}
>
<DialogPopup className="max-w-lg">
<DialogHeader>
<DialogTitle>Publish repository</DialogTitle>
<DialogDescription>
Pick where to host it, then point us at a repo to push to.
</DialogDescription>
<div className="mt-1 grid grid-cols-3 gap-2">
{(["Provider", "Repository", "Summary"] as const).map((label, index) => {
const summary =
index === 0 && publishWizardStep > 0
? publishProviderLabel
: index === 1 && publishWizardStep > 1 && publishResult
? publishResult.repository.nameWithOwner
: null;
const isComplete = index < publishWizardStep;
const isDoneStep = index === 2;
// The summary step is only reachable via a successful submit;
// disallow user-driven navigation to or from it.
const isClickable =
publishWizardStep !== 2 && !isDoneStep && 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 transition",
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}
{summary ? `: ${summary}` : ""}
</span>
</button>
);
})}
</div>
</DialogHeader>
{/* Step 1: Provider */}
{publishWizardStep === 0 && (
<DialogPanel className="space-y-4">
<div className="space-y-2">
<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"
>
{[
{
value: "github" as const,
label: "GitHub",
description: "github.com",
Icon: GitHubIcon,
},
{
value: "gitlab" as const,
label: "GitLab",
description: "gitlab.com",
Icon: GitLabIcon,
},
].map((option) => {
const isSelected = publishProvider === 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-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">
<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>
</DialogPanel>
)}
{publishWizardStep === 1 && (
<DialogPanel className="space-y-5">
<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">
{publishProvider === "github" ? (
<GitHubIcon className="size-3.5" />
) : (
<GitLabIcon 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>
)}
</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>
)}
{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>
)}
</DialogPanel>
)}
{publishWizardStep === 2 && publishResult && (
<DialogPanel className="space-y-4">
<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">
{publishProvider === "github" ? (
<GitHubIcon className="size-3.5 shrink-0 text-muted-foreground" />
) : (
<GitLabIcon 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>
</DialogPanel>
)}
<DialogFooter>
{publishWizardStep === 2 ? (
<Button size="sm" onClick={() => setIsPublishDialogOpen(false)}>
Done
</Button>
) : (
<>
<Button
variant="outline"
size="sm"
disabled={publishRepositoryMutation.isPending}
onClick={() => {
if (publishWizardStep === 0) {
setIsPublishDialogOpen(false);
return;
}
setPublishWizardStep((step) => Math.max(0, step - 1));
}}
>
{publishWizardStep === 0 ? "Cancel" : "Back"}
</Button>
{publishWizardStep < 1 ? (
<Button
size="sm"
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>
</DialogPopup>
</Dialog>
<Dialog
open={pendingDefaultBranchAction !== null}
onOpenChange={(open) => {
@@ -289,7 +289,7 @@ function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) {
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
version: 1,
type: "keybindingsUpdated",
payload: { keybindings: fixture.serverConfig.keybindings, issues },
payload: { issues },
});
}
+6 -20
View File
@@ -10,29 +10,15 @@ export function ProjectFavicon(input: {
cwd: string;
className?: string;
}) {
const src = (() => {
try {
return resolveEnvironmentHttpUrl({
environmentId: input.environmentId,
pathname: "/api/project-favicon",
searchParams: { cwd: input.cwd },
});
} catch {
return null;
}
})();
const src = resolveEnvironmentHttpUrl({
environmentId: input.environmentId,
pathname: "/api/project-favicon",
searchParams: { cwd: input.cwd },
});
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
src && loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
);
if (!src) {
return (
<FolderIcon
className={`size-3.5 shrink-0 text-muted-foreground/50 ${input.className ?? ""}`}
/>
);
}
return (
<>
{status !== "loaded" ? (
+1 -42
View File
@@ -61,7 +61,7 @@ import { usePrimaryEnvironmentId } from "../environments/primary";
import { isElectron } from "../env";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isMacPlatform, newCommandId, newThreadId } from "../lib/utils";
import { isMacPlatform, newCommandId } from "../lib/utils";
import {
selectProjectByRef,
selectProjectsAcrossEnvironments,
@@ -1905,7 +1905,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
[
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "branch", label: "Branch thread" },
{ id: "copy-path", label: "Copy Path" },
{ id: "copy-thread-id", label: "Copy Thread ID" },
{ id: "delete", label: "Delete", destructive: true },
@@ -1920,45 +1919,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return;
}
if (clicked === "branch") {
const environmentApi = readEnvironmentApi(threadRef.environmentId);
if (!environmentApi) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to branch thread",
description: "Thread API unavailable.",
}),
);
return;
}
const branchThreadRef = scopeThreadRef(threadRef.environmentId, newThreadId());
try {
await environmentApi.orchestration.dispatchCommand({
type: "thread.branch",
commandId: newCommandId(),
sourceThreadId: threadRef.threadId,
threadId: branchThreadRef.threadId,
title: `${thread.title} (Branched)`,
createdAt: new Date().toISOString(),
});
await router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(branchThreadRef),
});
} catch (error) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to branch thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
if (clicked === "mark-unread") {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
return;
@@ -2003,7 +1963,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
markThreadUnread,
memberProjectByScopedKey,
project.cwd,
router,
],
);
@@ -8,7 +8,6 @@ function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionSt
attemptCount: 0,
closeCode: null,
closeReason: null,
connectionLabel: null,
connectedAt: null,
disconnectedAt: null,
hasConnected: false,
@@ -53,16 +53,8 @@ function describeExhaustedToast(): string {
return "Retries exhausted trying to reconnect";
}
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 buildReconnectTitle(_status: WsConnectionStatus): string {
return "Disconnected from T3 Server";
}
function describeRecoveredToast(
@@ -305,7 +297,7 @@ export function WebSocketConnectionCoordinator() {
},
description: describeExhaustedToast(),
timeout: 0,
title: buildReconnectTitle(status),
title: "Disconnected from T3 Server",
type: "error",
})
: stackedThreadToast({
@@ -342,7 +334,7 @@ export function WebSocketConnectionCoordinator() {
) {
const successToast = {
description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt),
title: buildRecoveredTitle(status),
title: "Reconnected to T3 Server",
type: "success" as const,
timeout: 0,
data: {
@@ -2,13 +2,11 @@ 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";
@@ -161,127 +159,6 @@ 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;
+48 -374
View File
@@ -111,7 +111,6 @@ 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`;
@@ -139,13 +138,6 @@ const runtimeModeConfig: Record<
const runtimeModeOptions = Object.keys(runtimeModeConfig) as RuntimeMode[];
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
const COMPOSER_FLOATING_LAYER_SELECTOR = [
'[data-slot="popover-popup"]',
'[data-slot="menu-popup"]',
'[data-slot="select-popup"]',
'[data-slot="combobox-popup"]',
'[data-slot="autocomplete-popup"]',
].join(",");
const extendReplacementRangeForTrailingSpace = (
text: string,
@@ -175,10 +167,6 @@ const terminalContextIdListsEqual = (
): boolean =>
contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]);
function isInsideComposerFloatingLayer(element: Element): boolean {
return element.closest(COMPOSER_FLOATING_LAYER_SELECTOR) !== null;
}
const ComposerFooterModeControls = memo(function ComposerFooterModeControls(props: {
showInteractionModeToggle: boolean;
interactionMode: ProviderInteractionMode;
@@ -301,9 +289,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
promptHasText: boolean;
isSendBusy: boolean;
isConnecting: boolean;
isEnvironmentUnavailable: boolean;
hasSendableContent: boolean;
preserveComposerFocusOnPointerDown?: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
@@ -322,10 +308,8 @@ 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}
@@ -395,10 +379,6 @@ 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;
@@ -409,7 +389,7 @@ export interface ChatComposerProps {
isLastQuestion: boolean;
canAdvance: boolean;
customAnswer: string;
activeQuestion: { id: string; multiSelect?: boolean | undefined } | null;
activeQuestion: { id: string } | null;
} | null;
activePendingResolvedAnswers: Record<string, unknown> | null;
activePendingIsResponding: boolean;
@@ -506,7 +486,6 @@ export const ChatComposer = memo(
isConnecting,
isSendBusy,
isPreparingWorktree,
environmentUnavailable,
activePendingApproval,
pendingApprovals,
pendingUserInputs,
@@ -795,25 +774,17 @@ export const ChatComposer = memo(
const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false);
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const isMobileViewport = useMediaQuery("max-sm");
const isComposerCollapsedMobile = isMobileViewport && !isComposerFocused;
// ------------------------------------------------------------------
// 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 composerBlurFrameRef = useRef<number | null>(null);
const mobileComposerExpandFrameRef = useRef<number | null>(null);
const mobileComposerExpandReleaseFrameRef = useRef<number | null>(null);
const mobileComposerExpandInFlightRef = useRef(false);
const dragDepthRef = useRef(0);
// ------------------------------------------------------------------
@@ -958,8 +929,6 @@ export const ChatComposer = memo(
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
(showPlanFollowUpPrompt && activeProposedPlan !== null);
const showCollapsedMobilePromptRow =
isComposerCollapsedMobile && !isComposerApprovalState && pendingUserInputs.length === 0;
const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null;
const showPlanSidebarToggle = Boolean(activePlan || sidebarProposedPlan || planSidebarOpen);
@@ -1052,11 +1021,6 @@ export const ChatComposer = memo(
: null,
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
);
const collapsedComposerPrimaryActionDisabled =
phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null;
// ------------------------------------------------------------------
// Prompt helpers
@@ -1586,69 +1550,6 @@ export const ChatComposer = memo(
[composerHighlightedItemId, composerMenuItems],
);
const blurMobileComposerAfterSend = useCallback(() => {
if (!isMobileViewport) return;
if (composerBlurFrameRef.current !== null) {
window.cancelAnimationFrame(composerBlurFrameRef.current);
composerBlurFrameRef.current = null;
}
const activeElement = document.activeElement;
if (activeElement instanceof HTMLElement) {
activeElement.blur();
}
setIsComposerFocused(false);
}, [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(() => {
if (composerBlurFrameRef.current !== null) {
window.cancelAnimationFrame(composerBlurFrameRef.current);
composerBlurFrameRef.current = null;
}
if (mobileComposerExpandFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerExpandFrameRef.current);
}
if (mobileComposerExpandReleaseFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerExpandReleaseFrameRef.current);
}
mobileComposerExpandInFlightRef.current = true;
setIsComposerFocused(true);
mobileComposerExpandFrameRef.current = window.requestAnimationFrame(() => {
mobileComposerExpandFrameRef.current = null;
composerEditorRef.current?.focusAtEnd();
mobileComposerExpandReleaseFrameRef.current = window.requestAnimationFrame(() => {
mobileComposerExpandReleaseFrameRef.current = null;
mobileComposerExpandInFlightRef.current = false;
});
});
}, []);
// ------------------------------------------------------------------
// Callbacks: command key
// ------------------------------------------------------------------
@@ -1679,7 +1580,7 @@ export const ChatComposer = memo(
}
}
if (key === "Enter" && !event.shiftKey) {
submitComposer();
void onSend();
return true;
}
return false;
@@ -1789,50 +1690,6 @@ export const ChatComposer = memo(
const handleImplementPlanInNewThreadPrimaryAction = useCallback(() => {
void onImplementPlanInNewThread();
}, [onImplementPlanInNewThread]);
const scheduleComposerCollapseCheck = useCallback(() => {
if (!isMobileViewport) {
return;
}
if (mobileComposerExpandInFlightRef.current) {
return;
}
if (composerBlurFrameRef.current !== null) {
window.cancelAnimationFrame(composerBlurFrameRef.current);
}
composerBlurFrameRef.current = window.requestAnimationFrame(() => {
composerBlurFrameRef.current = null;
if (mobileComposerExpandInFlightRef.current) {
return;
}
const composerSurface = composerSurfaceRef.current;
const activeElement = document.activeElement;
if (activeElement instanceof Element && isInsideComposerFloatingLayer(activeElement)) {
return;
}
if (
composerSurface &&
activeElement instanceof Node &&
composerSurface.contains(activeElement)
) {
return;
}
setIsComposerFocused(false);
});
}, [isMobileViewport]);
useEffect(() => {
return () => {
if (composerBlurFrameRef.current !== null) {
window.cancelAnimationFrame(composerBlurFrameRef.current);
}
if (mobileComposerExpandFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerExpandFrameRef.current);
}
if (mobileComposerExpandReleaseFrameRef.current !== null) {
window.cancelAnimationFrame(mobileComposerExpandReleaseFrameRef.current);
}
};
}, []);
// ------------------------------------------------------------------
// Imperative handle
@@ -1946,7 +1803,7 @@ export const ChatComposer = memo(
return (
<form
ref={composerFormRef}
onSubmit={submitComposer}
onSubmit={onSend}
className="mx-auto w-full min-w-0 max-w-208"
data-chat-composer-form="true"
>
@@ -1961,83 +1818,21 @@ export const ChatComposer = memo(
onDrop={onComposerDrop}
>
<div
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"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,
)}
onFocusCapture={(event) => {
const activeElement = event.target;
if (
isComposerCollapsedMobile &&
activeElement instanceof HTMLElement &&
activeElement.closest('[data-chat-composer-collapsed-controls="true"]')
) {
return;
}
if (composerBlurFrameRef.current !== null) {
window.cancelAnimationFrame(composerBlurFrameRef.current);
composerBlurFrameRef.current = null;
}
setIsComposerFocused(true);
}}
onBlurCapture={() => {
scheduleComposerCollapseCheck();
}}
>
{!isComposerCollapsedMobile &&
(activePendingApproval ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<ComposerPendingApprovalPanel
approval={activePendingApproval}
pendingCount={pendingApprovals.length}
/>
</div>
) : pendingUserInputs.length > 0 ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
respondingRequestIds={respondingRequestIds}
answers={activePendingDraftAnswers}
questionIndex={activePendingQuestionIndex}
onToggleOption={onSelectActivePendingUserInputOption}
onAdvance={onAdvanceActivePendingUserInput}
/>
</div>
) : showPlanFollowUpPrompt && activeProposedPlan ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<ComposerPlanFollowUpBanner
key={activeProposedPlan.id}
planTitle={proposedPlanTitle(activeProposedPlan.planMarkdown) ?? null}
/>
</div>
) : null)}
{isComposerCollapsedMobile && activePendingApproval ? (
<div
className="rounded-t-[19px] border-b border-border/65 bg-muted/20"
data-chat-composer-collapsed-controls="true"
>
{activePendingApproval ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<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>
) : isComposerCollapsedMobile && pendingUserInputs.length > 0 ? (
<div
className="rounded-t-[19px] border-b border-border/65 bg-muted/20"
data-chat-composer-collapsed-controls="true"
>
) : pendingUserInputs.length > 0 ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
respondingRequestIds={respondingRequestIds}
@@ -2046,92 +1841,13 @@ export const ChatComposer = memo(
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()}
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="flex items-center justify-between gap-2 px-3 py-2">
<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()}
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>
) : showPlanFollowUpPrompt && activeProposedPlan ? (
<div className="rounded-t-[19px] border-b border-border/65 bg-muted/20">
<ComposerPlanFollowUpBanner
key={activeProposedPlan.id}
planTitle={proposedPlanTitle(activeProposedPlan.planMarkdown) ?? null}
/>
</div>
) : null}
@@ -2139,7 +1855,6 @@ export const ChatComposer = memo(
className={cn(
"relative px-3 pb-2 sm:px-4",
hasComposerHeader ? "pt-2.5 sm:pt-3" : "pt-3.5 sm:pt-4",
isComposerCollapsedMobile && "hidden",
)}
>
{composerMenuOpen && !isComposerApprovalState && (
@@ -2161,8 +1876,7 @@ export const ChatComposer = memo(
</div>
)}
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
{!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
composerImages.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
@@ -2229,80 +1943,43 @@ export const ChatComposer = memo(
</div>
)}
<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>
<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>
{/* Bottom toolbar */}
{isComposerCollapsedMobile ? null : activePendingApproval ? (
{activePendingApproval ? (
<div className="flex items-center justify-end gap-2 px-2.5 pb-2.5 sm:px-3 sm:pb-3">
<ComposerPendingApprovalActions
requestId={activePendingApproval.requestId}
@@ -2317,7 +1994,6 @@ 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 && "hidden sm:flex",
)}
>
<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">
@@ -2404,10 +2080,8 @@ 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}
@@ -1,48 +0,0 @@
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);
});
});
+15 -25
View File
@@ -17,6 +17,8 @@ import { Toggle } from "../ui/toggle";
import { SidebarTrigger } from "../ui/sidebar";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironmentId } from "../../environments/primary";
import { resolveVcsTerms } from "../../vcsPresentation";
import type { VcsDriverKind } from "@t3tools/contracts";
interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
@@ -24,7 +26,8 @@ interface ChatHeaderProps {
draftId?: DraftId;
activeThreadTitle: string;
activeProjectName: string | undefined;
isGitRepo: boolean;
isVcsRepo: boolean;
vcsKind: VcsDriverKind | null;
openInCwd: string | null;
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
@@ -44,25 +47,14 @@ interface ChatHeaderProps {
onToggleDiff: () => void;
}
export function shouldShowOpenInPicker(input: {
readonly activeProjectName: string | undefined;
readonly activeThreadEnvironmentId: EnvironmentId;
readonly primaryEnvironmentId: EnvironmentId | null;
}): boolean {
return (
Boolean(input.activeProjectName) &&
input.primaryEnvironmentId !== null &&
input.activeThreadEnvironmentId === input.primaryEnvironmentId
);
}
export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
activeThreadId,
draftId,
activeThreadTitle,
activeProjectName,
isGitRepo,
isVcsRepo,
vcsKind,
openInCwd,
activeProjectScripts,
preferredScriptId,
@@ -82,11 +74,9 @@ export const ChatHeader = memo(function ChatHeader({
onToggleDiff,
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName,
activeThreadEnvironmentId,
primaryEnvironmentId,
});
const isRemoteEnvironment =
primaryEnvironmentId !== null && activeThreadEnvironmentId !== primaryEnvironmentId;
const vcsTerms = resolveVcsTerms(vcsKind);
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
@@ -103,9 +93,9 @@ export const ChatHeader = memo(function ChatHeader({
<span className="min-w-0 truncate">{activeProjectName}</span>
</Badge>
)}
{activeProjectName && !isGitRepo && (
{activeProjectName && !isVcsRepo && (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
No repository
</Badge>
)}
</div>
@@ -121,7 +111,7 @@ export const ChatHeader = memo(function ChatHeader({
onDeleteScript={onDeleteProjectScript}
/>
)}
{showOpenInPicker && (
{activeProjectName && !isRemoteEnvironment && (
<OpenInPicker
keybindings={keybindings}
availableEditors={availableEditors}
@@ -169,15 +159,15 @@ export const ChatHeader = memo(function ChatHeader({
aria-label="Toggle diff panel"
variant="outline"
size="xs"
disabled={!isGitRepo && !diffOpen}
disabled={!isVcsRepo && !diffOpen}
>
<DiffIcon className="size-3" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{!isGitRepo && !diffOpen
? "Diff panel is unavailable because this project is not a git repository."
{!isVcsRepo && !diffOpen
? `Diff panel is unavailable because this project is not a supported ${vcsTerms.repositoryNoun}.`
: diffToggleShortcutLabel
? `Toggle diff panel (${diffToggleShortcutLabel})`
: "Toggle diff panel"}
@@ -1,195 +0,0 @@
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { XIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
import { Button } from "../ui/button";
const DISMISS_TRANSITION_MS = 220;
const frontExitStyle = {
opacity: 0,
transform: "translate3d(0, 4rem, 0)",
} satisfies CSSProperties;
const stackedExitStyle = {
opacity: 0,
transform: "translate3d(0, 7rem, 0)",
} satisfies CSSProperties;
const restingStyle = {
opacity: 1,
transform: "translate3d(0, 0, 0)",
} satisfies CSSProperties;
const exitTransitionStyle = {
transition: `transform ${DISMISS_TRANSITION_MS}ms ease-in, opacity ${DISMISS_TRANSITION_MS}ms ease-in`,
willChange: "transform, opacity",
} satisfies CSSProperties;
export interface ComposerBannerStackItem {
readonly id: string;
readonly variant: "error" | "info" | "success" | "warning";
readonly icon: ReactNode;
readonly title: ReactNode;
readonly description?: ReactNode;
readonly actions?: ReactNode;
readonly dismissLabel?: string;
readonly onDismiss?: () => void;
}
interface ComposerBannerStackProps {
readonly className?: string;
readonly items: ReadonlyArray<ComposerBannerStackItem>;
}
export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) {
const [exitingItemId, setExitingItemId] = useState<string | null>(null);
const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (exitingItemId && !items.some((item) => item.id === exitingItemId)) {
setExitingItemId(null);
}
}, [exitingItemId, items]);
useEffect(() => {
return () => {
if (dismissTimeoutRef.current) {
clearTimeout(dismissTimeoutRef.current);
}
};
}, []);
if (items.length === 0) {
return null;
}
const frontItem = items[0];
if (!frontItem) {
return null;
}
const stackedItems = items.slice(1);
const hasStack = stackedItems.length > 0;
const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id;
const requestDismiss = (item: ComposerBannerStackItem) => {
if (!item.onDismiss || exitingItemId) {
return;
}
setExitingItemId(item.id);
if (dismissTimeoutRef.current) {
clearTimeout(dismissTimeoutRef.current);
}
dismissTimeoutRef.current = setTimeout(() => {
dismissTimeoutRef.current = null;
item.onDismiss?.();
}, DISMISS_TRANSITION_MS);
};
return (
<div className={cn("group/banner-stack mx-auto mb-2 max-w-208", className)}>
<div
className={cn(
"relative",
hasStack ? "group-hover/banner-stack:z-50 group-focus-within/banner-stack:z-50" : null,
)}
>
{showCollapsedStackCap ? (
<div
className={cn(
"pointer-events-none absolute inset-x-0 -top-3 z-0 mx-auto h-3 rounded-t-xl",
"border border-b-0 border-warning/24 bg-background/96 shadow-[0_6px_18px_rgba(0,0,0,0.06)]",
"transition-opacity duration-150 ease-out",
"group-hover/banner-stack:opacity-0 group-focus-within/banner-stack:opacity-0",
)}
style={{ width: "96%" }}
aria-hidden="true"
/>
) : null}
<div
className={cn(
"relative z-10",
exitingItemId === frontItem.id ? "pointer-events-none" : null,
)}
style={{
...exitTransitionStyle,
...(exitingItemId === frontItem.id ? frontExitStyle : restingStyle),
}}
>
<ComposerBannerStackAlert
item={frontItem}
exiting={exitingItemId === frontItem.id}
onDismissRequest={() => requestDismiss(frontItem)}
/>
</div>
{hasStack ? (
<div
className={cn(
"pointer-events-none absolute inset-x-0 bottom-[calc(100%+0.5rem)] z-20 space-y-2 opacity-0",
"transition-[opacity,transform] duration-150 ease-out",
"translate-y-1 transform-gpu will-change-[opacity,transform]",
"group-hover/banner-stack:pointer-events-auto group-hover/banner-stack:translate-y-0 group-hover/banner-stack:opacity-100",
"group-focus-within/banner-stack:pointer-events-auto group-focus-within/banner-stack:translate-y-0 group-focus-within/banner-stack:opacity-100",
)}
>
{stackedItems.map((item) => (
<div
key={item.id}
className={cn(exitingItemId === item.id ? "pointer-events-none" : null)}
style={{
...exitTransitionStyle,
...(exitingItemId === item.id ? stackedExitStyle : restingStyle),
}}
>
<ComposerBannerStackAlert
item={item}
exiting={exitingItemId === item.id}
onDismissRequest={() => requestDismiss(item)}
/>
</div>
))}
</div>
) : null}
</div>
</div>
);
}
function ComposerBannerStackAlert({
item,
exiting,
onDismissRequest,
}: {
readonly item: ComposerBannerStackItem;
readonly exiting: boolean;
readonly onDismissRequest: () => void;
}) {
const dismissOnly = item.onDismiss && !item.actions;
return (
<Alert variant={item.variant}>
{item.icon}
<AlertTitle>{item.title}</AlertTitle>
{item.description ? <AlertDescription>{item.description}</AlertDescription> : null}
{item.actions || item.onDismiss ? (
<AlertAction
className={
dismissOnly
? "max-sm:col-start-3 max-sm:row-start-1 max-sm:mt-0 max-sm:self-start"
: undefined
}
>
{item.actions}
{item.onDismiss ? (
<Button
size="icon-xs"
variant="ghost"
aria-label={item.dismissLabel ?? "Dismiss warning"}
disabled={exiting}
onClick={onDismissRequest}
>
<XIcon className="size-3.5" />
</Button>
) : null}
</AlertAction>
) : null}
</Alert>
);
}
@@ -1,4 +1,4 @@
import { memo, type PointerEventHandler } from "react";
import { memo } from "react";
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
@@ -20,10 +20,8 @@ interface ComposerPrimaryActionsProps {
promptHasText: boolean;
isSendBusy: boolean;
isConnecting: boolean;
isEnvironmentUnavailable: boolean;
isPreparingWorktree: boolean;
hasSendableContent: boolean;
preserveComposerFocusOnPointerDown?: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
@@ -47,10 +45,6 @@ export const formatPendingPrimaryActionLabel = (input: {
return input.questionIndex > 0 ? "Submit answers" : "Submit answer";
};
const preventPointerFocus: PointerEventHandler<HTMLElement> = (event) => {
event.preventDefault();
};
export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
compact,
pendingAction,
@@ -59,18 +53,12 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
promptHasText,
isSendBusy,
isConnecting,
isEnvironmentUnavailable,
isPreparingWorktree,
hasSendableContent,
preserveComposerFocusOnPointerDown = false,
onPreviousPendingQuestion,
onInterrupt,
onImplementPlanInNewThread,
}: ComposerPrimaryActionsProps) {
const pointerFocusProps = preserveComposerFocusOnPointerDown
? { onPointerDown: preventPointerFocus }
: undefined;
if (pendingAction) {
return (
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
@@ -80,7 +68,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
size="icon-sm"
variant="outline"
className="rounded-full"
{...pointerFocusProps}
onClick={onPreviousPendingQuestion}
disabled={pendingAction.isResponding}
aria-label="Previous question"
@@ -92,7 +79,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
size="sm"
variant="outline"
className="rounded-full"
{...pointerFocusProps}
onClick={onPreviousPendingQuestion}
disabled={pendingAction.isResponding}
>
@@ -104,9 +90,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="submit"
size="sm"
className={cn("rounded-full", compact ? "px-3" : "px-4")}
{...pointerFocusProps}
disabled={
isEnvironmentUnavailable ||
pendingAction.isResponding ||
(pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance)
}
@@ -127,7 +111,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="button"
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-rose-500/90 text-white transition-all duration-150 hover:bg-rose-500 hover:scale-105 sm:h-8 sm:w-8"
{...pointerFocusProps}
onClick={onInterrupt}
aria-label="Stop generation"
>
@@ -145,8 +128,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="submit"
size="sm"
className={cn("rounded-full", compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8")}
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
disabled={isSendBusy || isConnecting}
>
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
</Button>
@@ -159,8 +141,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
type="submit"
size="sm"
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
disabled={isSendBusy || isConnecting}
>
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
</Button>
@@ -172,8 +153,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
variant="default"
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
aria-label="Implementation actions"
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
disabled={isSendBusy || isConnecting}
/>
}
>
@@ -181,7 +161,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
</MenuTrigger>
<MenuPopup align="end" side="top">
<MenuItem
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
disabled={isSendBusy || isConnecting}
onClick={() => void onImplementPlanInNewThread()}
>
Implement in a new thread
@@ -196,18 +176,15 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
{...pointerFocusProps}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
disabled={isSendBusy || isConnecting || !hasSendableContent}
aria-label={
isEnvironmentUnavailable
? "Environment disconnected"
: isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
}
>
{isConnecting || isSendBusy ? (
@@ -62,7 +62,6 @@ function buildProps() {
onOpenTurnDiff: vi.fn(),
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: vi.fn(),
onBranchAssistantMessage: vi.fn(),
isRevertingCheckpoint: false,
onImageExpand: vi.fn(),
activeThreadEnvironmentId: EnvironmentId.make("environment-local"),
@@ -88,7 +88,6 @@ function buildProps() {
onOpenTurnDiff: () => {},
revertTurnCountByUserMessageId: new Map(),
onRevertUserMessage: () => {},
onBranchAssistantMessage: () => {},
isRevertingCheckpoint: false,
onImageExpand: () => {},
activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
@@ -187,44 +186,4 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
});
it("renders assistant branch action next to the completed assistant copy action", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-user",
kind: "message",
createdAt: "2026-03-17T19:12:28.000Z",
message: {
id: MessageId.make("message-user"),
role: "user",
text: "do the thing",
createdAt: "2026-03-17T19:12:28.000Z",
streaming: false,
},
},
{
id: "entry-assistant",
kind: "message",
createdAt: "2026-03-17T19:12:30.000Z",
message: {
id: MessageId.make("message-assistant"),
role: "assistant",
text: "done",
turnId: "turn-1" as never,
createdAt: "2026-03-17T19:12:30.000Z",
completedAt: "2026-03-17T19:12:35.000Z",
streaming: false,
},
},
]}
/>,
);
expect(markup).toContain('aria-label="Copy link"');
expect(markup).toContain('aria-label="Branch from message"');
});
});
@@ -20,7 +20,6 @@ import {
CheckIcon,
CircleAlertIcon,
EyeIcon,
GitBranchIcon,
GlobeIcon,
HammerIcon,
type LucideIcon,
@@ -83,7 +82,6 @@ interface TimelineRowSharedState {
workspaceRoot: string | undefined;
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onBranchAssistantMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}
@@ -108,7 +106,6 @@ interface MessagesTimelineProps {
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
revertTurnCountByUserMessageId: Map<MessageId, number>;
onRevertUserMessage: (messageId: MessageId) => void;
onBranchAssistantMessage: (messageId: MessageId) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
activeThreadEnvironmentId: EnvironmentId;
@@ -137,7 +134,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenTurnDiff,
revertTurnCountByUserMessageId,
onRevertUserMessage,
onBranchAssistantMessage,
isRevertingCheckpoint,
onImageExpand,
activeThreadEnvironmentId,
@@ -209,7 +205,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
activeThreadEnvironmentId,
onRevertUserMessage,
onBranchAssistantMessage,
onImageExpand,
onOpenTurnDiff,
}),
@@ -226,7 +221,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
activeThreadEnvironmentId,
onRevertUserMessage,
onBranchAssistantMessage,
onImageExpand,
onOpenTurnDiff,
],
@@ -396,8 +390,6 @@ function TimelineRowContent({ row }: { row: TimelineRow }) {
showCopyButton: row.showAssistantCopyButton,
streaming: row.message.streaming || assistantTurnStillInProgress,
});
const showAssistantBranchButton =
row.showAssistantCopyButton && !row.message.streaming && !assistantTurnStillInProgress;
return (
<>
{row.showCompletionDivider && (
@@ -437,37 +429,14 @@ function TimelineRowContent({ row }: { row: TimelineRow }) {
)
)}
</p>
{assistantCopyState.visible || showAssistantBranchButton ? (
<div className="flex items-center gap-1 opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
{assistantCopyState.visible ? (
<MessageCopyButton
text={assistantCopyState.text ?? ""}
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
) : null}
{showAssistantBranchButton ? (
<Tooltip>
<TooltipTrigger
render={
<Button
aria-label="Branch from message"
onClick={() => ctx.onBranchAssistantMessage(row.message.id)}
type="button"
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
}
>
<GitBranchIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup>
<p>Branch from this message</p>
</TooltipPopup>
</Tooltip>
) : null}
{assistantCopyState.visible ? (
<div className="flex items-center opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
<MessageCopyButton
text={assistantCopyState.text ?? ""}
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
</div>
) : null}
</div>
@@ -1,221 +0,0 @@
import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { useEffect, useId, useRef, useState } from "react";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
function describeSshTarget(request: DesktopSshPasswordPromptRequest): string {
return request.username ? `${request.username}@${request.destination}` : request.destination;
}
function formatRemainingSeconds(seconds: number): string {
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}
function getPromptErrorMessage(error: unknown): string {
const message = error instanceof Error ? error.message : "SSH password prompt failed.";
return message.includes("expired") || message.includes("no longer pending")
? "This SSH password prompt expired. Try connecting again."
: message;
}
export function SshPasswordPromptDialog() {
const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
const [password, setPassword] = useState("");
const [isResponding, setIsResponding] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [responseError, setResponseError] = useState<string | null>(null);
const currentRequest = queue[0] ?? null;
const inputRef = useRef<HTMLInputElement | null>(null);
const isRespondingRef = useRef(false);
const formId = useId();
useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onSshPasswordPrompt) {
return;
}
return bridge.onSshPasswordPrompt((request) => {
setQueue((currentQueue) => [...currentQueue, request]);
});
}, []);
useEffect(() => {
setPassword("");
setResponseError(null);
if (!currentRequest) {
return;
}
setNow(Date.now());
const frame = window.requestAnimationFrame(() => {
inputRef.current?.focus();
inputRef.current?.select();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [currentRequest]);
useEffect(() => {
if (!currentRequest) {
return;
}
const interval = window.setInterval(() => {
setNow(Date.now());
}, 1_000);
return () => {
window.clearInterval(interval);
};
}, [currentRequest]);
const expiresAtMs = currentRequest ? Date.parse(currentRequest.expiresAt) : Number.NaN;
const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null;
const isExpired = remainingMs !== null && remainingMs <= 0;
const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
const remainingLabel =
remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
useEffect(() => {
if (isExpired) {
setResponseError("This SSH password prompt expired. Try connecting again.");
}
}, [isExpired]);
const removeCurrentPrompt = (requestId: string) => {
setQueue((currentQueue) =>
currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue,
);
setPassword("");
setResponseError(null);
};
const respond = async (nextPassword: string | null) => {
if (!currentRequest || isRespondingRef.current) {
return;
}
const requestId = currentRequest.requestId;
if (nextPassword !== null && isExpired) {
setResponseError("This SSH password prompt expired. Try connecting again.");
return;
}
isRespondingRef.current = true;
setIsResponding(true);
setResponseError(null);
try {
await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword);
removeCurrentPrompt(requestId);
} catch (error) {
if (nextPassword === null) {
removeCurrentPrompt(requestId);
} else {
setResponseError(getPromptErrorMessage(error));
}
} finally {
isRespondingRef.current = false;
setIsResponding(false);
}
};
const dismissExpiredPrompt = () => {
if (currentRequest) {
removeCurrentPrompt(currentRequest.requestId);
}
};
const cancelPrompt = () => {
if (isExpired) {
dismissExpiredPrompt();
return;
}
void respond(null);
};
const target = currentRequest ? describeSshTarget(currentRequest) : null;
return (
<Dialog
open={currentRequest !== null}
onOpenChange={(open) => {
if (!open) {
cancelPrompt();
}
}}
>
<DialogPopup className="max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>SSH Password Required</DialogTitle>
<DialogDescription>
T3 needs your SSH password to connect to{" "}
{target ? <code>{target}</code> : "the remote host"}. The password is passed to the
local SSH process for this connection attempt and is not saved by T3 Code.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-3" scrollFade={false}>
<form
className="space-y-3"
id={formId}
onSubmit={(event) => {
event.preventDefault();
void respond(password);
}}
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>
{remainingLabel ? (
<span
className={
isExpired
? "shrink-0 text-xs font-medium text-destructive"
: "shrink-0 text-xs text-muted-foreground"
}
>
{isExpired ? "Expired" : remainingLabel}
</span>
) : null}
</div>
<Input
ref={inputRef}
autoComplete="current-password"
disabled={isResponding || isExpired}
name="ssh-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</div>
{responseError ? (
<p className="text-sm text-destructive">{responseError}</p>
) : (
<p className="text-sm text-muted-foreground">
Use SSH keys to avoid repeated password prompts on new SSH sessions.
</p>
)}
</form>
</DialogPanel>
<DialogFooter>
<Button disabled={isResponding} type="button" variant="outline" onClick={cancelPrompt}>
{isExpired ? "Dismiss" : "Cancel"}
</Button>
<Button disabled={isResponding || isExpired} form={formId} type="submit">
Continue
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
File diff suppressed because it is too large. Load diff
@@ -21,7 +21,6 @@ import { render } from "vitest-browser-react";
import { __resetLocalApiForTests } from "../../localApi";
import { AppAtomRegistryProvider, resetAppAtomRegistryForTests } from "../../rpc/atomRegistry";
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
import { useUiStateStore } from "../../uiStateStore";
import { ConnectionsSettings } from "./ConnectionsSettings";
import { GeneralSettingsPanel } from "./SettingsPanels";
import { SourceControlSettingsPanel } from "./SourceControlSettings";
@@ -116,8 +115,6 @@ const authAccessHarness = vi.hoisted(() => {
};
});
const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn());
vi.mock("../../environments/runtime", () => {
const primaryConnection = {
kind: "primary" as const,
@@ -155,7 +152,6 @@ vi.mock("../../environments/runtime", () => {
new URL(path, "http://localhost:3000").toString(),
waitForSavedEnvironmentRegistryHydration: async () => undefined,
addSavedEnvironment: vi.fn(),
connectDesktopSshEnvironment: mockConnectDesktopSshEnvironment,
disconnectSavedEnvironment: vi.fn(),
ensureEnvironmentConnectionBootstrapped: async () => undefined,
getPrimaryEnvironmentConnection: () => primaryConnection,
@@ -263,9 +259,7 @@ function makeClientSession(input: {
}
const createDesktopBridgeStub = (overrides?: {
readonly discoverSshHosts?: DesktopBridge["discoverSshHosts"];
readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
readonly advertisedEndpoints?: Awaited<ReturnType<DesktopBridge["getAdvertisedEndpoints"]>>;
readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"];
}): DesktopBridge => {
@@ -301,58 +295,11 @@ const createDesktopBridgeStub = (overrides?: {
getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
discoverSshHosts: overrides?.discoverSshHosts ?? vi.fn().mockResolvedValue([]),
ensureSshEnvironment: vi.fn().mockImplementation(async (target) => ({
target,
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
pairingToken: "ssh-pairing-token",
})),
disconnectSshEnvironment: vi.fn().mockResolvedValue(undefined),
fetchSshEnvironmentDescriptor: vi.fn().mockResolvedValue({
environmentId: "environment-ssh",
label: "SSH environment",
platform: {
os: "linux",
arch: "x64",
},
serverVersion: "0.0.0-test",
capabilities: {
repositoryIdentity: true,
},
}),
bootstrapSshBearerSession: vi.fn().mockResolvedValue({
authenticated: true,
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
sessionToken: "ssh-bearer-token",
}),
fetchSshSessionState: vi.fn().mockResolvedValue({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: "t3_session",
},
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
}),
issueSshWebSocketToken: vi.fn().mockResolvedValue({
token: "ssh-ws-token",
expiresAt: "2026-05-01T12:05:00.000Z",
}),
onSshPasswordPrompt: vi.fn(() => () => {}),
resolveSshPasswordPrompt: vi.fn().mockResolvedValue(undefined),
getServerExposureState: vi.fn().mockResolvedValue(
overrides?.serverExposureState ?? {
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
),
setServerExposureMode:
@@ -361,17 +308,7 @@ const createDesktopBridgeStub = (overrides?: {
mode,
endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null,
advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
})),
setTailscaleServeEnabled: vi.fn().mockImplementation(async (input) => ({
mode: overrides?.serverExposureState?.mode ?? "network-accessible",
endpointUrl: overrides?.serverExposureState?.endpointUrl ?? "http://192.168.1.44:3773",
advertisedHost: overrides?.serverExposureState?.advertisedHost ?? "192.168.1.44",
tailscaleServeEnabled: input.enabled,
tailscaleServePort: input.port ?? 443,
})),
getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []),
pickFolder: vi.fn().mockResolvedValue(null),
confirm: vi.fn().mockResolvedValue(false),
setTheme: vi.fn().mockResolvedValue(undefined),
@@ -408,9 +345,7 @@ describe("GeneralSettingsPanel observability", () => {
resetServerStateForTests();
await __resetLocalApiForTests();
localStorage.clear();
useUiStateStore.setState({ defaultAdvertisedEndpointKey: null });
authAccessHarness.reset();
mockConnectDesktopSshEnvironment.mockReset();
});
afterEach(async () => {
@@ -496,176 +431,6 @@ describe("GeneralSettingsPanel observability", () => {
.toBeInTheDocument();
});
it("hides advertised endpoint rows when desktop network access is disabled", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
advertisedEndpoints: [
{
id: "loopback",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
},
{
id: "tailscale-ip",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.105.39.17:3773/",
wsBaseUrl: "ws://100.105.39.17:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
},
],
});
authAccessHarness.setSnapshot({
pairingLinks: [],
clientSessions: [],
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("Limited to this machine.")).toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "This machine", exact: true }))
.not.toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "Tailscale IP", exact: true }))
.not.toBeInTheDocument();
});
it("collapses advertised endpoints behind the network access summary", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
mode: "network-accessible",
endpointUrl: "http://192.168.86.39:3773",
advertisedHost: "192.168.86.39",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
advertisedEndpoints: [
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
},
{
id: "desktop-lan:http://192.168.86.39:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://192.168.86.39:3773/",
wsBaseUrl: "ws://192.168.86.39:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
},
{
id: "tailscale-ip:http://100.105.39.17:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.105.39.17:3773/",
wsBaseUrl: "ws://100.105.39.17:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
},
],
});
authAccessHarness.setSnapshot({
pairingLinks: [],
clientSessions: [],
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("http://192.168.86.39:3773/")).toBeInTheDocument();
await expect.element(page.getByRole("button", { name: "+2" })).toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "Local network", exact: true }))
.not.toBeInTheDocument();
await page.getByRole("button", { name: "+2" }).click();
await expect
.element(page.getByRole("heading", { name: "Local network", exact: true }))
.toBeInTheDocument();
await expect.element(page.getByText("Default", { exact: true })).toBeInTheDocument();
await page.getByRole("button", { name: "Set as default" }).first().click();
await expect.element(page.getByText("http://127.0.0.1:3773/").first()).toBeInTheDocument();
});
it("shows diagnostics inside About with a single logs-folder action", async () => {
setServerConfigSnapshot(createBaseServerConfig());
@@ -696,8 +461,6 @@ describe("GeneralSettingsPanel observability", () => {
mode: "network-accessible",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
});
let pairingLinks: Array<AuthAccessSnapshot["pairingLinks"][number]> = [];
@@ -803,7 +566,7 @@ describe("GeneralSettingsPanel observability", () => {
.element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))
.toBeInTheDocument();
await expect
.element(page.getByRole("button", { name: /^Copy pairing URL for:/ }))
.element(page.getByRole("button", { name: /^(Copy|Show link)$/ }))
.toBeInTheDocument();
await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
});
@@ -814,8 +577,6 @@ describe("GeneralSettingsPanel observability", () => {
mode: "network-accessible",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
});
let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
@@ -916,77 +677,9 @@ describe("GeneralSettingsPanel observability", () => {
await vi.waitFor(() => {
expect(desktopBridge.setServerExposureMode).toHaveBeenCalledWith("network-accessible");
});
await expect.element(page.getByText("http://192.168.1.44:3773")).toBeInTheDocument();
});
it("adds desktop ssh environments from the add-environment dialog", async () => {
const discoverSshHosts = vi.fn().mockResolvedValue([
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
source: "ssh-config" as const,
},
]);
window.desktopBridge = createDesktopBridgeStub({
discoverSshHosts,
});
mockConnectDesktopSshEnvironment.mockResolvedValue({
environmentId: EnvironmentId.make("environment-devbox"),
label: "Build box",
wsBaseUrl: "ws://127.0.0.1:3774/",
httpBaseUrl: "http://127.0.0.1:3774/",
createdAt: "2036-04-07T00:00:00.000Z",
lastConnectedAt: "2036-04-07T00:00:00.000Z",
desktopSsh: {
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await page.getByRole("button", { name: "Add environment", exact: true }).click();
const addEnvironmentDialog = page.getByRole("dialog", { name: "Add Environment" });
await expect
.element(addEnvironmentDialog.getByRole("heading", { name: "Add Environment", exact: true }))
.element(page.getByText("Reachable at http://192.168.1.44:3773"))
.toBeInTheDocument();
await addEnvironmentDialog.getByRole("button", { name: /^SSH\b/ }).click();
await vi.waitFor(() => {
expect(discoverSshHosts).toHaveBeenCalledTimes(1);
});
await expect
.element(page.getByRole("heading", { name: "devbox", exact: true }))
.toBeInTheDocument();
await addEnvironmentDialog.getByLabelText("SSH host or alias").fill("devbox.example.com");
await addEnvironmentDialog.getByLabelText("Username").fill("julius");
await addEnvironmentDialog.getByLabelText("Port").fill("2222");
await addEnvironmentDialog
.getByRole("button", { name: "Add environment", exact: true })
.first()
.click();
await vi.waitFor(() => {
expect(mockConnectDesktopSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ label: "" },
);
});
});
it("opens the logs folder in the preferred editor", async () => {
@@ -386,9 +386,6 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap
? ["Diff line wrapping"]
: []),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
? ["Diff whitespace changes"]
: []),
...(settings.autoOpenPlanSidebar !== DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar
? ["Auto-open task panel"]
: []),
@@ -418,7 +415,6 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.confirmThreadDelete,
settings.addProjectBaseDirectory,
settings.defaultThreadEnvMode,
settings.diffIgnoreWhitespace,
settings.diffWordWrap,
settings.enableAssistantStreaming,
settings.timestampFormat,
@@ -893,32 +889,6 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
title="Hide whitespace changes"
description="Set whether the diff panel ignores whitespace-only edits by default."
resetAction={
settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace ? (
<SettingResetButton
label="diff whitespace changes"
onClick={() =>
updateSettings({
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
})
}
/>
) : null
}
control={
<Switch
checked={settings.diffIgnoreWhitespace}
onCheckedChange={(checked) =>
updateSettings({ diffIgnoreWhitespace: Boolean(checked) })
}
aria-label="Hide whitespace changes by default"
/>
}
/>
<SettingsRow
title="Assistant output"
description="Show token-by-token output while a response is in progress."
@@ -57,8 +57,6 @@ const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
jj: JujutsuIcon,
};
const SOURCE_CONTROL_SKELETON_ROWS = ["primary", "secondary"] as const;
function optionLabel(value: Option.Option<string>): string | null {
return Option.getOrNull(value);
}
@@ -159,11 +157,6 @@ function itemSummary({
</>
);
}
if (!item.executable) {
return <span>{item.installHint}</span>;
}
if (auth.status === "unauthenticated") {
return <span>Sign in with the {item.executable} CLI to enable pull request actions.</span>;
}
@@ -239,8 +232,8 @@ function SourceControlSectionSkeleton({
}) {
return (
<SettingsSection title={title} headerAction={headerAction}>
{SOURCE_CONTROL_SKELETON_ROWS.map((row) => (
<div key={row} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
{Array.from({ length: 2 }, (_, index) => (
<div key={index} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1 space-y-2">
<div className="flex items-center gap-2">
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff. Show more