Compare commits

...
41 Commits
Author SHA1 Message Date
Julius Marmingeandcodex 9678d3b144 Fix visited timestamp under clock skew
Co-authored-by: codex <[email protected]>
2026-04-29 16:33:06 -07:00
Julius Marminge 0f6f2035e4 Log SSH tunnel lifecycle and surface bootstrap failures
- Add structured logging around SSH command, tunnel, and pairing flows
- Let desktop SSH bootstrap failures propagate instead of timing out locally
- Update reconnect test to expect the underlying SSH timeout error
2026-04-29 14:58:23 -07:00
Julius Marminge 873158254c Add hosted SSH pairing state handling
- Support remote T3 runner selection for hosted pairing
- Surface SSH/environment disconnect states in the UI
- Improve websocket snapshot and password prompt error handling
2026-04-29 13:14:52 -07:00
Julius Marminge fce33cadab Refine hosted pairing and SSH connection flows
- Simplify add-environment dialog around remote and SSH pairing
- Auto-detect pairing URLs and improve SSH prompt handling
- Add coverage for tunnel and connection parsing behavior
2026-04-28 21:13:31 -07:00
Julius Marminge ae9545e184 Refactor SSH desktop pairing onto shared runtime
- Move SSH auth, config, and tunnel logic into `packages/ssh`
- Wire `apps/desktop` to the shared Effect runtime
- Add tests for config, auth, and tunnel behavior
2026-04-28 17:44:04 -07:00
Julius Marminge 0d692d0cc2 Disable Tailscale Serve on server shutdown
- Factor Tailscale command execution into a reusable helper
- Add tests for `tailscale serve off`
- Ensure hosted pairing UI cleans up Tailscale Serve after startup
2026-04-28 14:07:09 -07:00
Julius Marminge 290b9db72e Gate pair route fallback to hosted static app
- Avoid showing the hosted pairing flow outside the static app
- Keep the existing error boundary behavior for local builds
2026-04-28 13:59:42 -07:00
Julius Marminge e4b6dd4efa Split SSH helpers into dedicated modules
- Add auth, command, config, and tunnel exports
- Update desktop SSH environment imports
- Add tests for auth and command helpers
2026-04-28 11:54:58 -07:00
Julius Marminge 20edab789d Extract SSH helpers into shared package
- Move SSH parsing and discovery logic into `@t3tools/ssh`
- Reuse the shared helpers from the desktop app and release smoke checks
- Add coverage for host discovery, parsing, and package spec resolution
2026-04-28 11:34:52 -07:00
Julius Marminge ed93c76d15 Update release smoke to include tailscale package
- Relax settings UI text assertions to match reachable URLs
- Add `packages/tailscale/package.json` to release smoke coverage
2026-04-28 10:02:51 -07:00
Julius Marminge bae05b2e88 Handle malformed custom endpoints in pairing flow
- Ignore invalid custom HTTPS endpoint URLs when building desktop exposure
- Reset pairing submission state after backend errors and clarify retry guidance
- Add coverage for malformed endpoint inputs
2026-04-28 09:30:19 -07:00
Julius Marminge bff64a3f19 Harden pairing and SSH prompt flows
- Preserve Tailscale Serve port when toggling exposure
- Prevent reused hosted pairing tokens and double SSH responses
- Refine endpoint compatibility for HTTP custom URLs
2026-04-27 23:54:23 -07:00
Julius Marminge fc49669529 Add Tailscale Serve pairing support
- add desktop and server settings for hosted HTTPS pairing
- resolve and probe MagicDNS endpoints via shared Tailscale helpers
- update remote pairing docs and UI to surface the new setup flow
2026-04-27 22:24:40 -07:00
Julius Marminge db6a2a6dc1 Delay SSH tunnel disposal until pending setup settles
- Fix auth-failure matching for permission denied variants
- Allow remote port picker to run without a state file path
- Dispose only after pending tunnel creation resolves
2026-04-27 18:37:13 -07:00
Julius Marmingeandcodex 02e194c000 docs(remote): document desktop ssh launch
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex cebe697733 Fix PR CI failures
- use type-only imports required by verbatim module syntax
- fix SSH desktop build/typecheck regressions and auth test isolation
- tighten browser test selectors for the add-environment dialog

Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marminge 0f2ed34b4f Simplify ssh askpass to require cached secret
- Remove native password prompts from posix and Windows scripts
- Fail loudly when T3_SSH_AUTH_SECRET is missing
2026-04-27 18:14:50 -07:00
Julius Marminge 6ea09363b2 Extract SSH launch scripts
- Externalize askpass, remote launch, and runner helpers into script assets
- Copy SSH scripts into `dist-electron` for packaging
- Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marminge bf81ea87ea Extract desktop SSH bridge into dedicated class
- Move SSH IPC handlers and password prompt state out of main.ts
- Keep SSH environment launch and auth flow owned by sshEnvironment.ts
2026-04-27 18:14:50 -07:00
Julius Marminge eaf246a400 Format settings and IPC imports
- No functional change
- Keep staged code style consistent
2026-04-27 18:14:50 -07:00
Julius Marminge 3652081556 Tighten SSH setup dialog scrolling
- Add a capped scroll area for discovered SSH hosts
- Keep the manual SSH form always visible and simplify the dialog layout
- Ensure the scroll area viewport respects inherited max height
2026-04-27 18:14:50 -07:00
Julius Marminge efef363e59 Improve SSH launch diagnostics
- surface stdout when remote launch or pairing fails
- report parse errors and invalid remote port or credential values
2026-04-27 18:14:50 -07:00
Julius Marminge fcf9ce0b10 Use nightly remote T3 CLI in development
- Resolve dev remote package specs to `t3@nightly`
- Cover the dev fallback in sshEnvironment tests
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 3af684f852 Address SSH launch review feedback
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 7fd550ec31 Pin nightly SSH bootstrap to desktop version
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 1f5187f0fa Respect desktop release channel for SSH bootstrap
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marminge 2ab77a2255 Harden remote SSH environment recovery
- Validate SSH targets and known-host parsing more strictly
- Retry desktop SSH session refresh on auth failures
- Preserve saved registry state when bearer persistence fails
2026-04-27 18:14:50 -07:00
Julius Marminge 399264836a Add remote SSH environment launch support
- Discover SSH hosts and persist SSH targets
- Bootstrap tunneled SSH sessions with desktop password prompts
- Extend IPC and storage tests for SSH metadata
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 596a25fefa fix(desktop): include port in tailscale https endpoint
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 53523d1719 docs(remote): document tailscale endpoint add-on
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 17d557cc84 fix(web): dedupe advertised pairing helpers
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex df66553b3f feat(desktop): add tailscale endpoint addon
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 4fff6c8894 feat(remote): add advertised endpoint registry
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex 722b41412e feat(web): make advertised endpoint defaults explicit
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex b500b84e34 fix(web): hide endpoint rows when network access is disabled
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex f822b301fd docs(remote): describe advertised endpoint selection
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex e06c5780b3 feat(remote): add advertised endpoint registry
Co-authored-by: codex <[email protected]>
2026-04-27 18:14:50 -07:00
Julius Marmingeandcodex b0cf85f69a fix(web): treat hosted app as static
Co-authored-by: codex <[email protected]>
2026-04-26 23:34:48 -07:00
Julius Marmingeandcodex 008fc1c628 docs(remote): document hosted pairing constraints
Co-authored-by: codex <[email protected]>
2026-04-26 19:55:24 -07:00
Julius Marmingeandcodex a28ba8b083 fix(web): keep hosted pairing to secure endpoints
Co-authored-by: codex <[email protected]>
2026-04-26 19:43:08 -07:00
Julius Marmingeandcodex 814c206bde feat(web): support hosted pairing links
Co-authored-by: codex <[email protected]>
2026-04-26 19:31:35 -07:00
106 changed files with 9874 additions and 541 deletions

No files matched your search

+80
View File
@@ -93,6 +93,8 @@ Examples:
A known environment may or may not know the target `environmentId` before first successful connect.
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
### AccessEndpoint
An `AccessEndpoint` is one concrete way to reach a known environment.
@@ -108,6 +110,67 @@ A single environment may have many endpoints:
The environment stays the same. Only the access path changes.
### AdvertisedEndpoint
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
`AdvertisedEndpoint` is deliberately narrower than the full access model:
- it describes a concrete HTTP and WebSocket base URL pair
- it can mark the endpoint as default, available, or unavailable
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
When no user default is saved, endpoint selection should prefer:
1. endpoints compatible with the hosted HTTPS app
2. explicitly default endpoints
3. non-loopback endpoints
4. loopback endpoints only for same-machine clients
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
### Endpoint providers
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
The provider boundary is intentionally outside the core environment model:
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
- providers discover or synthesize endpoints
- providers return normalized `AdvertisedEndpoint` records
- the UI and pairing logic select from those records without knowing provider-specific commands
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
### Hosted pairing request
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
Example:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
Important constraints:
- the hosted app does not proxy HTTP or WebSocket traffic
- the backend must still be reachable directly from the browser
- HTTPS pages can only connect to HTTPS/WSS backends
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
- the token belongs in the URL hash so it is not sent to the hosted app origin
### RepositoryIdentity
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
@@ -151,6 +214,8 @@ Benefits:
- no client-specific process management required
- best fit for hosted or self-managed remote T3 deployments
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
### 2. Tunneled WebSocket access
Examples:
@@ -170,6 +235,8 @@ This is especially useful when:
- mobile must reach a desktop-hosted environment
- a machine should be reachable without exposing raw LAN or public ports
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
### 3. Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type.
@@ -185,6 +252,8 @@ After that, the renderer should still connect using an ordinary WebSocket URL ag
This keeps the renderer transport model consistent with every other access method.
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
## Launch methods
Launch methods answer a different question:
@@ -227,6 +296,15 @@ The recommended T3 flow is:
4. Desktop establishes local port forwarding.
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
Failure handling should be explicit:
- SSH authentication failure should surface before any environment is saved
- remote launch failure should include remote logs or the launcher command output when available
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
### 3. Client-managed local publish
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
@@ -267,6 +345,8 @@ T3 already supports a WebSocket auth token on the server. That should become a f
For publicly reachable environments, authenticated access should be treated as required.
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
## Relationship to Zed
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
+1
View File
@@ -22,3 +22,4 @@ apps/web/src/components/__screenshots__
__screenshots__/
.tanstack
squashfs-root/
.vercel
+350
View File
@@ -0,0 +1,350 @@
# Remote Endpoints and Hosted Static App Plan
## Purpose
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
```ts
type AdvertisedEndpointProvider =
| "loopback"
| "lan"
| "tailscale-ip"
| "tailscale-magicdns"
| "manual"
| "t3-tunnel";
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
type AdvertisedEndpointCompatibility = {
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
desktopApp: "compatible" | "unknown";
};
type AdvertisedEndpoint = {
id: string;
provider: AdvertisedEndpointProvider;
label: string;
httpBaseUrl: string;
wsBaseUrl: string;
visibility: AdvertisedEndpointVisibility;
compatibility: AdvertisedEndpointCompatibility;
source: "server" | "desktop" | "user";
status: "available" | "unavailable" | "unknown";
isDefault?: boolean;
};
```
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
## HTTP/WS and HTTPS/WSS Readiness
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
What is ready:
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
- Saved environments store both HTTP and WebSocket base URLs.
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
- WebSocket connections can use a dynamically issued `wsToken`.
- Server CORS support exists for browser remote auth endpoints.
What is not solved by code alone:
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
Policy:
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
- Mark endpoint compatibility at the product layer.
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
## Architecture
### Endpoint Sources
Endpoint records can come from several providers:
1. **Server runtime**
- headless bind host and port
- server-known explicit advertised host config
2. **Desktop shell**
- loopback backend URL
- LAN exposure state
- network interface discovery
- Tailscale CLI/status discovery
3. **User configuration**
- manually added hostnames
- preferred endpoint labels
- hidden/disabled endpoints
4. **Future cloud provider**
- T3 Tunnel endpoint
- billing/account status
- tunnel lifecycle state
### Endpoint Registry
Create a central runtime registry:
- `packages/contracts/src/remoteAccess.ts`
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
- `apps/server/src/remoteAccess/*` for server/headless endpoints
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
### Pairing Link Generation
Move hosted pairing link generation to endpoint-driven input:
```ts
buildHostedPairingUrl({
endpoint: AdvertisedEndpoint,
token,
});
```
Generated URL:
```text
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
```
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
## Phase 1: Endpoint Abstraction
### Goals
- Centralize URL normalization, protocol derivation, and compatibility checks.
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
- Preserve all current remote behavior.
### Tasks
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
2. Add shared helpers:
- normalize HTTP base URL
- derive WebSocket base URL
- classify loopback/private/LAN/Tailscale/public host
- classify hosted HTTPS compatibility
3. Add server endpoint discovery:
- loopback endpoint
- configured non-loopback endpoint
- explicit advertised host override
4. Add desktop endpoint discovery:
- local loopback
- LAN exposure endpoint
- endpoint status labels
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
- `app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
+76 -1
View File
@@ -22,9 +22,41 @@ If you are already running the desktop app and want to make it reachable from ot
1. Open **Settings** → **Connections**.
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
4. Use **Create Link** to generate a pairing link you can share with another device.
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
available. You can set another endpoint as the default from the expanded endpoint list.
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
automatically.
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
### Tailscale Endpoints
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
Depending on your Tailscale setup, this may include:
- the machine's `100.x.y.z` Tailnet IP
- a MagicDNS name
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
Serve to proxy HTTPS traffic to the local backend.
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
@@ -47,14 +79,42 @@ From there, connect from another device in either of these ways:
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
```bash
npx t3 serve --tailscale-serve
```
By default this configures Tailscale Serve on HTTPS port 443 and advertises
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
```bash
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
```
> Note
> The GUIs do not currently support adding projects on remote environments.
> For now, use `t3 project ...` on the server machine instead.
> Full GUI support for remote project management is coming soon.
### Option 3: Desktop-Managed SSH Launch
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
1. Open **Settings** → **Connections**.
2. Under **Remote Environments**, choose **Add environment**.
3. Select the SSH launch flow.
4. Enter the SSH target, such as `[email protected]`.
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
## How Pairing Works
The remote device does not need a long-lived secret up front.
@@ -67,6 +127,20 @@ Instead:
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
## Hosted Web App Pairing
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
```text
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
```
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
@@ -84,4 +158,5 @@ Use `t3 auth --help` and the nested subcommand help pages for the full reference
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
+4
View File
@@ -15,13 +15,17 @@
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
"electron": "40.6.0",
"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:",
@@ -70,6 +70,12 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
describe("clientPersistence", () => {
+12 -3
View File
@@ -57,6 +57,12 @@ function isPersistedSavedEnvironmentStorageRecord(
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.desktopSsh === undefined ||
(Predicate.isObject(value.desktopSsh) &&
typeof value.desktopSsh.alias === "string" &&
typeof value.desktopSsh.hostname === "string" &&
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
@@ -77,7 +83,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -85,6 +91,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
@@ -134,6 +141,7 @@ export function writeSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
encryptedBearerToken,
}
: record;
@@ -189,7 +197,7 @@ export function writeSavedEnvironmentSecret(input: {
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -197,7 +205,8 @@ export function writeSavedEnvironmentSecret(input: {
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
+83
View File
@@ -9,6 +9,7 @@ import {
readDesktopSettings,
resolveDefaultDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -35,6 +36,8 @@ describe("desktopSettings", () => {
it("defaults packaged nightly builds to the nightly update channel", () => {
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -45,12 +48,16 @@ describe("desktopSettings", () => {
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
@@ -61,6 +68,8 @@ describe("desktopSettings", () => {
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -68,6 +77,50 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "network-accessible",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("persists the requested Tailscale Serve preference", () => {
expect(
setDesktopTailscaleServePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
{ enabled: true, port: 8443 },
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
it("preserves the configured Tailscale Serve port when no new port is requested", () => {
expect(
setDesktopTailscaleServePreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
{ enabled: true },
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
@@ -78,6 +131,8 @@ describe("desktopSettings", () => {
setDesktopUpdateChannelPreference(
{
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
},
@@ -85,6 +140,8 @@ describe("desktopSettings", () => {
),
).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
});
@@ -103,6 +160,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -121,6 +180,8 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
});
@@ -140,8 +201,30 @@ describe("desktopSettings", () => {
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
});
});
it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(
settingsPath,
JSON.stringify({
tailscaleServeEnabled: true,
tailscaleServePort: 0,
}),
"utf8",
);
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
serverExposureMode: "local-only",
tailscaleServeEnabled: true,
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
});
});
});
+33
View File
@@ -6,12 +6,18 @@ import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
}
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
tailscaleServeEnabled: false,
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
};
@@ -35,6 +41,29 @@ export function setDesktopServerExposurePreference(
};
}
export function setDesktopTailscaleServePreference(
settings: DesktopSettings,
input: { readonly enabled: boolean; readonly port?: number },
): DesktopSettings {
const port =
input.port === undefined
? settings.tailscaleServePort
: normalizeTailscaleServePort(input.port);
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
? settings
: {
...settings,
tailscaleServeEnabled: input.enabled,
tailscaleServePort: port,
};
}
export function normalizeTailscaleServePort(value: unknown): number {
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
? value
: DEFAULT_TAILSCALE_SERVE_PORT;
}
export function setDesktopUpdateChannelPreference(
settings: DesktopSettings,
requestedChannel: DesktopUpdateChannel,
@@ -57,6 +86,8 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
readonly tailscaleServeEnabled?: unknown;
readonly tailscaleServePort?: unknown;
readonly updateChannel?: unknown;
readonly updateChannelConfiguredByUser?: unknown;
};
@@ -72,6 +103,8 @@ export function readDesktopSettings(settingsPath: string, appVersion: string): D
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
updateChannel:
updateChannelConfiguredByUser && parsedUpdateChannel !== null
? parsedUpdateChannel
+129 -5
View File
@@ -36,11 +36,14 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
import {
type DesktopSettings,
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
setDesktopTailscaleServePreference,
setDesktopUpdateChannelPreference,
writeDesktopSettings,
} from "./desktopSettings.ts";
@@ -55,7 +58,11 @@ import {
} from "./clientPersistence.ts";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
import { resolveDesktopServerExposure } from "./serverExposure.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
} from "./serverExposure.ts";
import { DesktopSshEnvironmentBridge, resolveRemoteT3CliPackageSpec } from "./sshEnvironment.ts";
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
@@ -76,6 +83,7 @@ import {
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
import { resolveDesktopAppBranding } from "./appBranding.ts";
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
syncShellEnvironment();
@@ -102,6 +110,8 @@ const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secr
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
@@ -110,6 +120,12 @@ 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() ??
"/Users/julius/Developer/t3code/apps/server/dist/bin.mjs";
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
isDevelopment,
appVersion: app.getVersion(),
@@ -297,6 +313,9 @@ function backendChildEnv(): NodeJS.ProcessEnv {
delete env.T3CODE_DESKTOP_WS_URL;
delete env.T3CODE_DESKTOP_LAN_ACCESS;
delete env.T3CODE_DESKTOP_LAN_HOST;
delete env.T3CODE_DESKTOP_HTTPS_ENDPOINTS;
delete env.T3CODE_TAILSCALE_SERVE;
delete env.T3CODE_TAILSCALE_SERVE_PORT;
return env;
}
@@ -305,9 +324,32 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
mode: desktopServerExposureMode,
endpointUrl: backendEndpointUrl,
advertisedHost: backendAdvertisedHost,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
};
}
async function getDesktopAdvertisedEndpoints() {
const exposure = resolveDesktopServerExposure({
mode: desktopServerExposureMode,
port: backendPort,
networkInterfaces: OS.networkInterfaces(),
...(backendAdvertisedHost ? { advertisedHostOverride: backendAdvertisedHost } : {}),
});
const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
port: backendPort,
exposure,
customHttpsEndpointUrls: resolveCustomHttpsEndpointUrls(),
});
const tailscaleEndpoints = await resolveTailscaleAdvertisedEndpoints({
port: backendPort,
serveEnabled: desktopSettings.tailscaleServeEnabled,
servePort: desktopSettings.tailscaleServePort,
networkInterfaces: OS.networkInterfaces(),
});
return [...coreEndpoints, ...tailscaleEndpoints];
}
function getDesktopSecretStorage() {
return {
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
@@ -321,9 +363,19 @@ function resolveAdvertisedHostOverride(): string | undefined {
return override && override.length > 0 ? override : undefined;
}
function resolveCustomHttpsEndpointUrls(): readonly string[] {
return (process.env.T3CODE_DESKTOP_HTTPS_ENDPOINTS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
}
async function applyDesktopServerExposureMode(
mode: DesktopServerExposureMode,
options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
options?: {
readonly persist?: boolean;
readonly rejectIfUnavailable?: boolean;
},
): Promise<DesktopServerExposureState> {
const advertisedHostOverride = resolveAdvertisedHostOverride();
const requestedMode = mode;
@@ -361,6 +413,17 @@ async function applyDesktopServerExposureMode(
return getDesktopServerExposureState();
}
async function applyDesktopTailscaleServeEnabled(
nextSettings: DesktopSettings,
): Promise<DesktopServerExposureState> {
desktopSettings = nextSettings;
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
relaunchDesktopApp(
desktopSettings.tailscaleServeEnabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled",
);
return getDesktopServerExposureState();
}
function relaunchDesktopApp(reason: string): void {
writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
setImmediate(() => {
@@ -373,6 +436,7 @@ function relaunchDesktopApp(reason: string): void {
`desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
);
})
.then(() => desktopSshEnvironmentBridge.dispose().catch(() => undefined))
.finally(() => {
restoreStdIoCapture?.();
if (isDevelopment) {
@@ -629,6 +693,22 @@ let updateInstallInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
const desktopSshEnvironmentBridge = new DesktopSshEnvironmentBridge({
getMainWindow: () => mainWindow,
resolveCliRunner: (): RemoteT3RunnerOptions => {
if (isDevelopment && DEV_REMOTE_T3_SERVER_ENTRY_PATH.length > 0) {
return { nodeScriptPath: DEV_REMOTE_T3_SERVER_ENTRY_PATH };
}
return {
packageSpec: resolveRemoteT3CliPackageSpec({
appVersion: app.getVersion(),
updateChannel: desktopSettings.updateChannel,
isDevelopment,
}),
};
},
});
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateInstallInFlight) return "install";
if (updateDownloadInFlight) return "download";
@@ -1180,7 +1260,10 @@ async function checkForUpdates(reason: string): Promise<boolean> {
}
}
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
async function downloadAvailableUpdate(): Promise<{
accepted: boolean;
completed: boolean;
}> {
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
return { accepted: false, completed: false };
}
@@ -1202,7 +1285,10 @@ async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed
}
}
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
async function installDownloadedUpdate(): Promise<{
accepted: boolean;
completed: boolean;
}> {
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
return { accepted: false, completed: false };
}
@@ -1402,6 +1488,8 @@ function startBackend(): void {
t3Home: BASE_DIR,
host: backendBindHost,
desktopBootstrapToken: backendBootstrapToken,
tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,
tailscaleServePort: desktopSettings.tailscaleServePort,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
@@ -1647,6 +1735,8 @@ function registerIpcHandlers(): void {
},
);
desktopSshEnvironmentBridge.registerIpcHandlers(ipcMain);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
@@ -1669,6 +1759,31 @@ function registerIpcHandlers(): void {
return nextState;
});
ipcMain.removeHandler(SET_TAILSCALE_SERVE_ENABLED_CHANNEL);
ipcMain.handle(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, async (_event, rawInput: unknown) => {
if (typeof rawInput !== "object" || rawInput === null) {
throw new Error("Invalid Tailscale Serve input.");
}
const input = rawInput as {
readonly enabled?: unknown;
readonly port?: unknown;
};
if (typeof input.enabled !== "boolean") {
throw new Error("Invalid Tailscale Serve input.");
}
const nextSettings = setDesktopTailscaleServePreference(desktopSettings, {
enabled: input.enabled,
...(typeof input.port === "number" ? { port: input.port } : {}),
});
if (nextSettings === desktopSettings) {
return getDesktopServerExposureState();
}
return applyDesktopTailscaleServeEnabled(nextSettings);
});
ipcMain.removeHandler(GET_ADVERTISED_ENDPOINTS_CHANNEL);
ipcMain.handle(GET_ADVERTISED_ENDPOINTS_CHANNEL, async () => getDesktopAdvertisedEndpoints());
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -1959,7 +2074,10 @@ function createWindow(): BrowserWindow {
const externalUrl = getSafeExternalUrl(params.linkURL);
if (externalUrl) {
menuTemplate.push(
{ label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
{
label: "Copy Link",
click: () => clipboard.writeText(params.linkURL),
},
{ type: "separator" },
);
}
@@ -2019,6 +2137,9 @@ function createWindow(): BrowserWindow {
}
window.on("closed", () => {
desktopSshEnvironmentBridge.cancelPendingPasswordPrompts(
"SSH authentication was cancelled because the app window closed.",
);
if (mainWindow === window) {
mainWindow = null;
}
@@ -2110,6 +2231,7 @@ app.on("before-quit", () => {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
});
@@ -2159,6 +2281,7 @@ if (process.platform !== "win32") {
clearUpdatePollTimer();
cancelBackendReadinessWait();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
@@ -2169,6 +2292,7 @@ if (process.platform !== "win32") {
writeDesktopLogHeader("SIGTERM received");
clearUpdatePollTimer();
stopBackend();
void desktopSshEnvironmentBridge.dispose().catch(() => undefined);
restoreStdIoCapture?.();
app.quit();
});
+40
View File
@@ -22,8 +22,19 @@ 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";
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
@@ -51,8 +62,37 @@ 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: (target, options) =>
ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
disconnectSshEnvironment: (target) =>
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
onSshPasswordPrompt: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
if (typeof request !== "object" || request === null) return;
listener(request as Parameters<typeof listener>[0]);
};
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
};
},
resolveSshPasswordPrompt: (requestId, password) =>
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
setTailscaleServeEnabled: (input) =>
ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
+120 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
import {
resolveDesktopCoreAdvertisedEndpoints,
resolveDesktopServerExposure,
resolveLanAdvertisedHost,
} from "./serverExposure.ts";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
@@ -74,6 +78,121 @@ describe("resolveLanAdvertisedHost", () => {
});
});
describe("resolveDesktopCoreAdvertisedEndpoints", () => {
it("advertises loopback and LAN endpoints without provider-specific assumptions", () => {
const exposure = resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
});
expect(
resolveDesktopCoreAdvertisedEndpoints({
port: 3773,
exposure,
customHttpsEndpointUrls: [
"https://desktop.example.ts.net",
"http://desktop.example.test:3773",
"not-a-url",
],
}),
).toEqual([
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
description: "Loopback endpoint for this desktop app.",
},
{
id: "desktop-lan:http://192.168.1.44:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
},
httpBaseUrl: "http://192.168.1.44:3773/",
wsBaseUrl: "ws://192.168.1.44:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
description: "Reachable from devices on the same network.",
},
{
id: "manual:https://desktop.example.ts.net",
label: "Custom HTTPS",
provider: {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "https://desktop.example.ts.net/",
wsBaseUrl: "wss://desktop.example.ts.net/",
reachability: "public",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "user",
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
},
{
id: "manual:http://desktop.example.test:3773",
label: "Custom HTTPS",
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 HTTPS endpoint for this desktop backend.",
},
]);
});
});
describe("resolveDesktopServerExposure", () => {
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
expect(
+108 -1
View File
@@ -1,5 +1,13 @@
import type { NetworkInterfaceInfo } from "node:os";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
} from "@t3tools/contracts";
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
@@ -13,6 +21,26 @@ export interface DesktopServerExposure {
readonly advertisedHost: string | null;
}
export interface DesktopAdvertisedEndpointInput {
readonly port: number;
readonly exposure: DesktopServerExposure;
readonly customHttpsEndpointUrls?: readonly string[];
}
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
};
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "manual",
label: "Manual",
kind: "manual",
isAddon: false,
};
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
@@ -21,6 +49,14 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
const isUsableLanIpv4Address = (address: string): boolean =>
!address.startsWith("127.") && !address.startsWith("169.254.");
function isHttpsEndpointUrl(value: string): boolean {
try {
return new URL(value).protocol === "https:";
} catch {
return false;
}
}
export function resolveLanAdvertisedHost(
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
explicitHost: string | undefined,
@@ -78,3 +114,74 @@ 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 {
endpoints.push(
createManualEndpoint({
id: `manual:${customEndpointUrl}`,
label: "Custom HTTPS",
httpBaseUrl: customEndpointUrl,
reachability: "public",
...(isHttpsEndpointUrl(customEndpointUrl)
? ({ hostedHttpsCompatibility: "compatible" } as const)
: {}),
status: "unknown",
description: "User-configured HTTPS endpoint for this desktop backend.",
}),
);
} catch {
// Ignore malformed user-configured endpoints without dropping valid endpoints.
}
}
return endpoints;
}
+86
View File
@@ -0,0 +1,86 @@
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 { discoverDesktopSshHosts } 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("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",
},
]);
});
});
+379
View File
@@ -0,0 +1,379 @@
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;
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>;
}
/**
* 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;
return await this.manager.ensureEnvironment(target, {
issuePairingToken,
});
});
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 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 });
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
if (window.isMinimized()) {
window.restore();
}
window.focus();
});
}
}
@@ -0,0 +1,10 @@
#!/bin/sh
# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
# from the renderer's in-app prompt. We never expose a native dialog here — if
# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
if [ "${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
printf "%s\n" "$T3_SSH_AUTH_SECRET"
exit 0
fi
printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\n' >&2
exit 1
@@ -0,0 +1,2 @@
@echo off
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*
@@ -0,0 +1,10 @@
# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when T3 Code re-runs
# ssh with a cached password from the renderer's in-app prompt. We never expose
# a native dialog here — if T3_SSH_AUTH_SECRET is missing, that's a caller bug
# and we fail loudly.
if ($null -ne $env:T3_SSH_AUTH_SECRET) {
[Console]::Out.WriteLine($env:T3_SSH_AUTH_SECRET)
exit 0
}
[Console]::Error.WriteLine("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.")
exit 1
@@ -0,0 +1,34 @@
set -eu
STATE_KEY="$1"
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
SERVER_HOME="$STATE_DIR/server-home"
PORT_FILE="$STATE_DIR/port"
PID_FILE="$STATE_DIR/pid"
LOG_FILE="$STATE_DIR/server.log"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR" "$SERVER_HOME"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
pick_port() {
node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE'
@@T3_PICK_PORT_SCRIPT@@
NODE
}
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
if [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
:
else
REMOTE_PORT="$(pick_port)" || true
if [ -z "$REMOTE_PORT" ]; then
printf 'Failed to find an available port on the remote host. Ensure node is available on PATH.\n' >&2
exit 1
fi
nohup env T3CODE_NO_BROWSER=1 "$RUNNER_FILE" serve --host 127.0.0.1 --port "$REMOTE_PORT" --base-dir "$SERVER_HOME" >>"$LOG_FILE" 2>&1 < /dev/null &
REMOTE_PID="$!"
printf '%s\n' "$REMOTE_PID" >"$PID_FILE"
printf '%s\n' "$REMOTE_PORT" >"$PORT_FILE"
fi
printf '{"remotePort":%s}\n' "$REMOTE_PORT"
@@ -0,0 +1,10 @@
set -eu
STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"
SERVER_HOME="$STATE_DIR/server-home"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR" "$SERVER_HOME"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
"$RUNNER_FILE" auth pairing create --base-dir "$SERVER_HOME" --json
@@ -0,0 +1,31 @@
const fs = require("node:fs");
const net = require("node:net");
const filePath = process.argv[2] ?? "";
const defaultPort = Number.parseInt(process.argv[3] ?? "", 10);
const scanWindow = Number.parseInt(process.argv[4] ?? "", 10);
const raw = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8").trim() : "";
const preferred = Number.parseInt(raw, 10);
const start = Number.isInteger(preferred) ? preferred : defaultPort;
const end = start + scanWindow;
function tryPort(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", () => resolve(false));
server.listen(port, "127.0.0.1", () => {
server.close((error) => resolve(error ? false : port));
});
});
}
(async () => {
for (let port = start; port < end; port += 1) {
const available = await tryPort(port);
if (available) {
process.stdout.write(String(port));
return;
}
}
process.exit(1);
})().catch(() => process.exit(1));
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
if command -v t3 >/dev/null 2>&1; then
exec t3 "$@"
fi
if command -v npx >/dev/null 2>&1; then
exec npx --yes @@T3_PACKAGE_SPEC@@ "$@"
fi
if command -v npm >/dev/null 2>&1; then
exec npm exec --yes @@T3_PACKAGE_SPEC@@ -- "$@"
fi
printf 'Remote host is missing the t3 CLI and could not install @@T3_PACKAGE_SPEC@@ because npx and npm are unavailable on PATH.\n' >&2
exit 1
@@ -0,0 +1,122 @@
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
import {
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
resolveTailscaleAdvertisedEndpoints,
} from "./tailscaleEndpointProvider.ts";
describe("tailscale endpoint provider", () => {
it("detects Tailnet IPv4 addresses", () => {
expect(isTailscaleIpv4Address("100.64.0.1")).toBe(true);
expect(isTailscaleIpv4Address("100.127.255.254")).toBe(true);
expect(isTailscaleIpv4Address("100.128.0.1")).toBe(false);
expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false);
});
it("parses MagicDNS names from tailscale status", async () => {
expect(
Effect.runSync(
parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })),
),
).toBe("desktop.tail.ts.net");
expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull();
await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined();
});
it("resolves Tailscale endpoints as add-on advertised endpoints", async () => {
await expect(
resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {
tailscale0: [
{
address: "100.100.100.100",
family: "IPv4",
internal: false,
netmask: "255.192.0.0",
cidr: "100.100.100.100/10",
mac: "00:00:00:00:00:00",
},
],
},
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
}),
).resolves.toEqual([
{
id: "tailscale-ip:http://100.100.100.100:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.100.100.100:3773/",
wsBaseUrl: "ws://100.100.100.100:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "Reachable from devices on the same Tailnet.",
},
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "requires-configuration",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "unavailable",
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
},
]);
});
it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => {
await expect(
resolveTailscaleAdvertisedEndpoints({
port: 3773,
networkInterfaces: {},
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
serveEnabled: true,
probe: async () => true,
}),
).resolves.toEqual([
{
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
label: "Tailscale HTTPS",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "https://desktop.tail.ts.net/",
wsBaseUrl: "wss://desktop.tail.ts.net/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "compatible",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
description: "HTTPS endpoint served by Tailscale Serve.",
},
]);
});
});
@@ -0,0 +1,142 @@
import type { NetworkInterfaceInfo } from "node:os";
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
probeTailscaleHttpsEndpoint,
readTailscaleStatus,
} from "@t3tools/tailscale";
import { Effect, Layer } from "effect";
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici);
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
};
function createTailscaleEndpoint(
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
): AdvertisedEndpoint {
return createAdvertisedEndpoint({
...input,
provider: TAILSCALE_ENDPOINT_PROVIDER,
source: "desktop-addon",
});
}
export function resolveTailscaleIpAdvertisedEndpoints(input: {
readonly port: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
}): readonly AdvertisedEndpoint[] {
const seen = new Set<string>();
const endpoints: AdvertisedEndpoint[] = [];
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
if (!interfaceAddresses) continue;
for (const address of interfaceAddresses) {
if (address.internal) continue;
if (address.family !== "IPv4") continue;
if (!isTailscaleIpv4Address(address.address)) continue;
if (seen.has(address.address)) continue;
seen.add(address.address);
endpoints.push(
createTailscaleEndpoint({
id: `tailscale-ip:http://${address.address}:${input.port}`,
label: "Tailscale IP",
httpBaseUrl: `http://${address.address}:${input.port}`,
reachability: "private-network",
status: "available",
description: "Reachable from devices on the same Tailnet.",
}),
);
}
}
return endpoints;
}
export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: {
readonly dnsName: string | null;
readonly serveEnabled: boolean;
readonly servePort?: number;
readonly probe?: (baseUrl: string) => Promise<boolean>;
}): Promise<AdvertisedEndpoint | null> {
if (!input.dnsName) {
return null;
}
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
magicDnsName: input.dnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
});
const isReachable = input.serveEnabled
? await (input.probe?.(httpBaseUrl) ??
Effect.runPromise(
probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
Effect.provide(TailscaleDesktopLayer),
),
))
: false;
return createTailscaleEndpoint({
id: `tailscale-magicdns:${httpBaseUrl}`,
label: "Tailscale HTTPS",
httpBaseUrl,
reachability: "private-network",
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
status: isReachable ? "available" : "unavailable",
description: isReachable
? "HTTPS endpoint served by Tailscale Serve."
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
});
}
export async function resolveTailscaleAdvertisedEndpoints(input: {
readonly port: number;
readonly serveEnabled?: boolean;
readonly servePort?: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
readonly statusJson?: string | null;
readonly probe?: (baseUrl: string) => Promise<boolean>;
}): Promise<readonly AdvertisedEndpoint[]> {
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
const dnsName =
input.statusJson === undefined
? await Effect.runPromise(
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed(null)),
Effect.provide(TailscaleDesktopLayer),
),
)
: input.statusJson
? await Effect.runPromise(
parseTailscaleMagicDnsName(input.statusJson).pipe(
Effect.catch(() => Effect.succeed(null)),
),
)
: null;
const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({
dnsName,
serveEnabled: input.serveEnabled === true,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
...(input.probe === undefined ? {} : { probe: input.probe }),
});
return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints;
}
+1
View File
@@ -13,6 +13,7 @@ export default defineConfig([
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
copy: [{ from: "src/sshScripts/*", to: "dist-electron/sshScripts" }],
},
{
...shared,
+1
View File
@@ -40,6 +40,7 @@
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
+36
View File
@@ -46,6 +46,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -87,6 +89,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -108,6 +112,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(true),
logWebSocketEvents: Option.some(true),
tailscaleServeEnabled: Option.some(true),
tailscaleServePort: Option.some(8443),
},
Option.some("Debug"),
).pipe(
@@ -149,6 +155,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
});
}),
);
@@ -161,6 +169,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
@@ -176,6 +186,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(false),
logWebSocketEvents: Option.some(false),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -212,6 +224,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -229,6 +243,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
@@ -246,6 +262,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -281,6 +299,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(join(baseDir, "dev"), resolved.stateDir);
}),
@@ -305,6 +325,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -346,6 +368,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: false,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
@@ -361,6 +385,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.some("Debug"),
).pipe(
@@ -399,6 +425,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -432,6 +460,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
@@ -463,6 +493,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
@@ -485,6 +517,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
{
@@ -522,6 +556,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
}),
);
+2
View File
@@ -76,6 +76,8 @@ const makeCliTestServerConfig = (baseDir: string) =>
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
} satisfies ServerConfigShape;
});
+47
View File
@@ -78,6 +78,8 @@ const BootstrapEnvelopeSchema = Schema.Struct({
desktopBootstrapToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
tailscaleServePort: Schema.optional(PortSchema),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
@@ -126,6 +128,17 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withAlias("log-ws-events"),
Flag.optional,
);
const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
Flag.withDescription(
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
),
Flag.optional,
);
const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
Flag.optional,
);
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
@@ -174,6 +187,14 @@ const EnvServerConfig = Config.all({
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
interface CliServerFlags {
@@ -187,6 +208,8 @@ interface CliServerFlags {
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
readonly tailscaleServeEnabled: Option.Option<boolean>;
readonly tailscaleServePort: Option.Option<number>;
}
interface CliAuthLocationFlags {
@@ -233,6 +256,8 @@ export const resolveServerConfig = (
bootstrapFd: flags.bootstrapFd ?? Option.none(),
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
} satisfies CliServerFlags;
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
@@ -323,6 +348,22 @@ export const resolveServerConfig = (
),
() => Boolean(devUrl),
);
const tailscaleServeEnabled = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServeEnabled,
Option.fromUndefinedOr(env.tailscaleServeEnabled),
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
),
() => false,
);
const tailscaleServePort = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.tailscaleServePort,
Option.fromUndefinedOr(env.tailscaleServePort),
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
),
() => 443,
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
@@ -365,6 +406,8 @@ export const resolveServerConfig = (
desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
tailscaleServePort,
};
return config;
@@ -386,6 +429,8 @@ const resolveCliAuthConfig = (
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
cliLogLevel,
);
@@ -766,6 +811,8 @@ const sharedServerCommandFlags = {
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
tailscaleServeEnabled: tailscaleServeFlag,
tailscaleServePort: tailscaleServePortFlag,
} as const;
const authLocationFlags = sharedServerLocationFlags;
+4
View File
@@ -65,6 +65,8 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly desktopBootstrapToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
readonly tailscaleServeEnabled: boolean;
readonly tailscaleServePort: number;
}
export const deriveServerPaths = Effect.fn(function* (
@@ -158,6 +160,8 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
@@ -30,6 +30,8 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
+34 -5
View File
@@ -75,6 +75,7 @@ import {
type ProjectionSnapshotQueryShape,
} from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
import { PersistenceSqlError } from "./persistence/Errors.ts";
import {
ProviderRegistry,
type ProviderRegistryShape,
@@ -209,10 +210,8 @@ const browserOtlpTracingLayer = Layer.mergeAll(
Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
);
const authTestLayer = ServerAuthLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(ServerSecretStoreLive),
);
const makeAuthTestLayer = () =>
ServerAuthLive.pipe(Layer.provide(SqlitePersistenceMemory), Layer.provide(ServerSecretStoreLive));
const makeBrowserOtlpPayload = (spanName: string) =>
Effect.gen(function* () {
@@ -367,6 +366,8 @@ const buildAppUnderTest = (options?: {
desktopBootstrapToken: defaultDesktopBootstrapToken,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
...options?.config,
};
const layerConfig = Layer.succeed(ServerConfig, config);
@@ -539,7 +540,7 @@ const buildAppUnderTest = (options?: {
...options?.layers?.repositoryIdentityResolver,
}),
),
Layer.provideMerge(authTestLayer),
Layer.provideMerge(makeAuthTestLayer()),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(layerConfig),
@@ -2983,6 +2984,34 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("routes websocket rpc orchestration shell snapshot errors", () =>
Effect.gen(function* () {
const projectionError = new PersistenceSqlError({
operation: "ProjectionSnapshotQuery.getShellSnapshot:test",
detail: "failed to read projection shell snapshot",
});
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getShellSnapshot: () => Effect.fail(projectionError),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(Stream.runCollect),
).pipe(Effect.result),
);
assertTrue(result._tag === "Failure");
assertTrue(result.failure._tag === "OrchestrationGetSnapshotError");
assertTrue(result.failure.cause instanceof Error);
assert.include(result.failure.cause.message, projectionError.message);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("enriches replayed project events with repository identity metadata", () =>
Effect.gen(function* () {
const repositoryIdentity = {
+44
View File
@@ -77,6 +77,7 @@ import {
orchestrationSnapshotRouteLayer,
} from "./orchestration/http.ts";
import { NetService } from "@t3tools/shared/Net";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
@@ -306,6 +307,48 @@ export const makeServerLayer = Layer.unwrap(
() => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
),
);
const tailscaleServeLayer = config.tailscaleServeEnabled
? Layer.effectDiscard(
Effect.acquireRelease(
ensureTailscaleServe({
localPort: config.port,
servePort: config.tailscaleServePort,
localHost: "127.0.0.1",
}).pipe(
Effect.as(true),
Effect.tap(() =>
Effect.logInfo("Tailscale Serve configured", {
localPort: config.port,
servePort: config.tailscaleServePort,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to configure Tailscale Serve", {
cause,
localPort: config.port,
servePort: config.tailscaleServePort,
}).pipe(Effect.as(false)),
),
),
(configured) =>
configured
? disableTailscaleServe.pipe(
Effect.tap(() =>
Effect.logInfo("Tailscale Serve disabled", {
servePort: config.tailscaleServePort,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to disable Tailscale Serve", {
cause,
servePort: config.tailscaleServePort,
}),
),
)
: Effect.void,
),
)
: Layer.empty;
const serverApplicationLayer = Layer.mergeAll(
HttpRouter.serve(makeRoutesLayer, {
@@ -313,6 +356,7 @@ export const makeServerLayer = Layer.unwrap(
}),
httpListeningLayer,
runtimeStateLayer,
tailscaleServeLayer,
);
return serverApplicationLayer.pipe(
+3
View File
@@ -667,6 +667,9 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
ORCHESTRATION_WS_METHODS.subscribeShell,
Effect.gen(function* () {
const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration shell snapshot load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
@@ -10,6 +10,12 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
};
function createLocalStorageStub(): Storage {
+14 -3
View File
@@ -19,6 +19,14 @@ const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
wsBaseUrl: Schema.String,
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
desktopSsh: Schema.optionalKey(
Schema.Struct({
alias: Schema.String,
hostname: Schema.String,
username: Schema.NullOr(Schema.String),
port: Schema.NullOr(Schema.Number),
}),
),
bearerToken: Schema.optionalKey(Schema.String),
});
type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type;
@@ -37,7 +45,7 @@ function hasWindow(): boolean {
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -45,6 +53,7 @@ function toPersistedSavedEnvironmentRecord(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}
export function readBrowserClientSettings(): ClientSettings | null {
@@ -135,6 +144,7 @@ export function writeBrowserSavedEnvironmentRegistry(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
bearerToken,
}
: toPersistedSavedEnvironmentRecord(record);
@@ -166,7 +176,7 @@ export function writeBrowserSavedEnvironmentSecret(
return record;
}
found = true;
return {
const nextRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
@@ -174,7 +184,8 @@ export function writeBrowserSavedEnvironmentSecret(
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken: secret,
} satisfies BrowserSavedEnvironmentRecord;
};
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
}),
});
return found;
+91 -3
View File
@@ -102,7 +102,7 @@ import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon, WifiOffIcon } from "lucide-react";
import { cn, randomUUID } from "~/lib/utils";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
@@ -178,6 +178,8 @@ import {
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { retainThreadDetailSubscription } from "../environments/runtime/service";
import { RightPanelSheet } from "./RightPanelSheet";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert";
import { Button } from "./ui/button";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
@@ -185,6 +187,10 @@ 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 label: string;
readonly connectionState: "connecting" | "disconnected" | "error";
};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
@@ -853,6 +859,37 @@ 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 activeEnvironmentUnavailableLabel = activeSavedEnvironmentRecord
? resolveEnvironmentOptionLabel({
isPrimary: false,
environmentId: activeSavedEnvironmentRecord.environmentId,
runtimeLabel: activeSavedEnvironmentRuntime?.descriptor?.label ?? null,
savedLabel: activeSavedEnvironmentRecord.label,
})
: null;
const activeEnvironmentUnavailableState: EnvironmentUnavailableState | null =
activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel
? {
label: activeEnvironmentUnavailableLabel,
connectionState:
activeSavedEnvironmentConnectionState === "connecting" ||
activeSavedEnvironmentConnectionState === "error"
? activeSavedEnvironmentConnectionState
: "disconnected",
}
: null;
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
@@ -1019,7 +1056,10 @@ export default function ChatView(props: ChatViewProps) {
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
markThreadVisited(scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)));
markThreadVisited(
scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
activeLatestTurn.completedAt,
);
}, [
activeLatestTurn?.completedAt,
activeThreadLastVisitedAt,
@@ -2333,6 +2373,13 @@ export default function ChatView(props: ChatViewProps) {
const localApi = readLocalApi();
if (!api || !localApi || !activeThread || isRevertingCheckpoint) return;
if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
setThreadError(
activeThread.id,
`Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
);
return;
}
if (phase === "running" || isSendBusy || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
@@ -2368,6 +2415,8 @@ export default function ChatView(props: ChatViewProps) {
},
[
activeThread,
activeEnvironmentUnavailable,
activeEnvironmentUnavailableLabel,
environmentId,
isConnecting,
isRevertingCheckpoint,
@@ -2380,7 +2429,15 @@ export default function ChatView(props: ChatViewProps) {
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const api = readEnvironmentApi(environmentId);
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (
!api ||
!activeThread ||
isSendBusy ||
isConnecting ||
activeEnvironmentUnavailable ||
sendInFlightRef.current
)
return;
if (activePendingProgress) {
onAdvanceActivePendingUserInput();
return;
@@ -3331,6 +3388,36 @@ export default function ChatView(props: ChatViewProps) {
{/* Input bar */}
<div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}>
{activeEnvironmentUnavailableState ? (
<Alert
variant={
activeEnvironmentUnavailableState.connectionState === "error"
? "error"
: "warning"
}
className="mx-auto mb-2 max-w-208"
>
<WifiOffIcon />
<AlertTitle>
{activeEnvironmentUnavailableState.label} is{" "}
{activeEnvironmentUnavailableState.connectionState === "connecting"
? "connecting"
: "disconnected"}
</AlertTitle>
<AlertDescription>
Reconnect this environment before sending messages or running actions.
</AlertDescription>
<AlertAction>
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</AlertAction>
</Alert>
) : null}
<ChatComposer
ref={composerRef}
composerDraftTarget={composerDraftTarget}
@@ -3347,6 +3434,7 @@ export default function ChatView(props: ChatViewProps) {
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
@@ -8,6 +8,7 @@ function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionSt
attemptCount: 0,
closeCode: null,
closeReason: null,
connectionLabel: null,
connectedAt: null,
disconnectedAt: null,
hasConnected: false,
@@ -53,8 +53,16 @@ function describeExhaustedToast(): string {
return "Retries exhausted trying to reconnect";
}
function buildReconnectTitle(_status: WsConnectionStatus): string {
return "Disconnected from T3 Server";
function getConnectionDisplayName(status: WsConnectionStatus): string {
return status.connectionLabel?.trim() || "T3 Server";
}
function buildReconnectTitle(status: WsConnectionStatus): string {
return `Disconnected from ${getConnectionDisplayName(status)}`;
}
function buildRecoveredTitle(status: WsConnectionStatus): string {
return `Reconnected to ${getConnectionDisplayName(status)}`;
}
function describeRecoveredToast(
@@ -297,7 +305,7 @@ export function WebSocketConnectionCoordinator() {
},
description: describeExhaustedToast(),
timeout: 0,
title: "Disconnected from T3 Server",
title: buildReconnectTitle(status),
type: "error",
})
: stackedThreadToast({
@@ -334,7 +342,7 @@ export function WebSocketConnectionCoordinator() {
) {
const successToast = {
description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt),
title: "Reconnected to T3 Server",
title: buildRecoveredTitle(status),
type: "success" as const,
timeout: 0,
data: {
@@ -2,11 +2,13 @@ import type { AuthSessionState } from "@t3tools/contracts";
import React, { startTransition, useEffect, useRef, useState, useCallback } from "react";
import { APP_DISPLAY_NAME } from "../../branding";
import { addSavedEnvironment } from "../../environments/runtime";
import {
peekPairingTokenFromUrl,
stripPairingTokenFromUrl,
submitServerAuthCredential,
} from "../../environments/primary";
import { readHostedPairingRequest } from "../../hostedPairing";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
@@ -159,6 +161,116 @@ export function PairingRouteSurface({
);
}
export function HostedPairingRouteSurface() {
const hostedPairingRequestRef = useRef(readHostedPairingRequest());
const [status, setStatus] = useState<"pairing" | "paired" | "error">("pairing");
const [message, setMessage] = useState("Connecting to this backend.");
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.");
return;
}
if (tokenSubmittedRef.current) {
setStatus("error");
setMessage("This one-time pairing token was already submitted. Request a new pairing link.");
return;
}
setStatus("pairing");
setMessage("Connecting to this backend.");
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");
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>
) : !tokenSubmittedRef.current ? (
<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;
+21 -4
View File
@@ -285,6 +285,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
promptHasText: boolean;
isSendBusy: boolean;
isConnecting: boolean;
isEnvironmentUnavailable: boolean;
hasSendableContent: boolean;
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
@@ -304,6 +305,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
promptHasText={props.promptHasText}
isSendBusy={props.isSendBusy}
isConnecting={props.isConnecting}
isEnvironmentUnavailable={props.isEnvironmentUnavailable}
isPreparingWorktree={props.isPreparingWorktree}
hasSendableContent={props.hasSendableContent}
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
@@ -375,6 +377,10 @@ export interface ChatComposerProps {
isConnecting: boolean;
isSendBusy: boolean;
isPreparingWorktree: boolean;
environmentUnavailable: {
readonly label: string;
readonly connectionState: "connecting" | "disconnected" | "error";
} | null;
// Pending approvals / inputs
activePendingApproval: PendingApproval | null;
@@ -482,6 +488,7 @@ export const ChatComposer = memo(
isConnecting,
isSendBusy,
isPreparingWorktree,
environmentUnavailable,
activePendingApproval,
pendingApprovals,
pendingUserInputs,
@@ -1711,6 +1718,7 @@ export const ChatComposer = memo(
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,
)}
>
@@ -1860,11 +1868,19 @@ export const ChatComposer = memo(
? "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"
: 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
}
disabled={isConnecting || isComposerApprovalState}
/>
</div>
@@ -1969,6 +1985,7 @@ export const ChatComposer = memo(
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isPreparingWorktree={isPreparingWorktree}
hasSendableContent={composerSendState.hasSendableContent}
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
@@ -20,6 +20,7 @@ interface ComposerPrimaryActionsProps {
promptHasText: boolean;
isSendBusy: boolean;
isConnecting: boolean;
isEnvironmentUnavailable: boolean;
isPreparingWorktree: boolean;
hasSendableContent: boolean;
onPreviousPendingQuestion: () => void;
@@ -53,6 +54,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
promptHasText,
isSendBusy,
isConnecting,
isEnvironmentUnavailable,
isPreparingWorktree,
hasSendableContent,
onPreviousPendingQuestion,
@@ -91,6 +93,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
size="sm"
className={cn("rounded-full", compact ? "px-3" : "px-4")}
disabled={
isEnvironmentUnavailable ||
pendingAction.isResponding ||
(pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance)
}
@@ -128,7 +131,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")}
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
>
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
</Button>
@@ -141,7 +144,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"
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
>
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
</Button>
@@ -153,7 +156,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"
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
/>
}
>
@@ -161,7 +164,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
</MenuTrigger>
<MenuPopup align="end" side="top">
<MenuItem
disabled={isSendBusy || isConnecting}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable}
onClick={() => void onImplementPlanInNewThread()}
>
Implement in a new thread
@@ -176,15 +179,17 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={isSendBusy || isConnecting || !hasSendableContent}
disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent}
aria-label={
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
isEnvironmentUnavailable
? "Environment disconnected"
: isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
}
>
{isConnecting || isSendBusy ? (
@@ -0,0 +1,221 @@
import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { useEffect, useId, useRef, useState } from "react";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
function describeSshTarget(request: DesktopSshPasswordPromptRequest): string {
return request.username ? `${request.username}@${request.destination}` : request.destination;
}
function formatRemainingSeconds(seconds: number): string {
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}
function getPromptErrorMessage(error: unknown): string {
const message = error instanceof Error ? error.message : "SSH password prompt failed.";
return message.includes("expired") || message.includes("no longer pending")
? "This SSH password prompt expired. Try connecting again."
: message;
}
export function SshPasswordPromptDialog() {
const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
const [password, setPassword] = useState("");
const [isResponding, setIsResponding] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [responseError, setResponseError] = useState<string | null>(null);
const currentRequest = queue[0] ?? null;
const inputRef = useRef<HTMLInputElement | null>(null);
const isRespondingRef = useRef(false);
const formId = useId();
useEffect(() => {
const bridge = window.desktopBridge;
if (!bridge?.onSshPasswordPrompt) {
return;
}
return bridge.onSshPasswordPrompt((request) => {
setQueue((currentQueue) => [...currentQueue, request]);
});
}, []);
useEffect(() => {
setPassword("");
setResponseError(null);
if (!currentRequest) {
return;
}
setNow(Date.now());
const frame = window.requestAnimationFrame(() => {
inputRef.current?.focus();
inputRef.current?.select();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [currentRequest]);
useEffect(() => {
if (!currentRequest) {
return;
}
const interval = window.setInterval(() => {
setNow(Date.now());
}, 1_000);
return () => {
window.clearInterval(interval);
};
}, [currentRequest]);
const expiresAtMs = currentRequest ? Date.parse(currentRequest.expiresAt) : Number.NaN;
const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null;
const isExpired = remainingMs !== null && remainingMs <= 0;
const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
const remainingLabel =
remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
useEffect(() => {
if (isExpired) {
setResponseError("This SSH password prompt expired. Try connecting again.");
}
}, [isExpired]);
const removeCurrentPrompt = (requestId: string) => {
setQueue((currentQueue) =>
currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue,
);
setPassword("");
setResponseError(null);
};
const respond = async (nextPassword: string | null) => {
if (!currentRequest || isRespondingRef.current) {
return;
}
const requestId = currentRequest.requestId;
if (nextPassword !== null && isExpired) {
setResponseError("This SSH password prompt expired. Try connecting again.");
return;
}
isRespondingRef.current = true;
setIsResponding(true);
setResponseError(null);
try {
await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword);
removeCurrentPrompt(requestId);
} catch (error) {
if (nextPassword === null) {
removeCurrentPrompt(requestId);
} else {
setResponseError(getPromptErrorMessage(error));
}
} finally {
isRespondingRef.current = false;
setIsResponding(false);
}
};
const dismissExpiredPrompt = () => {
if (currentRequest) {
removeCurrentPrompt(currentRequest.requestId);
}
};
const cancelPrompt = () => {
if (isExpired) {
dismissExpiredPrompt();
return;
}
void respond(null);
};
const target = currentRequest ? describeSshTarget(currentRequest) : null;
return (
<Dialog
open={currentRequest !== null}
onOpenChange={(open) => {
if (!open) {
cancelPrompt();
}
}}
>
<DialogPopup className="max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>SSH Password Required</DialogTitle>
<DialogDescription>
T3 needs your SSH password to connect to{" "}
{target ? <code>{target}</code> : "the remote host"}. The password is passed to the
local SSH process for this connection attempt and is not saved by T3 Code.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-3" scrollFade={false}>
<form
className="space-y-3"
id={formId}
onSubmit={(event) => {
event.preventDefault();
void respond(password);
}}
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>
{remainingLabel ? (
<span
className={
isExpired
? "shrink-0 text-xs font-medium text-destructive"
: "shrink-0 text-xs text-muted-foreground"
}
>
{isExpired ? "Expired" : remainingLabel}
</span>
) : null}
</div>
<Input
ref={inputRef}
autoComplete="current-password"
disabled={isResponding || isExpired}
name="ssh-password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</div>
{responseError ? (
<p className="text-sm text-destructive">{responseError}</p>
) : (
<p className="text-sm text-muted-foreground">
Use SSH keys to avoid repeated password prompts on new SSH sessions.
</p>
)}
</form>
</DialogPanel>
<DialogFooter>
<Button disabled={isResponding} type="button" variant="outline" onClick={cancelPrompt}>
{isExpired ? "Dismiss" : "Cancel"}
</Button>
<Button disabled={isResponding || isExpired} form={formId} type="submit">
Continue
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
File diff suppressed because it is too large. Load diff
@@ -20,6 +20,7 @@ import { render } from "vitest-browser-react";
import { __resetLocalApiForTests } from "../../localApi";
import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
import { useUiStateStore } from "../../uiStateStore";
import { ConnectionsSettings } from "./ConnectionsSettings";
import { GeneralSettingsPanel } from "./SettingsPanels";
@@ -113,6 +114,8 @@ const authAccessHarness = vi.hoisted(() => {
};
});
const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn());
vi.mock("../../environments/runtime", () => {
const primaryConnection = {
kind: "primary" as const,
@@ -150,6 +153,7 @@ vi.mock("../../environments/runtime", () => {
new URL(path, "http://localhost:3000").toString(),
waitForSavedEnvironmentRegistryHydration: async () => undefined,
addSavedEnvironment: vi.fn(),
connectDesktopSshEnvironment: mockConnectDesktopSshEnvironment,
disconnectSavedEnvironment: vi.fn(),
ensureEnvironmentConnectionBootstrapped: async () => undefined,
getPrimaryEnvironmentConnection: () => primaryConnection,
@@ -257,7 +261,9 @@ function makeClientSession(input: {
}
const createDesktopBridgeStub = (overrides?: {
readonly discoverSshHosts?: DesktopBridge["discoverSshHosts"];
readonly serverExposureState?: Awaited<ReturnType<DesktopBridge["getServerExposureState"]>>;
readonly advertisedEndpoints?: Awaited<ReturnType<DesktopBridge["getAdvertisedEndpoints"]>>;
readonly setServerExposureMode?: DesktopBridge["setServerExposureMode"];
readonly setUpdateChannel?: DesktopBridge["setUpdateChannel"];
}): DesktopBridge => {
@@ -293,11 +299,58 @@ const createDesktopBridgeStub = (overrides?: {
getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
discoverSshHosts: overrides?.discoverSshHosts ?? vi.fn().mockResolvedValue([]),
ensureSshEnvironment: vi.fn().mockImplementation(async (target) => ({
target,
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
pairingToken: "ssh-pairing-token",
})),
disconnectSshEnvironment: vi.fn().mockResolvedValue(undefined),
fetchSshEnvironmentDescriptor: vi.fn().mockResolvedValue({
environmentId: "environment-ssh",
label: "SSH environment",
platform: {
os: "linux",
arch: "x64",
},
serverVersion: "0.0.0-test",
capabilities: {
repositoryIdentity: true,
},
}),
bootstrapSshBearerSession: vi.fn().mockResolvedValue({
authenticated: true,
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
sessionToken: "ssh-bearer-token",
}),
fetchSshSessionState: vi.fn().mockResolvedValue({
authenticated: true,
auth: {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: "t3_session",
},
role: "owner",
sessionMethod: "bearer-session-token",
expiresAt: "2026-05-01T12:00:00.000Z",
}),
issueSshWebSocketToken: vi.fn().mockResolvedValue({
token: "ssh-ws-token",
expiresAt: "2026-05-01T12:05:00.000Z",
}),
onSshPasswordPrompt: vi.fn(() => () => {}),
resolveSshPasswordPrompt: vi.fn().mockResolvedValue(undefined),
getServerExposureState: vi.fn().mockResolvedValue(
overrides?.serverExposureState ?? {
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
),
setServerExposureMode:
@@ -306,7 +359,17 @@ const createDesktopBridgeStub = (overrides?: {
mode,
endpointUrl: mode === "network-accessible" ? "http://192.168.1.44:3773" : null,
advertisedHost: mode === "network-accessible" ? "192.168.1.44" : null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
})),
setTailscaleServeEnabled: vi.fn().mockImplementation(async (input) => ({
mode: overrides?.serverExposureState?.mode ?? "network-accessible",
endpointUrl: overrides?.serverExposureState?.endpointUrl ?? "http://192.168.1.44:3773",
advertisedHost: overrides?.serverExposureState?.advertisedHost ?? "192.168.1.44",
tailscaleServeEnabled: input.enabled,
tailscaleServePort: input.port ?? 443,
})),
getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []),
pickFolder: vi.fn().mockResolvedValue(null),
confirm: vi.fn().mockResolvedValue(false),
setTheme: vi.fn().mockResolvedValue(undefined),
@@ -343,7 +406,9 @@ describe("GeneralSettingsPanel observability", () => {
resetServerStateForTests();
await __resetLocalApiForTests();
localStorage.clear();
useUiStateStore.setState({ defaultAdvertisedEndpointKey: null });
authAccessHarness.reset();
mockConnectDesktopSshEnvironment.mockReset();
});
afterEach(async () => {
@@ -429,6 +494,176 @@ describe("GeneralSettingsPanel observability", () => {
.toBeInTheDocument();
});
it("hides advertised endpoint rows when desktop network access is disabled", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
advertisedEndpoints: [
{
id: "loopback",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
},
{
id: "tailscale-ip",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.105.39.17:3773/",
wsBaseUrl: "ws://100.105.39.17:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
},
],
});
authAccessHarness.setSnapshot({
pairingLinks: [],
clientSessions: [],
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("Limited to this machine.")).toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "This machine", exact: true }))
.not.toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "Tailscale IP", exact: true }))
.not.toBeInTheDocument();
});
it("collapses advertised endpoints behind the network access summary", async () => {
window.desktopBridge = createDesktopBridgeStub({
serverExposureState: {
mode: "network-accessible",
endpointUrl: "http://192.168.86.39:3773",
advertisedHost: "192.168.86.39",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
advertisedEndpoints: [
{
id: "desktop-loopback:3773",
label: "This machine",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://127.0.0.1:3773/",
wsBaseUrl: "ws://127.0.0.1:3773/",
reachability: "loopback",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
},
{
id: "desktop-lan:http://192.168.86.39:3773",
label: "Local network",
provider: {
id: "desktop-core",
label: "Desktop",
kind: "manual",
isAddon: false,
},
httpBaseUrl: "http://192.168.86.39:3773/",
wsBaseUrl: "ws://192.168.86.39:3773/",
reachability: "lan",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-core",
status: "available",
isDefault: true,
},
{
id: "tailscale-ip:http://100.105.39.17:3773",
label: "Tailscale IP",
provider: {
id: "tailscale",
label: "Tailscale",
kind: "private-network",
isAddon: true,
},
httpBaseUrl: "http://100.105.39.17:3773/",
wsBaseUrl: "ws://100.105.39.17:3773/",
reachability: "private-network",
compatibility: {
hostedHttpsApp: "mixed-content-blocked",
desktopApp: "compatible",
},
source: "desktop-addon",
status: "available",
},
],
});
authAccessHarness.setSnapshot({
pairingLinks: [],
clientSessions: [],
});
setServerConfigSnapshot(createBaseServerConfig());
mounted = await render(
<AppAtomRegistryProvider>
<ConnectionsSettings />
</AppAtomRegistryProvider>,
);
await expect.element(page.getByText("http://192.168.86.39:3773/")).toBeInTheDocument();
await expect.element(page.getByRole("button", { name: "+2" })).toBeInTheDocument();
await expect
.element(page.getByRole("heading", { name: "Local network", exact: true }))
.not.toBeInTheDocument();
await page.getByRole("button", { name: "+2" }).click();
await expect
.element(page.getByRole("heading", { name: "Local network", exact: true }))
.toBeInTheDocument();
await expect.element(page.getByText("Default", { exact: true })).toBeInTheDocument();
await page.getByRole("button", { name: "Set as default" }).first().click();
await expect.element(page.getByText("http://127.0.0.1:3773/").first()).toBeInTheDocument();
});
it("shows diagnostics inside About with a single logs-folder action", async () => {
setServerConfigSnapshot(createBaseServerConfig());
@@ -459,6 +694,8 @@ describe("GeneralSettingsPanel observability", () => {
mode: "network-accessible",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
});
let pairingLinks: Array<AuthAccessSnapshot["pairingLinks"][number]> = [];
@@ -564,7 +801,7 @@ describe("GeneralSettingsPanel observability", () => {
.element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))
.toBeInTheDocument();
await expect
.element(page.getByRole("button", { name: /^(Copy|Show link)$/ }))
.element(page.getByRole("button", { name: /^(Copy code|Show link)$/ }))
.toBeInTheDocument();
await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
});
@@ -575,6 +812,8 @@ describe("GeneralSettingsPanel observability", () => {
mode: "network-accessible",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
});
let clientSessions: Array<AuthAccessSnapshot["clientSessions"][number]> = [
@@ -675,9 +914,75 @@ 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();
await expect
.element(page.getByText("Reachable at http://192.168.1.44:3773"))
.element(page.getByRole("heading", { name: "Add Environment", exact: true }))
.toBeInTheDocument();
await page.getByRole("button", { name: "SSH", exact: true }).click();
await vi.waitFor(() => {
expect(discoverSshHosts).toHaveBeenCalledTimes(1);
});
await expect
.element(page.getByRole("heading", { name: "devbox", exact: true }))
.toBeInTheDocument();
await page.getByText("Enter a host manually").click();
await page.getByLabelText("Label").fill("Build box");
await page.getByLabelText("SSH host or alias").fill("devbox.example.com");
await page.getByLabelText("Username").fill("julius");
await page.getByLabelText("Port").fill("2222");
await page.getByRole("button", { name: "Connect SSH host", exact: true }).click();
await vi.waitFor(() => {
expect(mockConnectDesktopSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox.example.com",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ label: "Build box" },
);
});
});
it("opens the logs folder in the preferred editor", async () => {
@@ -0,0 +1,24 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
describe("settings pairing URL helpers", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("uses direct backend pairing URLs for HTTP endpoints", () => {
expect(resolveHostedPairingUrl("http://192.168.1.44:3773", "PAIRCODE")).toBeNull();
expect(resolveDesktopPairingUrl("http://192.168.1.44:3773", "PAIRCODE")).toBe(
"http://192.168.1.44:3773/pair#token=PAIRCODE",
);
});
it("uses hosted pairing URLs for HTTPS endpoints", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes");
expect(resolveHostedPairingUrl("https://host.tailnet.example.ts.net:3773", "PAIRCODE")).toBe(
"https://preview.t3.codes/pair?host=https%3A%2F%2Fhost.tailnet.example.ts.net%3A3773#token=PAIRCODE",
);
});
});
@@ -0,0 +1,20 @@
import { buildHostedPairingUrl } from "../../hostedPairing";
import { setPairingTokenOnUrl } from "../../pairingUrl";
export function resolveDesktopPairingUrl(endpointUrl: string, credential: string): string {
const url = new URL(endpointUrl);
url.pathname = "/pair";
return setPairingTokenOnUrl(url, credential).toString();
}
export function resolveHostedPairingUrl(endpointUrl: string, credential: string): string | null {
const url = new URL(endpointUrl);
if (url.protocol !== "https:") {
return null;
}
return buildHostedPairingUrl({
host: endpointUrl,
token: credential,
});
}
@@ -52,7 +52,7 @@ export function SettingsRow({
children,
}: {
title: ReactNode;
description: string;
description: ReactNode;
status?: ReactNode;
resetAction?: ReactNode;
control?: ReactNode;
+2 -2
View File
@@ -18,7 +18,7 @@ function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backd
return (
<AlertDialogPrimitive.Backdrop
className={cn(
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 ease-out data-ending-style:opacity-0 data-starting-style:opacity-0",
"fixed inset-0 z-50 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
className,
)}
data-slot="alert-dialog-backdrop"
@@ -31,7 +31,7 @@ function AlertDialogViewport({ className, ...props }: AlertDialogPrimitive.Viewp
return (
<AlertDialogPrimitive.Viewport
className={cn(
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center bg-white/48 p-4 backdrop-blur-[2px] dark:bg-black/28",
className,
)}
data-slot="alert-dialog-viewport"
+2 -2
View File
@@ -24,7 +24,7 @@ function DialogBackdrop({ className, ...props }: DialogPrimitive.Backdrop.Props)
return (
<DialogPrimitive.Backdrop
className={cn(
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
"fixed inset-0 z-50 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
className,
)}
data-slot="dialog-backdrop"
@@ -37,7 +37,7 @@ function DialogViewport({ className, ...props }: DialogPrimitive.Viewport.Props)
return (
<DialogPrimitive.Viewport
className={cn(
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center bg-white/48 p-4 backdrop-blur-[2px] dark:bg-black/28",
className,
)}
data-slot="dialog-viewport"
+1 -1
View File
@@ -23,7 +23,7 @@ function ScrollArea({
>
<ScrollAreaPrimitive.Viewport
className={cn(
"h-full overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
"h-full max-h-[inherit] overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
scrollFade &&
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
scrollbarGutter && "[scrollbar-gutter:stable]",
@@ -48,6 +48,19 @@ describe("remote environment api", () => {
});
});
it("derives backend urls and token from a hosted app pairing link", () => {
expect(
resolveRemotePairingTarget({
pairingUrl:
"https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.tailnet.ts.net%3A44342%2F#token=pairing-token",
}),
).toEqual({
credential: "pairing-token",
httpBaseUrl: "https://desktop.tailnet.ts.net:44342/",
wsBaseUrl: "wss://desktop.tailnet.ts.net:44342/",
});
});
it("derives backend urls from a host and pairing code", () => {
expect(
resolveRemotePairingTarget({
+6
View File
@@ -15,6 +15,12 @@ class RemoteEnvironmentAuthHttpError extends Error {
}
}
export function isRemoteEnvironmentAuthHttpError(
error: unknown,
): error is RemoteEnvironmentAuthHttpError {
return error instanceof RemoteEnvironmentAuthHttpError;
}
function remoteEndpointUrl(httpBaseUrl: string, pathname: string): string {
const url = new URL(httpBaseUrl);
url.pathname = pathname;
@@ -1,4 +1,5 @@
import { getPairingTokenFromUrl } from "../../pairingUrl";
import { readHostedPairingRequest } from "../../hostedPairing";
export interface ResolvedRemotePairingTarget {
readonly credential: string;
@@ -57,6 +58,16 @@ export function resolveRemotePairingTarget(input: {
const pairingUrl = input.pairingUrl?.trim() ?? "";
if (pairingUrl.length > 0) {
const url = new URL(pairingUrl, window.location.origin);
const hostedPairingRequest = readHostedPairingRequest(url);
if (hostedPairingRequest) {
const hostedBackendUrl = normalizeRemoteBaseUrl(hostedPairingRequest.host);
return {
credential: hostedPairingRequest.token,
httpBaseUrl: toHttpBaseUrl(hostedBackendUrl),
wsBaseUrl: toWsBaseUrl(hostedBackendUrl),
};
}
const credential = getPairingTokenFromUrl(url) ?? "";
if (!credential) {
throw new Error("Pairing URL is missing its token.");
+21 -1
View File
@@ -18,6 +18,7 @@ export interface SavedEnvironmentRecord {
readonly httpBaseUrl: string;
readonly createdAt: string;
readonly lastConnectedAt: string | null;
readonly desktopSsh?: PersistedSavedEnvironmentRecord["desktopSsh"];
}
interface SavedEnvironmentRegistryState {
@@ -28,13 +29,14 @@ interface SavedEnvironmentRegistryStore extends SavedEnvironmentRegistryState {
readonly upsert: (record: SavedEnvironmentRecord) => void;
readonly remove: (environmentId: EnvironmentId) => void;
readonly markConnected: (environmentId: EnvironmentId, connectedAt: string) => void;
readonly rename: (environmentId: EnvironmentId, label: string) => void;
readonly reset: () => void;
}
let savedEnvironmentRegistryHydrated = false;
let savedEnvironmentRegistryHydrationPromise: Promise<void> | null = null;
function toPersistedSavedEnvironmentRecord(
export function toPersistedSavedEnvironmentRecord(
record: SavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
@@ -44,6 +46,7 @@ function toPersistedSavedEnvironmentRecord(
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
};
}
@@ -148,6 +151,23 @@ export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryS
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
rename: (environmentId, label) =>
set((state) => {
const existing = state.byId[environmentId];
const nextLabel = label.trim();
if (!existing || nextLabel.length === 0 || existing.label === nextLabel) {
return state;
}
const byId = {
...state.byId,
[environmentId]: {
...existing,
label: nextLabel,
},
};
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
reset: () => {
persistSavedEnvironmentRegistryState({});
set({
@@ -16,6 +16,7 @@ export {
export {
addSavedEnvironment,
connectDesktopSshEnvironment,
disconnectSavedEnvironment,
ensureEnvironmentConnectionBootstrapped,
getPrimaryEnvironmentConnection,
@@ -1,14 +1,60 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
let mockSavedRecords: Array<Record<string, unknown>> = [];
const mockResolveRemotePairingTarget = vi.fn();
const mockFetchRemoteEnvironmentDescriptor = vi.fn();
const mockBootstrapRemoteBearerSession = vi.fn();
const mockFetchRemoteSessionState = vi.fn();
const mockIsRemoteEnvironmentAuthHttpError = vi.fn((_: unknown) => false);
const mockResolveRemoteWebSocketConnectionUrl = vi.fn();
const mockBootstrapSshBearerSession = vi.fn();
const mockFetchSshSessionState = vi.fn();
const mockPersistSavedEnvironmentRecord = vi.fn();
const mockWriteSavedEnvironmentBearerToken = vi.fn();
const mockSetSavedEnvironmentRegistry = vi.fn();
const mockUpsert = vi.fn();
const mockListSavedEnvironmentRecords = vi.fn();
const mockGetSavedEnvironmentRecord = vi.fn((environmentId: EnvironmentId) => {
return mockSavedRecords.find((record) => record.environmentId === environmentId) ?? null;
});
const mockReadSavedEnvironmentBearerToken = vi.fn();
const mockRemoveSavedEnvironmentBearerToken = vi.fn();
const mockPatchRuntime = vi.fn();
const mockClearRuntime = vi.fn();
const mockRegistrySetState = vi.fn((next: { byId: Record<string, Record<string, unknown>> }) => {
mockSavedRecords = Object.values(next.byId);
});
const mockRemove = vi.fn((environmentId: EnvironmentId) => {
mockSavedRecords = mockSavedRecords.filter((record) => record.environmentId !== environmentId);
});
const mockMarkConnected = vi.fn((environmentId: EnvironmentId, connectedAt: string) => {
mockSavedRecords = mockSavedRecords.map((record) =>
record.environmentId === environmentId ? { ...record, lastConnectedAt: connectedAt } : record,
);
});
const mockRename = vi.fn((environmentId: EnvironmentId, label: string) => {
mockSavedRecords = mockSavedRecords.map((record) =>
record.environmentId === environmentId ? { ...record, label } : record,
);
});
const mockUpsert = vi.fn((record: Record<string, unknown>) => {
mockSavedRecords = [
...mockSavedRecords.filter((entry) => entry.environmentId !== record.environmentId),
record,
];
});
const mockListSavedEnvironmentRecords = vi.fn(() => mockSavedRecords);
const mockEnsureSshEnvironment = vi.fn();
const mockDisconnectSshEnvironment = vi.fn();
const mockFetchSshEnvironmentDescriptor = vi.fn();
const mockToPersistedSavedEnvironmentRecord = vi.fn((record) => record);
const mockCreateEnvironmentConnection = vi.fn();
const mockClientGetConfig = vi.fn(async () => ({
environment: {
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
},
}));
vi.mock("../remote/target", () => ({
resolveRemotePairingTarget: mockResolveRemotePairingTarget,
@@ -17,8 +63,9 @@ vi.mock("../remote/target", () => ({
vi.mock("../remote/api", () => ({
bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState: vi.fn(),
resolveRemoteWebSocketConnectionUrl: vi.fn(),
fetchRemoteSessionState: mockFetchRemoteSessionState,
isRemoteEnvironmentAuthHttpError: mockIsRemoteEnvironmentAuthHttpError,
resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl,
}));
vi.mock("~/localApi", () => ({
@@ -30,24 +77,28 @@ vi.mock("~/localApi", () => ({
}));
vi.mock("./catalog", () => ({
getSavedEnvironmentRecord: vi.fn(),
getSavedEnvironmentRecord: mockGetSavedEnvironmentRecord,
hasSavedEnvironmentRegistryHydrated: vi.fn(),
listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord,
readSavedEnvironmentBearerToken: vi.fn(),
removeSavedEnvironmentBearerToken: vi.fn(),
readSavedEnvironmentBearerToken: mockReadSavedEnvironmentBearerToken,
removeSavedEnvironmentBearerToken: mockRemoveSavedEnvironmentBearerToken,
toPersistedSavedEnvironmentRecord: mockToPersistedSavedEnvironmentRecord,
useSavedEnvironmentRegistryStore: {
getState: () => ({
upsert: mockUpsert,
remove: vi.fn(),
markConnected: vi.fn(),
remove: mockRemove,
markConnected: mockMarkConnected,
rename: mockRename,
}),
setState: mockRegistrySetState,
subscribe: vi.fn(() => () => {}),
},
useSavedEnvironmentRuntimeStore: {
getState: () => ({
ensure: vi.fn(),
patch: vi.fn(),
clear: vi.fn(),
patch: mockPatchRuntime,
clear: mockClearRuntime,
}),
},
waitForSavedEnvironmentRegistryHydration: vi.fn(),
@@ -55,18 +106,58 @@ vi.mock("./catalog", () => ({
}));
vi.mock("./connection", () => ({
createEnvironmentConnection: vi.fn(),
createEnvironmentConnection: mockCreateEnvironmentConnection,
}));
vi.mock("../../rpc/wsRpcClient", () => ({
createWsRpcClient: vi.fn(() => ({
server: {
getConfig: mockClientGetConfig,
},
orchestration: {
subscribeThread: vi.fn(() => () => {}),
},
})),
}));
vi.mock("../../rpc/wsTransport", () => ({
WsTransport: vi.fn(),
}));
describe("addSavedEnvironment", () => {
afterEach(() => {
vi.useRealTimers();
});
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
mockResolveRemotePairingTarget.mockReturnValue({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
credential: "pairing-code",
mockSavedRecords = [];
vi.stubGlobal("window", {
desktopBridge: {
ensureSshEnvironment: mockEnsureSshEnvironment,
disconnectSshEnvironment: mockDisconnectSshEnvironment,
fetchSshEnvironmentDescriptor: mockFetchSshEnvironmentDescriptor,
bootstrapSshBearerSession: mockBootstrapSshBearerSession,
fetchSshSessionState: mockFetchSshSessionState,
issueSshWebSocketToken: vi.fn(),
},
});
mockResolveRemotePairingTarget.mockImplementation(
(input: { host?: string; pairingCode?: string }) => ({
httpBaseUrl: input.host
? input.host.endsWith("/")
? input.host
: `${input.host}/`
: "https://remote.example.com/",
wsBaseUrl: input.host
? input.host.replace(/^http/u, "ws").endsWith("/")
? input.host.replace(/^http/u, "ws")
: `${input.host.replace(/^http/u, "ws")}/`
: "wss://remote.example.com/",
credential: input.pairingCode ?? "pairing-code",
}),
);
mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
@@ -75,10 +166,60 @@ describe("addSavedEnvironment", () => {
sessionToken: "bearer-token",
role: "owner",
});
mockFetchRemoteSessionState.mockResolvedValue({
authenticated: true,
role: "owner",
});
mockIsRemoteEnvironmentAuthHttpError.mockReturnValue(false);
mockResolveRemoteWebSocketConnectionUrl.mockResolvedValue(
"wss://remote.example.com/?wsToken=remote-token",
);
mockFetchSshEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
});
mockBootstrapSshBearerSession.mockResolvedValue({
sessionToken: "ssh-bearer-token",
role: "owner",
});
mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
mockListSavedEnvironmentRecords.mockReturnValue([]);
mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
mockRemoveSavedEnvironmentBearerToken.mockResolvedValue(undefined);
mockFetchSshSessionState.mockResolvedValue({
authenticated: true,
role: "owner",
});
mockCreateEnvironmentConnection.mockImplementation(
(input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => ({
kind: "saved",
environmentId: input.knownEnvironment.environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
ensureBootstrapped: async () => undefined,
reconnect: async () => undefined,
dispose: async () => undefined,
}),
);
mockClientGetConfig.mockResolvedValue({
environment: {
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
},
});
mockEnsureSshEnvironment.mockResolvedValue({
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
pairingToken: "ssh-pairing-code",
});
mockDisconnectSshEnvironment.mockResolvedValue(undefined);
});
it("rolls back persisted metadata when bearer token persistence fails", async () => {
@@ -102,4 +243,551 @@ describe("addSavedEnvironment", () => {
await resetEnvironmentServiceForTests();
});
it("restores unrelated saved environments when credential persistence rollback runs", async () => {
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-existing"),
label: "Existing environment",
httpBaseUrl: "https://existing.example.com/",
wsBaseUrl: "wss://existing.example.com/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
},
];
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await expect(
addSavedEnvironment({
label: "Remote environment",
host: "remote.example.com",
pairingCode: "123456",
}),
).rejects.toThrow("Unable to persist saved environment credentials.");
expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([
expect.objectContaining({
environmentId: EnvironmentId.make("environment-existing"),
}),
]);
await resetEnvironmentServiceForTests();
});
it("persists the server label after saved environment metadata refresh", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
mockClientGetConfig.mockResolvedValue({
environment: {
environmentId: EnvironmentId.make("environment-1"),
label: "Julius's Mac mini",
},
});
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await expect(
addSavedEnvironment({
label: "100.65.180.100",
host: "remote.example.com",
pairingCode: "123456",
}),
).resolves.toMatchObject({
environmentId: EnvironmentId.make("environment-1"),
});
expect(mockRename).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
"Julius's Mac mini",
);
expect(mockSavedRecords).toEqual([
expect.objectContaining({
environmentId: EnvironmentId.make("environment-1"),
label: "Julius's Mac mini",
}),
]);
await resetEnvironmentServiceForTests();
});
it("removes an older ssh record when the same target returns a new environment id", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
mockFetchSshEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.make("environment-2"),
label: "Remote environment",
});
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Old ssh environment",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
];
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await expect(
addSavedEnvironment({
label: "Remote environment",
host: "http://127.0.0.1:3774/",
pairingCode: "ssh-pairing-code",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
}),
).resolves.toMatchObject({
environmentId: EnvironmentId.make("environment-2"),
});
expect(mockUpsert).toHaveBeenCalledWith(
expect.objectContaining({
environmentId: EnvironmentId.make("environment-2"),
}),
);
expect(mockRemove).toHaveBeenCalledWith(EnvironmentId.make("environment-1"));
expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
);
await resetEnvironmentServiceForTests();
});
it("retries desktop ssh session refresh when the forwarded endpoint returns ssh_http 401", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
mockBootstrapSshBearerSession
.mockResolvedValueOnce({
sessionToken: "ssh-bearer-token",
role: "owner",
})
.mockResolvedValueOnce({
sessionToken: "ssh-bearer-token-2",
role: "owner",
});
mockFetchSshSessionState
.mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized"))
.mockResolvedValueOnce({
authenticated: true,
role: "owner",
});
const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await expect(
connectDesktopSshEnvironment({
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
}),
).resolves.toMatchObject({
environmentId: EnvironmentId.make("environment-1"),
});
expect(mockEnsureSshEnvironment).toHaveBeenCalled();
expect(mockBootstrapSshBearerSession).toHaveBeenCalledTimes(2);
expect(mockFetchSshSessionState).toHaveBeenCalledTimes(2);
await resetEnvironmentServiceForTests();
});
it("does not attempt desktop ssh bearer recovery for non-ssh saved environments", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
const authError = {
status: 401,
message: "Unauthorized",
};
mockFetchRemoteSessionState.mockRejectedValueOnce(authError);
mockIsRemoteEnvironmentAuthHttpError.mockImplementation(
(error: unknown) => error === authError,
);
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await expect(
addSavedEnvironment({
label: "Remote environment",
host: "remote.example.com",
pairingCode: "123456",
}),
).rejects.toThrow("Saved environment credential expired. Pair it again.");
expect(mockEnsureSshEnvironment).not.toHaveBeenCalled();
expect(mockBootstrapSshBearerSession).not.toHaveBeenCalled();
expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
);
await resetEnvironmentServiceForTests();
});
it("only registers the retried ssh connection after bearer re-issuance succeeds", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
mockBootstrapSshBearerSession
.mockResolvedValueOnce({
sessionToken: "ssh-bearer-token",
role: "owner",
})
.mockResolvedValueOnce({
sessionToken: "ssh-bearer-token-2",
role: "owner",
});
mockFetchSshSessionState
.mockRejectedValueOnce(new Error("[ssh_http:401] Unauthorized"))
.mockResolvedValueOnce({
authenticated: true,
role: "owner",
});
const createdConnections: Array<{
readonly environmentId: EnvironmentId;
readonly dispose: ReturnType<typeof vi.fn>;
}> = [];
mockCreateEnvironmentConnection.mockImplementation(
(input: { knownEnvironment: { environmentId: EnvironmentId }; client: unknown }) => {
const connection = {
kind: "saved" as const,
environmentId: input.knownEnvironment.environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
ensureBootstrapped: async () => undefined,
reconnect: async () => undefined,
dispose: vi.fn(async () => undefined),
};
createdConnections.push(connection);
return connection;
},
);
const {
connectDesktopSshEnvironment,
listEnvironmentConnections,
resetEnvironmentServiceForTests,
} = await import("./service");
await connectDesktopSshEnvironment({
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
});
expect(createdConnections).toHaveLength(2);
expect(createdConnections[0]?.dispose).toHaveBeenCalledTimes(1);
expect(listEnvironmentConnections()).toHaveLength(1);
expect(listEnvironmentConnections()[0]).toBe(createdConnections[1]);
await resetEnvironmentServiceForTests();
});
it("marks desktop ssh reconnect failures as runtime errors when bearer recovery fails", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
const connection = {
kind: "saved" as const,
environmentId: EnvironmentId.make("environment-1"),
knownEnvironment: {
environmentId: EnvironmentId.make("environment-1"),
},
client: {},
ensureBootstrapped: async () => undefined,
reconnect: vi.fn(async () => {
throw new Error("socket closed");
}),
dispose: async () => undefined,
};
mockCreateEnvironmentConnection.mockReturnValue(connection);
const { addSavedEnvironment, reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await addSavedEnvironment({
label: "Remote environment",
host: "http://127.0.0.1:3774/",
pairingCode: "ssh-pairing-code",
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
});
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
];
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
await expect(reconnectSavedEnvironment(EnvironmentId.make("environment-1"))).rejects.toThrow(
"Unable to persist saved environment credentials.",
);
expect(mockPatchRuntime).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
expect.objectContaining({
connectionState: "error",
lastError: "Unable to persist saved environment credentials.",
}),
);
await resetEnvironmentServiceForTests();
});
it("bootstraps a desktop ssh environment through the desktop bridge", async () => {
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
const { connectDesktopSshEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await expect(
connectDesktopSshEnvironment({
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
}),
).resolves.toMatchObject({
environmentId: EnvironmentId.make("environment-1"),
});
expect(mockEnsureSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox",
hostname: "devbox",
username: null,
port: null,
},
{ issuePairingToken: true },
);
expect(mockResolveRemotePairingTarget).toHaveBeenCalledWith({
host: "http://127.0.0.1:3774/",
pairingCode: "ssh-pairing-code",
});
expect(mockFetchSshEnvironmentDescriptor).toHaveBeenCalledWith("http://127.0.0.1:3774/");
expect(mockBootstrapSshBearerSession).toHaveBeenCalledWith(
"http://127.0.0.1:3774/",
"ssh-pairing-code",
);
expect(mockFetchRemoteEnvironmentDescriptor).not.toHaveBeenCalled();
expect(mockBootstrapRemoteBearerSession).not.toHaveBeenCalled();
expect(mockUpsert.mock.invocationCallOrder[0]).toBeLessThan(
mockCreateEnvironmentConnection.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
);
await resetEnvironmentServiceForTests();
});
it("disconnects the desktop ssh process before removing a saved ssh environment", async () => {
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
];
const { removeSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await removeSavedEnvironment(EnvironmentId.make("environment-1"));
expect(mockDisconnectSshEnvironment).toHaveBeenCalledWith({
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
});
expect(mockRemove).toHaveBeenCalledWith(EnvironmentId.make("environment-1"));
expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
);
expect(mockDisconnectSshEnvironment.mock.invocationCallOrder[0]).toBeLessThan(
mockRemove.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
);
await resetEnvironmentServiceForTests();
});
it("disconnects a saved ssh environment without removing its saved record", async () => {
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
];
const { disconnectSavedEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await disconnectSavedEnvironment(EnvironmentId.make("environment-1"));
expect(mockDisconnectSshEnvironment).toHaveBeenCalledWith({
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
});
expect(mockRemove).not.toHaveBeenCalled();
expect(mockRemoveSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
);
await resetEnvironmentServiceForTests();
});
it("keeps remote environment credentials when disconnecting a non-ssh saved environment", async () => {
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
},
];
const { disconnectSavedEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await disconnectSavedEnvironment(EnvironmentId.make("environment-1"));
expect(mockDisconnectSshEnvironment).not.toHaveBeenCalled();
expect(mockRemove).not.toHaveBeenCalled();
expect(mockRemoveSavedEnvironmentBearerToken).not.toHaveBeenCalled();
await resetEnvironmentServiceForTests();
});
it("reissues ssh pairing credentials when connecting after a manual ssh disconnect", async () => {
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
];
mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(true);
const { reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await reconnectSavedEnvironment(EnvironmentId.make("environment-1"));
expect(mockEnsureSshEnvironment).toHaveBeenCalledWith(
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
{ issuePairingToken: true },
);
expect(mockBootstrapSshBearerSession).toHaveBeenCalledWith(
"http://127.0.0.1:3774/",
"ssh-pairing-code",
);
expect(mockWriteSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
"ssh-bearer-token",
);
await resetEnvironmentServiceForTests();
});
it("surfaces desktop ssh bootstrap failures during saved ssh reconnect", async () => {
mockSavedRecords = [
{
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
createdAt: "2026-04-14T00:00:00.000Z",
lastConnectedAt: null,
desktopSsh: {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 22,
},
},
];
mockReadSavedEnvironmentBearerToken.mockResolvedValue(null);
mockEnsureSshEnvironment.mockRejectedValue(new Error("SSH command timed out after 60000ms."));
const { reconnectSavedEnvironment, resetEnvironmentServiceForTests } =
await import("./service");
await expect(reconnectSavedEnvironment(EnvironmentId.make("environment-1"))).rejects.toThrow(
"SSH command timed out after 60000ms.",
);
expect(mockPatchRuntime).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
expect.objectContaining({
connectionState: "connecting",
}),
);
expect(mockPatchRuntime).toHaveBeenCalledWith(
EnvironmentId.make("environment-1"),
expect.objectContaining({
connectionState: "error",
lastError: "SSH command timed out after 60000ms.",
}),
);
await resetEnvironmentServiceForTests();
});
});
@@ -15,22 +15,14 @@ const mockCreateWsRpcClient = vi.fn();
const mockWaitForSavedEnvironmentRegistryHydration = vi.fn();
const mockListSavedEnvironmentRecords = vi.fn();
const mockSavedEnvironmentRegistrySubscribe = vi.fn();
const mockGetPrimaryKnownEnvironment = vi.hoisted(() => vi.fn());
function MockWsTransport() {
return undefined;
}
vi.mock("../primary", () => ({
getPrimaryKnownEnvironment: vi.fn(() => ({
id: "env-1",
label: "Primary environment",
source: "window-origin",
target: {
httpBaseUrl: "http://127.0.0.1:3000/",
wsBaseUrl: "ws://127.0.0.1:3000/",
},
environmentId: EnvironmentId.make("env-1"),
})),
getPrimaryKnownEnvironment: mockGetPrimaryKnownEnvironment,
}));
vi.mock("./catalog", () => ({
@@ -46,6 +38,7 @@ vi.mock("./catalog", () => ({
upsert: vi.fn(),
remove: vi.fn(),
markConnected: vi.fn(),
rename: vi.fn(),
}),
},
useSavedEnvironmentRuntimeStore: {
@@ -144,6 +137,16 @@ describe("retainThreadDetailSubscription", () => {
vi.useFakeTimers();
vi.resetModules();
vi.clearAllMocks();
mockGetPrimaryKnownEnvironment.mockReturnValue({
id: "env-1",
label: "Primary environment",
source: "window-origin",
target: {
httpBaseUrl: "http://127.0.0.1:3000/",
wsBaseUrl: "ws://127.0.0.1:3000/",
},
environmentId: EnvironmentId.make("env-1"),
});
mockThreadUnsubscribe.mockImplementation(() => undefined);
mockSubscribeThread.mockImplementation(() => mockThreadUnsubscribe);
@@ -203,6 +206,31 @@ describe("retainThreadDetailSubscription", () => {
await resetEnvironmentServiceForTests();
});
it("does not start the primary connection until the known environment has an id", async () => {
mockGetPrimaryKnownEnvironment.mockReturnValue({
id: "env-1",
label: "Primary environment",
source: "window-origin",
target: {
httpBaseUrl: "http://127.0.0.1:3000/",
wsBaseUrl: "ws://127.0.0.1:3000/",
},
});
const {
listEnvironmentConnections,
resetEnvironmentServiceForTests,
startEnvironmentConnectionService,
} = await import("./service");
const stop = startEnvironmentConnectionService(new QueryClient());
expect(mockCreateEnvironmentConnection).not.toHaveBeenCalled();
expect(listEnvironmentConnections()).toEqual([]);
stop();
await resetEnvironmentServiceForTests();
});
it("keeps non-idle thread detail subscriptions attached until the thread becomes idle", async () => {
const {
retainThreadDetailSubscription,
+468 -113
View File
@@ -1,5 +1,7 @@
import {
type AuthSessionRole,
type DesktopSshEnvironmentBootstrap,
type DesktopSshEnvironmentTarget,
type EnvironmentId,
type OrchestrationEvent,
type OrchestrationShellSnapshot,
@@ -33,6 +35,7 @@ import {
bootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
isRemoteEnvironmentAuthHttpError,
resolveRemoteWebSocketConnectionUrl,
} from "../remote/api";
import { resolveRemotePairingTarget } from "../remote/target";
@@ -44,6 +47,7 @@ import {
readSavedEnvironmentBearerToken,
removeSavedEnvironmentBearerToken,
type SavedEnvironmentRecord,
toPersistedSavedEnvironmentRecord,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
@@ -85,6 +89,7 @@ type ThreadDetailSubscriptionEntry = {
};
const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();
const pendingSavedEnvironmentConnections = new Map<EnvironmentId, Promise<EnvironmentConnection>>();
const environmentConnectionListeners = new Set<() => void>();
const threadDetailSubscriptions = new Map<string, ThreadDetailSubscriptionEntry>();
const lastAppliedProjectionVersionByEnvironment = new Map<
@@ -108,6 +113,7 @@ let needsProviderInvalidation = false;
const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000;
const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32;
const NOOP = () => undefined;
const SSH_HTTP_STATUS_RE = /^\[ssh_http:(\d+)\]\s/u;
function compareAppliedProjectionVersion(
left: { readonly sequence: number; readonly updatedAt: string | null },
@@ -491,6 +497,206 @@ function isoNow(): string {
return new Date().toISOString();
}
function readSshHttpErrorStatus(error: unknown): number | null {
if (!(error instanceof Error)) {
return null;
}
const match = SSH_HTTP_STATUS_RE.exec(error.message);
if (!match) {
return null;
}
const parsed = Number.parseInt(match[1] ?? "", 10);
return Number.isInteger(parsed) ? parsed : null;
}
function isSshHttpAuthError(error: unknown, status: number): boolean {
return readSshHttpErrorStatus(error) === status;
}
function isDesktopSshTargetEqual(
left: DesktopSshEnvironmentTarget | undefined,
right: DesktopSshEnvironmentTarget | undefined,
): boolean {
if (!left || !right) {
return false;
}
return (
left.alias === right.alias &&
left.hostname === right.hostname &&
left.username === right.username &&
left.port === right.port
);
}
function findSavedEnvironmentRecordByDesktopSshTarget(
target: DesktopSshEnvironmentTarget | undefined,
): SavedEnvironmentRecord | null {
if (!target) {
return null;
}
return (
listSavedEnvironmentRecords().find((record) =>
isDesktopSshTargetEqual(record.desktopSsh, target),
) ?? null
);
}
function buildSavedEnvironmentRegistryById(
records: ReadonlyArray<SavedEnvironmentRecord>,
): Record<EnvironmentId, SavedEnvironmentRecord> {
return Object.fromEntries(records.map((record) => [record.environmentId, record])) as Record<
EnvironmentId,
SavedEnvironmentRecord
>;
}
type SavedEnvironmentRegistrySnapshot = ReadonlyMap<EnvironmentId, SavedEnvironmentRecord | null>;
function snapshotSavedEnvironmentRegistry(
environmentIds: ReadonlyArray<EnvironmentId>,
): SavedEnvironmentRegistrySnapshot {
return new Map(
environmentIds.map((environmentId) => [
environmentId,
getSavedEnvironmentRecord(environmentId) ?? null,
]),
);
}
async function persistSavedEnvironmentRegistryRollback(
snapshot: SavedEnvironmentRegistrySnapshot,
): Promise<void> {
const byId = buildSavedEnvironmentRegistryById(listSavedEnvironmentRecords());
for (const [environmentId, record] of snapshot) {
if (record) {
byId[environmentId] = record;
continue;
}
delete byId[environmentId];
}
const records = Object.values(byId);
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
records.map((entry) => toPersistedSavedEnvironmentRecord(entry)),
);
useSavedEnvironmentRegistryStore.setState({
byId,
});
}
async function resolveDesktopSshEnvironmentBootstrap(
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
): Promise<DesktopSshEnvironmentBootstrap> {
const desktopBridge = window.desktopBridge;
if (!desktopBridge) {
throw new Error("SSH launch is only available in the desktop app.");
}
return await desktopBridge.ensureSshEnvironment(target, options);
}
function getDesktopSshBridge() {
const desktopBridge = window.desktopBridge;
if (!desktopBridge) {
throw new Error("SSH launch is only available in the desktop app.");
}
return desktopBridge;
}
async function fetchDesktopSshEnvironmentDescriptor(httpBaseUrl: string) {
return await getDesktopSshBridge().fetchSshEnvironmentDescriptor(httpBaseUrl);
}
async function bootstrapDesktopSshBearerSession(httpBaseUrl: string, credential: string) {
return await getDesktopSshBridge().bootstrapSshBearerSession(httpBaseUrl, credential);
}
async function fetchDesktopSshSessionState(httpBaseUrl: string, bearerToken: string) {
return await getDesktopSshBridge().fetchSshSessionState(httpBaseUrl, bearerToken);
}
async function resolveDesktopSshWebSocketConnectionUrl(
wsBaseUrl: string,
httpBaseUrl: string,
bearerToken: string,
) {
const issued = await getDesktopSshBridge().issueSshWebSocketToken(httpBaseUrl, bearerToken);
const url = new URL(wsBaseUrl, window.location.origin);
url.searchParams.set("wsToken", issued.token);
return url.toString();
}
async function prepareSavedEnvironmentRecordForConnection(
record: SavedEnvironmentRecord,
options?: { readonly issuePairingToken?: boolean },
): Promise<{
readonly record: SavedEnvironmentRecord;
readonly pairingToken: string | null;
}> {
if (!record.desktopSsh) {
return { record, pairingToken: null };
}
const bootstrap = await resolveDesktopSshEnvironmentBootstrap(record.desktopSsh, options);
const nextRecord: SavedEnvironmentRecord = {
...record,
httpBaseUrl: bootstrap.httpBaseUrl,
wsBaseUrl: bootstrap.wsBaseUrl,
desktopSsh: bootstrap.target,
};
if (
nextRecord.httpBaseUrl !== record.httpBaseUrl ||
nextRecord.wsBaseUrl !== record.wsBaseUrl ||
!isDesktopSshTargetEqual(nextRecord.desktopSsh, record.desktopSsh)
) {
await persistSavedEnvironmentRecord(nextRecord);
useSavedEnvironmentRegistryStore.getState().upsert(nextRecord);
}
return {
record: nextRecord,
pairingToken: bootstrap.pairingToken,
};
}
async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Promise<{
readonly record: SavedEnvironmentRecord;
readonly bearerToken: string;
readonly role: AuthSessionRole | null;
}> {
const registrySnapshot = snapshotSavedEnvironmentRegistry([record.environmentId]);
const prepared = await prepareSavedEnvironmentRecordForConnection(record, {
issuePairingToken: true,
});
if (!prepared.pairingToken) {
throw new Error("Desktop SSH launch did not return a pairing token.");
}
const bearerSession = await bootstrapDesktopSshBearerSession(
prepared.record.httpBaseUrl,
prepared.pairingToken,
);
const didPersistBearerToken = await writeSavedEnvironmentBearerToken(
prepared.record.environmentId,
bearerSession.sessionToken,
);
if (!didPersistBearerToken) {
await persistSavedEnvironmentRegistryRollback(registrySnapshot);
throw new Error("Unable to persist saved environment credentials.");
}
return {
record: prepared.record,
bearerToken: bearerSession.sessionToken,
role: bearerSession.role ?? null,
};
}
function setRuntimeConnecting(environmentId: EnvironmentId) {
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "connecting",
@@ -797,40 +1003,57 @@ function createPrimaryEnvironmentClient(
`Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
);
}
const connectionLabel = knownEnvironment?.label ?? null;
return createWsRpcClient(new WsTransport(wsBaseUrl));
return createWsRpcClient(
new WsTransport(wsBaseUrl, {
getConnectionLabel: () => connectionLabel,
}),
);
}
function createSavedEnvironmentClient(
record: SavedEnvironmentRecord,
environmentId: EnvironmentId,
bearerToken: string,
): WsRpcClient {
useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
useSavedEnvironmentRuntimeStore.getState().ensure(environmentId);
return createWsRpcClient(
new WsTransport(
() =>
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
}),
async () => {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
return record.desktopSsh
? await resolveDesktopSshWebSocketConnectionUrl(
record.wsBaseUrl,
record.httpBaseUrl,
bearerToken,
)
: await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
});
},
{
getConnectionLabel: () => getSavedEnvironmentRecord(environmentId)?.label ?? null,
onAttempt: () => {
setRuntimeConnecting(record.environmentId);
setRuntimeConnecting(environmentId);
},
onOpen: () => {
setRuntimeConnected(record.environmentId);
setRuntimeConnected(environmentId);
},
onError: (message: string) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "error",
lastError: message,
lastErrorAt: isoNow(),
});
},
onClose: (details: { readonly code: number; readonly reason: string }) => {
setRuntimeDisconnected(record.environmentId, details.reason);
setRuntimeDisconnected(environmentId, details.reason);
},
},
),
@@ -838,18 +1061,25 @@ function createSavedEnvironmentClient(
}
async function refreshSavedEnvironmentMetadata(
record: SavedEnvironmentRecord,
environmentId: EnvironmentId,
bearerToken: string,
client: WsRpcClient,
roleHint?: AuthSessionRole | null,
configHint?: ServerConfig | null,
): Promise<void> {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
const [serverConfig, sessionState] = await Promise.all([
configHint ? Promise.resolve(configHint) : client.server.getConfig(),
fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken,
}),
record.desktopSsh
? fetchDesktopSshSessionState(record.httpBaseUrl, bearerToken)
: fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken,
}),
]);
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
@@ -858,6 +1088,9 @@ async function refreshSavedEnvironmentMetadata(
serverConfig,
role: sessionState.authenticated ? (sessionState.role ?? roleHint ?? null) : null,
});
useSavedEnvironmentRegistryStore
.getState()
.rename(record.environmentId, serverConfig.environment.label);
}
function registerConnection(connection: EnvironmentConnection): EnvironmentConnection {
@@ -905,6 +1138,10 @@ function createPrimaryEnvironmentConnection(): EnvironmentConnection {
);
}
function maybeCreatePrimaryEnvironmentConnection(): EnvironmentConnection | null {
return getPrimaryKnownEnvironment()?.environmentId ? createPrimaryEnvironmentConnection() : null;
}
async function ensureSavedEnvironmentConnection(
record: SavedEnvironmentRecord,
options?: {
@@ -919,69 +1156,131 @@ async function ensureSavedEnvironmentConnection(
return existing;
}
const bearerToken =
options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
if (!bearerToken) {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
authState: "requires-auth",
role: null,
connectionState: "disconnected",
lastError: "Saved environment is missing its saved credential. Pair it again.",
lastErrorAt: isoNow(),
const pending = pendingSavedEnvironmentConnections.get(record.environmentId);
if (pending) {
return pending;
}
const nextConnection = (async () => {
let activeRecord = record;
let roleHint = options?.role ?? null;
let bearerToken =
options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
if (!bearerToken) {
if (record.desktopSsh) {
const issued = await issueDesktopSshBearerSession(record);
activeRecord = issued.record;
bearerToken = issued.bearerToken;
roleHint = issued.role;
} else {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
authState: "requires-auth",
role: null,
connectionState: "disconnected",
lastError: "Saved environment is missing its saved credential. Pair it again.",
lastErrorAt: isoNow(),
});
throw new Error("Saved environment is missing its saved credential.");
}
} else {
const prepared = await prepareSavedEnvironmentRecordForConnection(record);
activeRecord = prepared.record;
}
const activeBearerToken = bearerToken;
const client =
options?.client ??
createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken);
const knownEnvironment = createKnownEnvironment({
id: activeRecord.environmentId,
label: activeRecord.label,
source: "manual",
target: {
httpBaseUrl: activeRecord.httpBaseUrl,
wsBaseUrl: activeRecord.wsBaseUrl,
},
});
throw new Error("Saved environment is missing its saved credential.");
}
const client = options?.client ?? createSavedEnvironmentClient(record, bearerToken);
const knownEnvironment = createKnownEnvironment({
id: record.environmentId,
label: record.label,
source: "manual",
target: {
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
},
});
const connection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
...knownEnvironment,
environmentId: record.environmentId,
},
client,
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(record, bearerToken, client);
},
onConfigSnapshot: (config) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
descriptor: config.environment,
serverConfig: config,
});
},
onWelcome: (payload) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
descriptor: payload.environment,
});
},
...createEnvironmentConnectionHandlers(),
});
registerConnection(connection);
try {
await refreshSavedEnvironmentMetadata(
record,
bearerToken,
const connection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
...knownEnvironment,
environmentId: activeRecord.environmentId,
},
client,
options?.role ?? null,
options?.serverConfig ?? null,
);
return connection;
} catch (error) {
setRuntimeError(record.environmentId, error);
await removeConnection(record.environmentId).catch(() => false);
throw error;
}
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(
activeRecord.environmentId,
activeBearerToken,
client,
);
},
onConfigSnapshot: (config) => {
useSavedEnvironmentRuntimeStore.getState().patch(activeRecord.environmentId, {
descriptor: config.environment,
serverConfig: config,
});
},
onWelcome: (payload) => {
useSavedEnvironmentRuntimeStore.getState().patch(activeRecord.environmentId, {
descriptor: payload.environment,
});
},
...createEnvironmentConnectionHandlers(),
});
try {
try {
await refreshSavedEnvironmentMetadata(
activeRecord.environmentId,
activeBearerToken,
client,
roleHint,
options?.serverConfig ?? null,
);
} catch (error) {
const isAuthError = activeRecord.desktopSsh
? isSshHttpAuthError(error, 401)
: isRemoteEnvironmentAuthHttpError(error) && error.status === 401;
if (!isAuthError) {
throw error;
}
if (!activeRecord.desktopSsh) {
await removeSavedEnvironmentBearerToken(activeRecord.environmentId);
throw new Error("Saved environment credential expired. Pair it again.", {
cause: error,
});
}
const issued = await issueDesktopSshBearerSession(activeRecord);
activeRecord = issued.record;
bearerToken = issued.bearerToken;
roleHint = issued.role;
await connection.dispose().catch(() => undefined);
pendingSavedEnvironmentConnections.delete(activeRecord.environmentId);
return await ensureSavedEnvironmentConnection(activeRecord, {
bearerToken,
role: roleHint,
serverConfig: options?.serverConfig ?? null,
});
}
registerConnection(connection);
return connection;
} catch (error) {
setRuntimeError(activeRecord.environmentId, error);
const removed = await removeConnection(activeRecord.environmentId).catch(() => false);
if (!removed) {
await connection.dispose().catch(() => undefined);
}
throw error;
}
})();
pendingSavedEnvironmentConnections.set(record.environmentId, nextConnection);
return await nextConnection.finally(() => {
if (pendingSavedEnvironmentConnections.get(record.environmentId) === nextConnection) {
pendingSavedEnvironmentConnections.delete(record.environmentId);
}
});
}
async function syncSavedEnvironmentConnections(
@@ -1036,13 +1335,18 @@ export function getPrimaryEnvironmentConnection(): EnvironmentConnection {
}
export async function disconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
const record = getSavedEnvironmentRecord(environmentId);
const connection = environmentConnections.get(environmentId);
if (connection?.kind !== "saved") {
return;
}
useSavedEnvironmentRuntimeStore.getState().clear(environmentId);
await removeConnection(environmentId).catch(() => false);
if (connection?.kind === "saved") {
await removeConnection(environmentId).catch(() => false);
}
setRuntimeDisconnected(environmentId);
if (record?.desktopSsh && typeof window !== "undefined") {
await window.desktopBridge?.disconnectSshEnvironment(record.desktopSsh);
await removeSavedEnvironmentBearerToken(environmentId);
}
}
export async function reconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
@@ -1053,23 +1357,49 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): P
const connection = environmentConnections.get(environmentId);
if (!connection) {
await ensureSavedEnvironmentConnection(record);
return;
setRuntimeConnecting(environmentId);
try {
await ensureSavedEnvironmentConnection(record);
return;
} catch (error) {
setRuntimeError(environmentId, error);
throw error;
}
}
setRuntimeConnecting(environmentId);
try {
if (record.desktopSsh) {
await prepareSavedEnvironmentRecordForConnection(record);
}
await connection.reconnect();
} catch (error) {
if (record.desktopSsh) {
try {
const issued = await issueDesktopSshBearerSession(
getSavedEnvironmentRecord(environmentId) ?? record,
);
await removeConnection(environmentId).catch(() => false);
await ensureSavedEnvironmentConnection(issued.record, {
bearerToken: issued.bearerToken,
role: issued.role,
});
return;
} catch (recoveryError) {
setRuntimeError(environmentId, recoveryError);
throw recoveryError;
}
}
setRuntimeError(environmentId, error);
throw error;
}
}
export async function removeSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
useSavedEnvironmentRegistryStore.getState().remove(environmentId);
await removeSavedEnvironmentBearerToken(environmentId);
await disconnectSavedEnvironment(environmentId);
useSavedEnvironmentRegistryStore.getState().remove(environmentId);
useSavedEnvironmentRuntimeStore.getState().clear(environmentId);
await removeSavedEnvironmentBearerToken(environmentId);
}
export async function addSavedEnvironment(input: {
@@ -1077,33 +1407,43 @@ export async function addSavedEnvironment(input: {
readonly pairingUrl?: string;
readonly host?: string;
readonly pairingCode?: string;
readonly desktopSsh?: DesktopSshEnvironmentTarget;
}): Promise<SavedEnvironmentRecord> {
const resolvedTarget = resolveRemotePairingTarget({
...(input.pairingUrl !== undefined ? { pairingUrl: input.pairingUrl } : {}),
...(input.host !== undefined ? { host: input.host } : {}),
...(input.pairingCode !== undefined ? { pairingCode: input.pairingCode } : {}),
});
const descriptor = await fetchRemoteEnvironmentDescriptor({
httpBaseUrl: resolvedTarget.httpBaseUrl,
});
const descriptor = input.desktopSsh
? await fetchDesktopSshEnvironmentDescriptor(resolvedTarget.httpBaseUrl)
: await fetchRemoteEnvironmentDescriptor({
httpBaseUrl: resolvedTarget.httpBaseUrl,
});
const environmentId = descriptor.environmentId;
const registrySnapshot = snapshotSavedEnvironmentRegistry([environmentId]);
const existingRecord =
getSavedEnvironmentRecord(environmentId) ??
findSavedEnvironmentRecordByDesktopSshTarget(input.desktopSsh);
const staleDesktopSshRecord =
existingRecord && existingRecord.environmentId !== environmentId ? existingRecord : null;
if (environmentConnections.has(environmentId)) {
throw new Error("This environment is already connected.");
}
const bearerSession = await bootstrapRemoteBearerSession({
httpBaseUrl: resolvedTarget.httpBaseUrl,
credential: resolvedTarget.credential,
});
const bearerSession = input.desktopSsh
? await bootstrapDesktopSshBearerSession(resolvedTarget.httpBaseUrl, resolvedTarget.credential)
: await bootstrapRemoteBearerSession({
httpBaseUrl: resolvedTarget.httpBaseUrl,
credential: resolvedTarget.credential,
});
const record: SavedEnvironmentRecord = {
environmentId,
label: input.label.trim() || descriptor.label,
label: input.label.trim() || existingRecord?.label || descriptor.label,
wsBaseUrl: resolvedTarget.wsBaseUrl,
httpBaseUrl: resolvedTarget.httpBaseUrl,
createdAt: isoNow(),
createdAt: existingRecord?.createdAt ?? isoNow(),
lastConnectedAt: isoNow(),
...((input.desktopSsh ?? existingRecord?.desktopSsh)
? { desktopSsh: input.desktopSsh ?? existingRecord?.desktopSsh }
: {}),
};
await persistSavedEnvironmentRecord(record);
@@ -1112,26 +1452,40 @@ export async function addSavedEnvironment(input: {
bearerSession.sessionToken,
);
if (!didPersistBearerToken) {
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
listSavedEnvironmentRecords().map((entry) => ({
environmentId: entry.environmentId,
label: entry.label,
httpBaseUrl: entry.httpBaseUrl,
wsBaseUrl: entry.wsBaseUrl,
createdAt: entry.createdAt,
lastConnectedAt: entry.lastConnectedAt,
})),
);
await persistSavedEnvironmentRegistryRollback(registrySnapshot);
throw new Error("Unable to persist saved environment credentials.");
}
useSavedEnvironmentRegistryStore.getState().upsert(record);
if (staleDesktopSshRecord) {
await removeSavedEnvironment(staleDesktopSshRecord.environmentId);
}
await removeConnection(environmentId).catch(() => false);
await ensureSavedEnvironmentConnection(record, {
bearerToken: bearerSession.sessionToken,
role: bearerSession.role,
});
useSavedEnvironmentRegistryStore.getState().upsert(record);
return record;
}
export async function connectDesktopSshEnvironment(
target: DesktopSshEnvironmentTarget,
options?: { label?: string },
): Promise<SavedEnvironmentRecord> {
const bootstrap = await resolveDesktopSshEnvironmentBootstrap(target, {
issuePairingToken: true,
});
if (!bootstrap.pairingToken) {
throw new Error("Desktop SSH launch did not return a pairing token.");
}
return await addSavedEnvironment({
label: options?.label?.trim() || bootstrap.target.alias,
host: bootstrap.httpBaseUrl,
pairingCode: bootstrap.pairingToken,
desktopSsh: bootstrap.target,
});
}
export async function ensureEnvironmentConnectionBootstrapped(
environmentId: EnvironmentId,
): Promise<void> {
@@ -1170,7 +1524,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
},
);
createPrimaryEnvironmentConnection();
maybeCreatePrimaryEnvironmentConnection();
const unsubscribeSavedEnvironments = useSavedEnvironmentRegistryStore.subscribe(() => {
if (!hasSavedEnvironmentRegistryHydrated()) {
@@ -1207,6 +1561,7 @@ export function startEnvironmentConnectionService(queryClient: QueryClient): ()
export async function resetEnvironmentServiceForTests(): Promise<void> {
stopActiveService();
lastAppliedProjectionVersionByEnvironment.clear();
pendingSavedEnvironmentConnections.clear();
for (const key of Array.from(threadDetailSubscriptions.keys())) {
disposeThreadDetailSubscriptionByKey(key);
}
+66
View File
@@ -0,0 +1,66 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
buildHostedPairingUrl,
hasHostedPairingRequest,
isHostedStaticApp,
readHostedPairingRequest,
} from "./hostedPairing";
describe("hostedPairing", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("reads hosted pairing host and query token parameters", () => {
const url = new URL("https://app.t3.codes/pair?host=100.64.1.2:3773&token=ABCD1234");
expect(readHostedPairingRequest(url)).toEqual({
host: "100.64.1.2:3773",
token: "ABCD1234",
label: "",
});
expect(hasHostedPairingRequest(url)).toBe(true);
});
it("prefers hash tokens so generated hosted links do not put credentials in search params", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes");
const url = new URL(
buildHostedPairingUrl({
host: "https://backend.example.com:3773",
token: "pairing-token",
label: "Workstation",
}),
);
expect(url.origin).toBe("https://preview.t3.codes");
expect(url.pathname).toBe("/pair");
expect(url.searchParams.get("host")).toBe("https://backend.example.com:3773");
expect(url.searchParams.get("label")).toBe("Workstation");
expect(url.searchParams.has("token")).toBe(false);
expect(url.hash).toBe("#token=pairing-token");
});
it("ignores incomplete hosted pairing requests", () => {
expect(
hasHostedPairingRequest(new URL("https://app.t3.codes/pair?host=backend.example.com")),
).toBe(false);
expect(hasHostedPairingRequest(new URL("https://app.t3.codes/pair?token=ABCD1234"))).toBe(
false,
);
});
it("detects the hosted static app only when no backend URL is configured", () => {
vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes");
vi.stubEnv("VITE_HTTP_URL", "");
vi.stubEnv("VITE_WS_URL", "");
expect(isHostedStaticApp(new URL("https://preview.t3.codes/"))).toBe(true);
expect(isHostedStaticApp(new URL("https://preview.t3.codes/pair"))).toBe(true);
expect(isHostedStaticApp(new URL("https://backend.example.com/"))).toBe(false);
vi.stubEnv("VITE_HTTP_URL", "https://backend.example.com");
expect(isHostedStaticApp(new URL("https://preview.t3.codes/"))).toBe(false);
});
});
+70
View File
@@ -0,0 +1,70 @@
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
export interface HostedPairingRequest {
readonly host: string;
readonly token: string;
readonly label: string;
}
function configuredHostedAppUrl(): string {
return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
}
function configuredBackendUrl(): string {
return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
}
function originFromUrl(value: string): string | null {
try {
return new URL(value).origin;
} catch {
return null;
}
}
export function isHostedStaticApp(url: URL = new URL(window.location.href)): boolean {
if (configuredBackendUrl()) {
return false;
}
const hostedOrigin = originFromUrl(configuredHostedAppUrl());
return hostedOrigin !== null && url.origin === hostedOrigin;
}
export function readHostedPairingRequest(url: URL = new URL(window.location.href)) {
const host = url.searchParams.get("host")?.trim() ?? "";
const token = getPairingTokenFromUrl(url)?.trim() ?? "";
const label = url.searchParams.get("label")?.trim() ?? "";
if (!host || !token) {
return null;
}
return {
host,
token,
label,
} satisfies HostedPairingRequest;
}
export function hasHostedPairingRequest(url: URL = new URL(window.location.href)): boolean {
return readHostedPairingRequest(url) !== null;
}
export function buildHostedPairingUrl(input: {
readonly host: string;
readonly token: string;
readonly label?: string | null;
}): string {
const url = new URL("/pair", configuredHostedAppUrl());
url.searchParams.set("host", input.host);
const label = input.label?.trim();
if (label) {
url.searchParams.set("label", label);
}
return setPairingTokenOnUrl(url, input.token).toString();
}
+31
View File
@@ -169,16 +169,47 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
discoverSshHosts: async () => [],
ensureSshEnvironment: async () => {
throw new Error("ensureSshEnvironment not implemented in test");
},
disconnectSshEnvironment: async () => undefined,
fetchSshEnvironmentDescriptor: async () => {
throw new Error("fetchSshEnvironmentDescriptor not implemented in test");
},
bootstrapSshBearerSession: async () => {
throw new Error("bootstrapSshBearerSession not implemented in test");
},
fetchSshSessionState: async () => {
throw new Error("fetchSshSessionState not implemented in test");
},
issueSshWebSocketToken: async () => {
throw new Error("issueSshWebSocketToken not implemented in test");
},
onSshPasswordPrompt: () => () => undefined,
resolveSshPasswordPrompt: async () => undefined,
getServerExposureState: async () => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
}),
setServerExposureMode: async () => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
}),
setTailscaleServeEnabled: async (input) => ({
mode: "local-only",
endpointUrl: null,
advertisedHost: null,
tailscaleServeEnabled: input.enabled,
tailscaleServePort: input.port ?? 443,
}),
getAdvertisedEndpoints: async () => [],
pickFolder: async () => null,
confirm: async () => true,
setTheme: async () => undefined,
+34 -8
View File
@@ -12,6 +12,7 @@ import {
getPrimaryEnvironmentConnection,
resetEnvironmentServiceForTests,
} from "./environments/runtime";
import { getPrimaryKnownEnvironment } from "./environments/primary";
import { type WsRpcClient } from "./rpc/wsRpcClient";
import { showContextMenuFallback } from "./contextMenuFallback";
import {
@@ -26,7 +27,11 @@ import {
let cachedApi: LocalApi | undefined;
export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
function unavailableLocalBackendError(): Error {
return new Error("Local backend API is unavailable before a backend is paired.");
}
function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
return {
dialogs: {
pickFolder: async (options) => {
@@ -41,7 +46,10 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
},
},
shell: {
openInEditor: (cwd, editor) => rpcClient.shell.openInEditor({ cwd, editor }),
openInEditor: (cwd, editor) =>
rpcClient
? rpcClient.shell.openInEditor({ cwd, editor })
: Promise.reject(unavailableLocalBackendError()),
openExternal: async (url) => {
if (window.desktopBridge) {
const opened = await window.desktopBridge.openExternal(url);
@@ -110,15 +118,30 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
},
},
server: {
getConfig: rpcClient.server.getConfig,
refreshProviders: rpcClient.server.refreshProviders,
upsertKeybinding: rpcClient.server.upsertKeybinding,
getSettings: rpcClient.server.getSettings,
updateSettings: rpcClient.server.updateSettings,
getConfig: () =>
rpcClient ? rpcClient.server.getConfig() : Promise.reject(unavailableLocalBackendError()),
refreshProviders: () =>
rpcClient
? rpcClient.server.refreshProviders()
: Promise.reject(unavailableLocalBackendError()),
upsertKeybinding: (input) =>
rpcClient
? rpcClient.server.upsertKeybinding(input)
: Promise.reject(unavailableLocalBackendError()),
getSettings: () =>
rpcClient ? rpcClient.server.getSettings() : Promise.reject(unavailableLocalBackendError()),
updateSettings: (patch) =>
rpcClient
? rpcClient.server.updateSettings(patch)
: Promise.reject(unavailableLocalBackendError()),
},
};
}
export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
return createBrowserLocalApi(rpcClient);
}
export function readLocalApi(): LocalApi | undefined {
if (typeof window === "undefined") return undefined;
if (cachedApi) return cachedApi;
@@ -128,7 +151,10 @@ export function readLocalApi(): LocalApi | undefined {
return cachedApi;
}
cachedApi = createLocalApi(getPrimaryEnvironmentConnection().client);
const primaryEnvironment = getPrimaryKnownEnvironment();
cachedApi = primaryEnvironment
? createLocalApi(getPrimaryEnvironmentConnection().client)
: createBrowserLocalApi();
return cachedApi;
}
+103 -22
View File
@@ -13,6 +13,7 @@ import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { APP_DISPLAY_NAME } from "../branding";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import {
SlowRpcAckToastCoordinator,
WebSocketConnectionCoordinator,
@@ -46,26 +47,64 @@ import { syncBrowserChromeTheme } from "../hooks/useTheme";
import {
ensureEnvironmentConnectionBootstrapped,
getPrimaryEnvironmentConnection,
listSavedEnvironmentRecords,
waitForSavedEnvironmentRegistryHydration,
startEnvironmentConnectionService,
useSavedEnvironmentRegistryStore,
} from "../environments/runtime";
import { configureClientTracing } from "../observability/clientTracing";
import {
ensurePrimaryEnvironmentReady,
getPrimaryKnownEnvironment,
resolveInitialServerAuthGateState,
updatePrimaryEnvironmentDescriptor,
} from "../environments/primary";
import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
}>()({
beforeLoad: async () => {
const [, authGateState] = await Promise.all([
ensurePrimaryEnvironmentReady(),
resolveInitialServerAuthGateState(),
]);
return {
authGateState,
};
beforeLoad: async ({ location }) => {
if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
return {
authGateState: {
status: "hosted-pairing",
} as const,
};
}
if (isHostedStaticApp(new URL(window.location.href))) {
await waitForSavedEnvironmentRegistryHydration();
return {
authGateState: {
status: "hosted-static",
} as const,
};
}
try {
const [, authGateState] = await Promise.all([
ensurePrimaryEnvironmentReady(),
resolveInitialServerAuthGateState(),
]);
return {
authGateState,
};
} catch (error) {
if (location.pathname === "/pair") {
throw error;
}
if (!isHostedStaticApp(new URL(window.location.href))) {
throw error;
}
await waitForSavedEnvironmentRegistryHydration();
return {
authGateState: {
status: "hosted-static",
} as const,
};
}
},
component: RootRouteView,
errorComponent: RootRouteErrorView,
@@ -77,6 +116,7 @@ export const Route = createRootRouteWithContext<{
function RootRouteView() {
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
@@ -91,30 +131,65 @@ function RootRouteView() {
return <Outlet />;
}
if (authGateState.status !== "authenticated") {
if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
return <Outlet />;
}
const appShell = (
<CommandPalette>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</CommandPalette>
);
return (
<ToastProvider>
<AnchoredToastProvider>
<AuthenticatedTracingBootstrap />
<ServerStateBootstrap />
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
{primaryEnvironmentAuthenticated ? <ServerStateBootstrap /> : null}
<EnvironmentConnectionManagerBootstrap />
<EventRouter />
<WebSocketConnectionCoordinator />
<SlowRpcAckToastCoordinator />
<WebSocketConnectionSurface>
<CommandPalette>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</CommandPalette>
</WebSocketConnectionSurface>
<SshPasswordPromptDialog />
<HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
{primaryEnvironmentAuthenticated ? <WebSocketConnectionCoordinator /> : null}
{primaryEnvironmentAuthenticated ? <SlowRpcAckToastCoordinator /> : null}
{primaryEnvironmentAuthenticated ? (
<WebSocketConnectionSurface>{appShell}</WebSocketConnectionSurface>
) : (
appShell
)}
</AnchoredToastProvider>
</ToastProvider>
);
}
function HostedStaticEnvironmentBootstrap() {
const savedEnvironmentCount = useSavedEnvironmentRegistryStore(
(state) => Object.keys(state.byId).length,
);
useEffect(() => {
if (getPrimaryKnownEnvironment()) {
return;
}
const currentActiveEnvironmentId = useStore.getState().activeEnvironmentId;
if (currentActiveEnvironmentId) {
return;
}
const firstSavedEnvironment = listSavedEnvironmentRecords()[0];
if (!firstSavedEnvironment) {
return;
}
useStore.getState().setActiveEnvironmentId(firstSavedEnvironment.environmentId);
}, [savedEnvironmentCount]);
return null;
}
function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
const message = errorMessage(error);
const details = errorDetails(error);
@@ -187,7 +262,13 @@ function errorDetails(error: unknown): string {
}
function ServerStateBootstrap() {
useEffect(() => startServerStateSync(getPrimaryEnvironmentConnection().client.server), []);
useEffect(() => {
if (!getPrimaryKnownEnvironment()) {
return;
}
return startServerStateSync(getPrimaryEnvironmentConnection().client.server);
}, []);
return null;
}
+55
View File
@@ -1,11 +1,66 @@
import { createFileRoute } from "@tanstack/react-router";
import { LinkIcon, PlusIcon } from "lucide-react";
import { NoActiveThreadState } from "../components/NoActiveThreadState";
import { Button } from "../components/ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
import { useSavedEnvironmentRegistryStore } from "../environments/runtime";
import { APP_DISPLAY_NAME } from "~/branding";
function ChatIndexRouteView() {
const { authGateState } = Route.useRouteContext();
const savedEnvironmentCount = useSavedEnvironmentRegistryStore(
(state) => Object.keys(state.byId).length,
);
if (authGateState.status === "hosted-static" && savedEnvironmentCount === 0) {
return <HostedStaticOnboardingState />;
}
return <NoActiveThreadState />;
}
export const Route = createFileRoute("/_chat/")({
component: ChatIndexRouteView,
});
function HostedStaticOnboardingState() {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<header className="border-b border-border px-3 py-2 sm:px-5 sm:py-3">
<div className="flex items-center gap-2">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<span className="text-sm font-medium text-foreground md:text-muted-foreground/60">
{APP_DISPLAY_NAME}
</span>
</div>
</header>
<Empty className="flex-1">
<div className="w-full max-w-xl rounded-3xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
<EmptyHeader className="max-w-none">
<div className="mx-auto mb-5 flex size-11 items-center justify-center rounded-xl border border-border/70 bg-background/70 text-muted-foreground">
<LinkIcon className="size-5" />
</div>
<EmptyTitle className="text-foreground text-xl">
Connect an environment to get started
</EmptyTitle>
<EmptyDescription className="mt-2 text-sm leading-relaxed text-muted-foreground/78">
Open a pairing link from your T3 Code desktop app or add a reachable backend
manually. Your saved environments stay in this browser.
</EmptyDescription>
<div className="mt-6 flex justify-center">
<Button render={<a href="/settings/connections" />} size="sm">
<PlusIcon className="size-4" />
Add environment
</Button>
</div>
</EmptyHeader>
</div>
</Empty>
</div>
</SidebarInset>
);
}
+4 -1
View File
@@ -108,7 +108,10 @@ function ChatRouteLayout() {
export const Route = createFileRoute("/_chat")({
beforeLoad: async ({ context }) => {
if (context.authGateState.status !== "authenticated") {
if (
context.authGateState.status !== "authenticated" &&
context.authGateState.status !== "hosted-static"
) {
throw redirect({ to: "/pair", replace: true });
}
},
+16 -2
View File
@@ -1,11 +1,21 @@
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import { PairingPendingSurface, PairingRouteSurface } from "../components/auth/PairingRouteSurface";
import {
HostedPairingRouteSurface,
PairingPendingSurface,
PairingRouteSurface,
} from "../components/auth/PairingRouteSurface";
export const Route = createFileRoute("/pair")({
beforeLoad: async ({ context }) => {
const { authGateState } = context;
if (authGateState.status === "authenticated") {
if (authGateState.status === "hosted-pairing") {
return {
authGateState,
};
}
if (authGateState.status === "authenticated" || authGateState.status === "hosted-static") {
throw redirect({ to: "/", replace: true });
}
return {
@@ -24,6 +34,10 @@ function PairRouteView() {
return null;
}
if (authGateState.status === "hosted-pairing") {
return <HostedPairingRouteSurface />;
}
return (
<PairingRouteSurface
auth={authGateState.auth}
+4 -1
View File
@@ -88,7 +88,10 @@ function SettingsRouteLayout() {
export const Route = createFileRoute("/settings")({
beforeLoad: async ({ context, location }) => {
if (context.authGateState.status !== "authenticated") {
if (
context.authGateState.status !== "authenticated" &&
context.authGateState.status !== "hosted-static"
) {
throw redirect({ to: "/pair", replace: true });
}
+49 -15
View File
@@ -14,14 +14,24 @@ import {
recordWsConnectionClosed,
recordWsConnectionErrored,
recordWsConnectionOpened,
type WsConnectionMetadata,
WS_RECONNECT_MAX_RETRIES,
} from "./wsConnectionState";
export interface WsProtocolCloseContext {
readonly intentional: boolean;
}
export interface WsProtocolLifecycleHandlers {
readonly getConnectionLabel?: () => string | null;
readonly isCloseIntentional?: () => boolean;
readonly onAttempt?: (socketUrl: string) => void;
readonly onOpen?: () => void;
readonly onError?: (message: string) => void;
readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void;
readonly onClose?: (
details: { readonly code: number; readonly reason: string },
context: WsProtocolCloseContext,
) => void;
}
export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup);
@@ -47,25 +57,44 @@ function resolveWsRpcSocketUrl(rawUrl: string): string {
return resolved.toString();
}
function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
function resolveConnectionMetadata(handlers?: WsProtocolLifecycleHandlers): WsConnectionMetadata {
return {
onAttempt: recordWsConnectionAttempt,
onOpen: recordWsConnectionOpened,
connectionLabel: handlers?.getConnectionLabel?.() ?? null,
};
}
type ComposedWsProtocolLifecycleHandlers = Required<
Pick<WsProtocolLifecycleHandlers, "onAttempt" | "onOpen" | "onError" | "onClose">
>;
function defaultLifecycleHandlers(
handlers?: WsProtocolLifecycleHandlers,
): ComposedWsProtocolLifecycleHandlers {
return {
onAttempt: (socketUrl) => {
recordWsConnectionAttempt(socketUrl, resolveConnectionMetadata(handlers));
},
onOpen: () => {
recordWsConnectionOpened(resolveConnectionMetadata(handlers));
},
onError: (message) => {
clearAllTrackedRpcRequests();
recordWsConnectionErrored(message);
},
onClose: (details) => {
onClose: (details, context) => {
clearAllTrackedRpcRequests();
recordWsConnectionClosed(details);
if (context.intentional) {
return;
}
recordWsConnectionClosed(details, resolveConnectionMetadata(handlers));
},
};
}
function composeLifecycleHandlers(
handlers?: WsProtocolLifecycleHandlers,
): Required<WsProtocolLifecycleHandlers> {
const defaults = defaultLifecycleHandlers();
): ComposedWsProtocolLifecycleHandlers {
const defaults = defaultLifecycleHandlers(handlers);
return {
onAttempt: (socketUrl) => {
@@ -80,9 +109,9 @@ function composeLifecycleHandlers(
defaults.onError(message);
handlers?.onError?.(message);
},
onClose: (details) => {
defaults.onClose(details);
handlers?.onClose?.(details);
onClose: (details, context) => {
defaults.onClose(details, context);
handlers?.onClose?.(details, context);
},
};
}
@@ -128,10 +157,15 @@ export function createWsRpcProtocolLayer(
socket.addEventListener(
"close",
(event) => {
lifecycle.onClose({
code: event.code,
reason: event.reason,
});
lifecycle.onClose(
{
code: event.code,
reason: event.reason,
},
{
intentional: handlers?.isCloseIntentional?.() ?? false,
},
);
},
{ once: true },
);
+4 -1
View File
@@ -45,7 +45,9 @@ describe("wsConnectionState", () => {
});
it("schedules the next retry after a failed websocket attempt", () => {
recordWsConnectionAttempt("ws://localhost:3020/ws");
recordWsConnectionAttempt("ws://localhost:3020/ws", {
connectionLabel: "Remote Mac",
});
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
const firstRetryDelayMs = getWsReconnectDelayMsForRetry(0);
@@ -54,6 +56,7 @@ describe("wsConnectionState", () => {
}
expect(getWsConnectionStatus()).toMatchObject({
connectionLabel: "Remote Mac",
nextRetryAt: new Date(Date.now() + firstRetryDelayMs).toISOString(),
reconnectAttemptCount: 1,
reconnectPhase: "waiting",
+38 -10
View File
@@ -16,6 +16,7 @@ export interface WsConnectionStatus {
readonly attemptCount: number;
readonly closeCode: number | null;
readonly closeReason: string | null;
readonly connectionLabel: string | null;
readonly connectedAt: string | null;
readonly disconnectedAt: string | null;
readonly hasConnected: boolean;
@@ -34,6 +35,7 @@ const INITIAL_WS_CONNECTION_STATUS = Object.freeze<WsConnectionStatus>({
attemptCount: 0,
closeCode: null,
closeReason: null,
connectionLabel: null,
connectedAt: null,
disconnectedAt: null,
hasConnected: false,
@@ -65,6 +67,15 @@ function updateWsConnectionStatus(
return nextStatus;
}
export interface WsConnectionMetadata {
readonly connectionLabel?: string | null;
}
function normalizeConnectionLabel(label: string | null | undefined): string | null {
const normalized = label?.trim();
return normalized ? normalized : null;
}
export function getWsConnectionStatus(): WsConnectionStatus {
return appAtomRegistry.get(wsConnectionStatusAtom);
}
@@ -85,10 +96,15 @@ export function getWsConnectionUiState(status: WsConnectionStatus): WsConnection
return "reconnecting";
}
export function recordWsConnectionAttempt(socketUrl: string): WsConnectionStatus {
export function recordWsConnectionAttempt(
socketUrl: string,
metadata?: WsConnectionMetadata,
): WsConnectionStatus {
const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
return updateWsConnectionStatus((current) => ({
...current,
attemptCount: current.attemptCount + 1,
connectionLabel: connectionLabel ?? current.connectionLabel,
nextRetryAt: null,
phase: "connecting",
reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1,
@@ -97,11 +113,13 @@ export function recordWsConnectionAttempt(socketUrl: string): WsConnectionStatus
}));
}
export function recordWsConnectionOpened(): WsConnectionStatus {
export function recordWsConnectionOpened(metadata?: WsConnectionMetadata): WsConnectionStatus {
const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
return updateWsConnectionStatus((current) => ({
...current,
closeCode: null,
closeReason: null,
connectionLabel: connectionLabel ?? current.connectionLabel,
connectedAt: isoNow(),
disconnectedAt: null,
hasConnected: true,
@@ -121,15 +139,23 @@ export function recordWsConnectionErrored(message?: string | null): WsConnection
);
}
export function recordWsConnectionClosed(details?: {
readonly code?: number;
readonly reason?: string;
}): WsConnectionStatus {
export function recordWsConnectionClosed(
details?: {
readonly code?: number;
readonly reason?: string;
},
metadata?: WsConnectionMetadata,
): WsConnectionStatus {
const connectionLabel = normalizeConnectionLabel(metadata?.connectionLabel);
return updateWsConnectionStatus((current) =>
applyDisconnectState(current, {
closeCode: details?.code ?? current.closeCode,
closeReason: details?.reason?.trim() ? details.reason : current.closeReason,
}),
applyDisconnectState(
current,
{
closeCode: details?.code ?? current.closeCode,
closeReason: details?.reason?.trim() ? details.reason : current.closeReason,
},
connectionLabel === null ? undefined : { connectionLabel },
),
);
}
@@ -173,6 +199,7 @@ function applyDisconnectState(
updates: Partial<
Pick<WsConnectionStatus, "closeCode" | "closeReason" | "lastError" | "lastErrorAt">
>,
metadata?: WsConnectionMetadata,
): WsConnectionStatus {
const disconnectedAt = current.disconnectedAt ?? isoNow();
const nextRetryDelayMs =
@@ -183,6 +210,7 @@ function applyDisconnectState(
return {
...current,
...updates,
connectionLabel: normalizeConnectionLabel(metadata?.connectionLabel) ?? current.connectionLabel,
disconnectedAt,
nextRetryAt:
nextRetryDelayMs === null
+49 -4
View File
@@ -284,10 +284,15 @@ describe("WsTransport", () => {
socket.close(1012, "service restart");
await waitFor(() => {
expect(onClose).toHaveBeenCalledWith({
code: 1012,
reason: "service restart",
});
expect(onClose).toHaveBeenCalledWith(
{
code: 1012,
reason: "service restart",
},
{
intentional: false,
},
);
expect(getWsConnectionStatus()).toMatchObject({
attemptCount: 2,
closeReason: "service restart",
@@ -298,6 +303,46 @@ describe("WsTransport", () => {
await transport.dispose();
});
it("does not report an intentional dispose as a reconnectable disconnect", async () => {
const onClose = vi.fn();
const transport = createTransport("ws://localhost:3020", {
getConnectionLabel: () => "Remote Mac mini",
onClose,
});
await waitFor(() => {
expect(sockets).toHaveLength(1);
});
const socket = getSocket();
socket.open();
await waitFor(() => {
expect(getWsConnectionStatus()).toMatchObject({
connectionLabel: "Remote Mac mini",
hasConnected: true,
phase: "connected",
});
});
await transport.dispose();
expect(onClose).toHaveBeenCalledWith(
{
code: 1000,
reason: "",
},
{
intentional: true,
},
);
expect(getWsConnectionStatus()).toMatchObject({
connectionLabel: "Remote Mac mini",
phase: "connected",
reconnectPhase: "idle",
});
});
it("reconnects the websocket session without disposing the transport", async () => {
const transport = createTransport("ws://localhost:3020");
+13 -1
View File
@@ -52,6 +52,7 @@ export class WsTransport {
private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined;
private disposed = false;
private hasReportedTransportDisconnect = false;
private intentionalCloseDepth = 0;
private reconnectChain: Promise<void> = Promise.resolve();
private session: TransportSession;
@@ -209,14 +210,25 @@ export class WsTransport {
}
private closeSession(session: TransportSession) {
this.intentionalCloseDepth += 1;
return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
this.intentionalCloseDepth -= 1;
session.runtime.dispose();
});
}
private createSession(): TransportSession {
const runtime = ManagedRuntime.make(
Layer.mergeAll(createWsRpcProtocolLayer(this.url, this.lifecycleHandlers), ClientTracingLive),
Layer.mergeAll(
createWsRpcProtocolLayer(this.url, {
...this.lifecycleHandlers,
isCloseIntentional: () =>
this.disposed ||
this.intentionalCloseDepth > 0 ||
this.lifecycleHandlers?.isCloseIntentional?.() === true,
}),
ClientTracingLive,
),
);
const clientScope = runtime.runSync(Scope.make());
return {
+48
View File
@@ -4,11 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
clearThreadUi,
hydratePersistedProjectState,
markThreadVisited,
markThreadUnread,
PERSISTED_STATE_KEY,
type PersistedUiState,
persistState,
reorderProjects,
setDefaultAdvertisedEndpointKey,
setProjectExpanded,
setThreadChangedFilesExpanded,
syncProjects,
@@ -22,11 +24,34 @@ function makeUiState(overrides: Partial<UiState> = {}): UiState {
projectOrder: [],
threadLastVisitedAtById: {},
threadChangedFilesExpandedById: {},
defaultAdvertisedEndpointKey: null,
...overrides,
};
}
describe("uiStateStore pure functions", () => {
it("markThreadVisited stores the provided server timestamp", () => {
const threadId = ThreadId.make("thread-1");
const initialState = makeUiState();
const next = markThreadVisited(initialState, threadId, "2026-02-25T12:30:00.700Z");
expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:30:00.700Z");
});
it("markThreadVisited does not move visit state backwards under clock skew", () => {
const threadId = ThreadId.make("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:30:00.700Z",
},
});
const next = markThreadVisited(initialState, threadId, "2026-02-25T12:30:00.000Z");
expect(next).toBe(initialState);
});
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const threadId = ThreadId.make("thread-1");
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
@@ -79,6 +104,18 @@ describe("uiStateStore pure functions", () => {
expect(next).toBe(initialState);
});
it("setDefaultAdvertisedEndpointKey stores endpoint preference by stable key", () => {
const initialState = makeUiState();
const next = setDefaultAdvertisedEndpointKey(initialState, "desktop-core:lan:http");
expect(next.defaultAdvertisedEndpointKey).toBe("desktop-core:lan:http");
expect(setDefaultAdvertisedEndpointKey(next, "desktop-core:lan:http")).toBe(next);
expect(setDefaultAdvertisedEndpointKey(next, "")).toMatchObject({
defaultAdvertisedEndpointKey: null,
});
});
it("reorderProjects moves all member keys of a multi-member group together", () => {
const keyALocal = "env-local:proj-a";
const keyARemote = "env-remote:proj-a";
@@ -531,6 +568,17 @@ describe("uiStateStore persistence round-trip", () => {
expect(rehydrated.projectOrder).toEqual([projectC.key, projectA.key, projectB.key]);
});
it("persists the default advertised endpoint preference", () => {
const state = setDefaultAdvertisedEndpointKey(makeUiState(), "desktop-core:lan:http");
persistState(state);
const persisted = JSON.parse(
localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
) as PersistedUiState;
expect(persisted.defaultAdvertisedEndpointKey).toBe("desktop-core:lan:http");
});
it("preserves expand state across restart when project's logical key changes", () => {
// After restart, in-memory previousExpandedById is empty, so the
// previousLogicalKey-to-state bridge in syncProjects cannot help. The
+27 -1
View File
@@ -19,6 +19,7 @@ export interface PersistedUiState {
collapsedProjectCwds?: string[];
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
defaultAdvertisedEndpointKey?: string | null;
threadChangedFilesExpandedById?: Record<string, Record<string, boolean>>;
}
@@ -32,7 +33,11 @@ export interface UiThreadState {
threadChangedFilesExpandedById: Record<string, Record<string, boolean>>;
}
export interface UiState extends UiProjectState, UiThreadState {}
export interface UiEndpointState {
defaultAdvertisedEndpointKey: string | null;
}
export interface UiState extends UiProjectState, UiThreadState, UiEndpointState {}
export interface SyncProjectInput {
/** Physical project key (env + cwd). Used for manual sort order. */
@@ -52,6 +57,7 @@ const initialState: UiState = {
projectOrder: [],
threadLastVisitedAtById: {},
threadChangedFilesExpandedById: {},
defaultAdvertisedEndpointKey: null,
};
const persistedCollapsedProjectCwds = new Set<string>();
@@ -88,6 +94,11 @@ function readPersistedState(): UiState {
hydratePersistedProjectState(parsed);
return {
...initialState,
defaultAdvertisedEndpointKey:
typeof parsed.defaultAdvertisedEndpointKey === "string" &&
parsed.defaultAdvertisedEndpointKey.length > 0
? parsed.defaultAdvertisedEndpointKey
: null,
threadChangedFilesExpandedById: sanitizePersistedThreadChangedFilesExpanded(
parsed.threadChangedFilesExpandedById,
),
@@ -179,6 +190,7 @@ export function persistState(state: UiState): void {
collapsedProjectCwds,
expandedProjectCwds,
projectOrderCwds,
defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey,
threadChangedFilesExpandedById,
} satisfies PersistedUiState),
);
@@ -532,6 +544,17 @@ export function setThreadChangedFilesExpanded(
};
}
export function setDefaultAdvertisedEndpointKey(state: UiState, key: string | null): UiState {
const nextKey = key && key.length > 0 ? key : null;
if (state.defaultAdvertisedEndpointKey === nextKey) {
return state;
}
return {
...state,
defaultAdvertisedEndpointKey: nextKey,
};
}
export function toggleProject(state: UiState, projectId: string): UiState {
const expanded = state.projectExpandedById[projectId] ?? true;
return {
@@ -606,6 +629,7 @@ interface UiStateStore extends UiState {
markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void;
clearThreadUi: (threadId: string) => void;
setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void;
setDefaultAdvertisedEndpointKey: (key: string | null) => void;
toggleProject: (projectId: string) => void;
setProjectExpanded: (projectId: string, expanded: boolean) => void;
reorderProjects: (
@@ -625,6 +649,8 @@ export const useUiStateStore = create<UiStateStore>((set) => ({
clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)),
setThreadChangedFilesExpanded: (threadId, turnId, expanded) =>
set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)),
setDefaultAdvertisedEndpointKey: (key) =>
set((state) => setDefaultAdvertisedEndpointKey(state, key)),
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
+3
View File
@@ -3,6 +3,9 @@
import type { DesktopBridge, LocalApi } from "@t3tools/contracts";
interface ImportMetaEnv {
readonly VITE_HTTP_URL: string;
readonly VITE_WS_URL: string;
readonly VITE_HOSTED_APP_URL: string;
readonly APP_VERSION: string;
}
+10
View File
@@ -0,0 +1,10 @@
{
"buildCommand": "turbo build --filter @t3tools/web && bun ../../scripts/apply-web-brand-assets.ts production",
"installCommand": "bun add -g turbo && bun install --filter '@t3tools/contracts' --filter '@t3tools/client-runtime' --filter '@t3tools/scripts' --filter '@t3tools/web'",
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html"
}
]
}
+10
View File
@@ -9,6 +9,15 @@ const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredHttpUrl = process.env.VITE_HTTP_URL?.trim();
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const configuredHostedAppUrl = (() => {
if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`;
}
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}`;
}
return process.env.VITE_HOSTED_APP_URL?.trim();
})();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
const buildSourcemap =
@@ -62,6 +71,7 @@ export default defineConfig({
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
"import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
"import.meta.env.APP_VERSION": JSON.stringify(pkg.version),
},
resolve: {
+41
View File
@@ -16,13 +16,17 @@
"name": "@t3tools/desktop",
"version": "0.0.21",
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
"electron": "40.6.0",
"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:",
@@ -63,6 +67,7 @@
"@effect/vitest": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
@@ -197,6 +202,38 @@
"vitest": "catalog:",
},
},
"packages/ssh": {
"name": "@t3tools/ssh",
"version": "0.0.0-alpha.1",
"dependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"packages/tailscale": {
"name": "@t3tools/tailscale",
"version": "0.0.0-alpha.1",
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"scripts": {
"name": "@t3tools/scripts",
"dependencies": {
@@ -739,6 +776,10 @@
"@t3tools/shared": ["@t3tools/shared@workspace:packages/shared"],
"@t3tools/ssh": ["@t3tools/ssh@workspace:packages/ssh"],
"@t3tools/tailscale": ["@t3tools/tailscale@workspace:packages/tailscale"],
"@t3tools/web": ["@t3tools/web@workspace:apps/web"],
"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.19.0", "jiti": "^2.6.1", "lightningcss": "1.31.1", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.2.1" } }, "sha512-jlx6sLk4EOwO6hHe1oCGm1Q4AN/s0rSrTTPBGPM0/RQ6Uylwq17FuU8IeJJKEjtc6K6O07zsvP+gDO6MMWo7pg=="],
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import {
classifyHostedHttpsCompatibility,
createAdvertisedEndpoint,
deriveWsBaseUrl,
normalizeHttpBaseUrl,
} from "./advertisedEndpoint.ts";
const coreProvider = {
id: "desktop-core",
label: "Desktop",
kind: "core",
isAddon: false,
} as const;
describe("advertised endpoint helpers", () => {
it("normalizes HTTP and WebSocket base URLs", () => {
expect(normalizeHttpBaseUrl("https://example.com/path?x=1#hash")).toBe("https://example.com/");
expect(normalizeHttpBaseUrl("wss://example.com/socket")).toBe("https://example.com/");
expect(deriveWsBaseUrl("https://example.com/api")).toBe("wss://example.com/");
expect(deriveWsBaseUrl("http://127.0.0.1:3773")).toBe("ws://127.0.0.1:3773/");
});
it("marks HTTP endpoints as blocked from hosted HTTPS apps", () => {
expect(classifyHostedHttpsCompatibility("http://192.168.1.44:3773")).toBe(
"mixed-content-blocked",
);
expect(classifyHostedHttpsCompatibility("https://desktop.example.com", "compatible")).toBe(
"compatible",
);
});
it("creates provider-neutral endpoint records", () => {
expect(
createAdvertisedEndpoint({
id: "lan:http://192.168.1.44:3773",
label: "LAN",
provider: coreProvider,
httpBaseUrl: "http://192.168.1.44:3773",
reachability: "lan",
source: "desktop-core",
isDefault: true,
}),
).toEqual({
id: "lan:http://192.168.1.44:3773",
label: "LAN",
provider: coreProvider,
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,
});
});
});
@@ -0,0 +1,78 @@
import type {
AdvertisedEndpoint,
AdvertisedEndpointHostedHttpsCompatibility,
AdvertisedEndpointProvider,
AdvertisedEndpointReachability,
AdvertisedEndpointSource,
AdvertisedEndpointStatus,
} from "@t3tools/contracts";
export interface CreateAdvertisedEndpointInput {
readonly id: string;
readonly label: string;
readonly provider: AdvertisedEndpointProvider;
readonly httpBaseUrl: string;
readonly reachability: AdvertisedEndpointReachability;
readonly hostedHttpsCompatibility?: AdvertisedEndpointHostedHttpsCompatibility;
readonly desktopCompatibility?: "compatible" | "unknown";
readonly source: AdvertisedEndpointSource;
readonly status?: AdvertisedEndpointStatus;
readonly isDefault?: boolean;
readonly description?: string;
}
export function normalizeHttpBaseUrl(rawValue: string): string {
const url = new URL(rawValue);
if (url.protocol === "ws:") {
url.protocol = "http:";
} else if (url.protocol === "wss:") {
url.protocol = "https:";
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`Endpoint must use HTTP or HTTPS. Received ${url.protocol}`);
}
url.pathname = "/";
url.search = "";
url.hash = "";
return url.toString();
}
export function deriveWsBaseUrl(httpBaseUrl: string): string {
const url = new URL(normalizeHttpBaseUrl(httpBaseUrl));
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
return url.toString();
}
export function classifyHostedHttpsCompatibility(
httpBaseUrl: string,
fallback: AdvertisedEndpointHostedHttpsCompatibility = "unknown",
): AdvertisedEndpointHostedHttpsCompatibility {
const url = new URL(normalizeHttpBaseUrl(httpBaseUrl));
if (url.protocol === "http:") {
return "mixed-content-blocked";
}
return fallback === "mixed-content-blocked" ? "unknown" : fallback;
}
export function createAdvertisedEndpoint(input: CreateAdvertisedEndpointInput): AdvertisedEndpoint {
const httpBaseUrl = normalizeHttpBaseUrl(input.httpBaseUrl);
return {
id: input.id,
label: input.label,
provider: input.provider,
httpBaseUrl,
wsBaseUrl: deriveWsBaseUrl(httpBaseUrl),
reachability: input.reachability,
compatibility: {
hostedHttpsApp:
input.hostedHttpsCompatibility ?? classifyHostedHttpsCompatibility(httpBaseUrl),
desktopApp: input.desktopCompatibility ?? "compatible",
},
source: input.source,
status: input.status ?? "available",
...(input.isDefault === undefined ? {} : { isDefault: input.isDefault }),
...(input.description === undefined ? {} : { description: input.description }),
};
}
+1
View File
@@ -1,2 +1,3 @@
export * from "./advertisedEndpoint.ts";
export * from "./knownEnvironment.ts";
export * from "./scoped.ts";
+1
View File
@@ -1,6 +1,7 @@
export * from "./baseSchemas.ts";
export * from "./auth.ts";
export * from "./environment.ts";
export * from "./remoteAccess.ts";
export * from "./ipc.ts";
export * from "./terminal.ts";
export * from "./provider.ts";
+63 -1
View File
@@ -52,8 +52,16 @@ import type {
OrchestrationThreadStreamItem,
} from "./orchestration.ts";
import type { EnvironmentId } from "./baseSchemas.ts";
import type {
AuthBearerBootstrapResult,
AuthSessionState,
AuthWebSocketTokenResult,
} from "./auth.ts";
import type { AdvertisedEndpoint } from "./remoteAccess.ts";
import { EditorId } from "./editor.ts";
import { ServerSettings, type ClientSettings, type ServerSettingsPatch } from "./settings.ts";
import type { ExecutionEnvironmentDescriptor } from "./environment.ts";
import type { ClientSettings } from "./settings.ts";
import { ServerSettings, ServerSettingsPatch } from "./settings.ts";
export interface ContextMenuItem<T extends string = string> {
id: T;
@@ -125,6 +133,34 @@ export interface DesktopEnvironmentBootstrap {
bootstrapToken?: string;
}
export interface DesktopSshEnvironmentTarget {
alias: string;
hostname: string;
username: string | null;
port: number | null;
}
export type DesktopSshHostSource = "ssh-config" | "known-hosts";
export interface DesktopDiscoveredSshHost extends DesktopSshEnvironmentTarget {
source: DesktopSshHostSource;
}
export interface DesktopSshEnvironmentBootstrap {
target: DesktopSshEnvironmentTarget;
httpBaseUrl: string;
wsBaseUrl: string;
pairingToken: string | null;
}
export interface DesktopSshPasswordPromptRequest {
requestId: string;
destination: string;
username: string | null;
prompt: string;
expiresAt: string;
}
export interface PersistedSavedEnvironmentRecord {
environmentId: EnvironmentId;
label: string;
@@ -132,6 +168,7 @@ export interface PersistedSavedEnvironmentRecord {
httpBaseUrl: string;
createdAt: string;
lastConnectedAt: string | null;
desktopSsh?: DesktopSshEnvironmentTarget;
}
export type DesktopServerExposureMode = "local-only" | "network-accessible";
@@ -140,6 +177,8 @@ export interface DesktopServerExposureState {
mode: DesktopServerExposureMode;
endpointUrl: string | null;
advertisedHost: string | null;
tailscaleServeEnabled: boolean;
tailscaleServePort: number;
}
export interface PickFolderOptions {
@@ -158,8 +197,31 @@ export interface DesktopBridge {
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
discoverSshHosts: () => Promise<readonly DesktopDiscoveredSshHost[]>;
ensureSshEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { issuePairingToken?: boolean },
) => Promise<DesktopSshEnvironmentBootstrap>;
disconnectSshEnvironment: (target: DesktopSshEnvironmentTarget) => Promise<void>;
fetchSshEnvironmentDescriptor: (httpBaseUrl: string) => Promise<ExecutionEnvironmentDescriptor>;
bootstrapSshBearerSession: (
httpBaseUrl: string,
credential: string,
) => Promise<AuthBearerBootstrapResult>;
fetchSshSessionState: (httpBaseUrl: string, bearerToken: string) => Promise<AuthSessionState>;
issueSshWebSocketToken: (
httpBaseUrl: string,
bearerToken: string,
) => Promise<AuthWebSocketTokenResult>;
onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => () => void;
resolveSshPasswordPrompt: (requestId: string, password: string | null) => Promise<void>;
getServerExposureState: () => Promise<DesktopServerExposureState>;
setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;
setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Promise<DesktopServerExposureState>;
getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;
pickFolder: (options?: PickFolderOptions) => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
setTheme: (theme: DesktopTheme) => Promise<void>;
+68
View File
@@ -0,0 +1,68 @@
import { Schema } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
export const AdvertisedEndpointProviderKind = Schema.Literals([
"core",
"private-network",
"tunnel",
"manual",
]);
export type AdvertisedEndpointProviderKind = typeof AdvertisedEndpointProviderKind.Type;
export const AdvertisedEndpointReachability = Schema.Literals([
"loopback",
"lan",
"private-network",
"public",
]);
export type AdvertisedEndpointReachability = typeof AdvertisedEndpointReachability.Type;
export const AdvertisedEndpointHostedHttpsCompatibility = Schema.Literals([
"compatible",
"mixed-content-blocked",
"requires-configuration",
"unknown",
]);
export type AdvertisedEndpointHostedHttpsCompatibility =
typeof AdvertisedEndpointHostedHttpsCompatibility.Type;
export const AdvertisedEndpointStatus = Schema.Literals(["available", "unavailable", "unknown"]);
export type AdvertisedEndpointStatus = typeof AdvertisedEndpointStatus.Type;
export const AdvertisedEndpointSource = Schema.Literals([
"desktop-core",
"desktop-addon",
"server",
"user",
]);
export type AdvertisedEndpointSource = typeof AdvertisedEndpointSource.Type;
export const AdvertisedEndpointProvider = Schema.Struct({
id: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
kind: AdvertisedEndpointProviderKind,
isAddon: Schema.Boolean,
});
export type AdvertisedEndpointProvider = typeof AdvertisedEndpointProvider.Type;
export const AdvertisedEndpointCompatibility = Schema.Struct({
hostedHttpsApp: AdvertisedEndpointHostedHttpsCompatibility,
desktopApp: Schema.Literals(["compatible", "unknown"]),
});
export type AdvertisedEndpointCompatibility = typeof AdvertisedEndpointCompatibility.Type;
export const AdvertisedEndpoint = Schema.Struct({
id: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
provider: AdvertisedEndpointProvider,
httpBaseUrl: TrimmedNonEmptyString,
wsBaseUrl: TrimmedNonEmptyString,
reachability: AdvertisedEndpointReachability,
compatibility: AdvertisedEndpointCompatibility,
source: AdvertisedEndpointSource,
status: AdvertisedEndpointStatus,
isDefault: Schema.optional(Schema.Boolean),
description: Schema.optional(TrimmedNonEmptyString),
});
export type AdvertisedEndpoint = typeof AdvertisedEndpoint.Type;
+46
View File
@@ -0,0 +1,46 @@
{
"name": "@t3tools/ssh",
"version": "0.0.0-alpha.1",
"private": true,
"type": "module",
"exports": {
"./auth": {
"types": "./src/auth.ts",
"import": "./src/auth.ts"
},
"./command": {
"types": "./src/command.ts",
"import": "./src/command.ts"
},
"./config": {
"types": "./src/config.ts",
"import": "./src/config.ts"
},
"./errors": {
"types": "./src/errors.ts",
"import": "./src/errors.ts"
},
"./tunnel": {
"types": "./src/tunnel.ts",
"import": "./src/tunnel.ts"
}
},
"scripts": {
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+65
View File
@@ -0,0 +1,65 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { Effect, FileSystem, Path } from "effect";
import {
buildSshAskpassHelperDescriptor,
buildSshChildEnvironment,
isSshAuthFailure,
} from "./auth.ts";
describe("ssh auth", () => {
it.effect("detects ssh auth failures from common permission denied messages", () =>
Effect.sync(() => {
assert.equal(
isSshAuthFailure(
new Error(
"[email protected]: Permission denied (publickey,password,keyboard-interactive).",
),
),
true,
);
assert.equal(isSshAuthFailure(new Error("Permission denied (publickey).")), true);
assert.equal(isSshAuthFailure(new Error("Connection timed out")), false);
assert.equal(isSshAuthFailure(new Error("mkdir: Permission denied")), false);
}),
);
it.effect("creates askpass env for cached password prompts", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-askpass-test-" });
const env = yield* buildSshChildEnvironment({
authSecret: "super-secret",
interactiveAuth: true,
askpassDirectory: directory,
platform: "linux",
baseEnv: {},
});
const askpassPath = path.join(directory, "ssh-askpass.sh");
assert.equal(env.SSH_ASKPASS, askpassPath);
assert.equal(env.SSH_ASKPASS_REQUIRE, "force");
assert.equal(env.T3_SSH_AUTH_SECRET, "super-secret");
assert.equal(env.DISPLAY, "t3code");
assert.equal(yield* fs.exists(askpassPath), true);
assert.include(yield* fs.readFileString(askpassPath), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("builds a windows askpass launcher pair", () =>
Effect.gen(function* () {
const descriptor = yield* buildSshAskpassHelperDescriptor({
directory: "C:\\temp\\t3code-ssh-askpass",
platform: "win32",
}).pipe(Effect.provide(NodeServices.layer));
assert.equal(descriptor.launcherPath, "C:\\temp\\t3code-ssh-askpass\\ssh-askpass.cmd");
assert.deepEqual(
descriptor.files.map((file) => file.path.split("\\").at(-1)),
["ssh-askpass.cmd", "ssh-askpass.ps1"],
);
}),
);
});
+205
View File
@@ -0,0 +1,205 @@
import { Context, Effect, FileSystem, Layer, Path, PlatformError } from "effect";
import { SshPasswordPromptError } from "./errors.ts";
export interface SshPasswordRequest {
readonly destination: string;
readonly username: string | null;
readonly prompt: string;
readonly attempt: number;
}
export interface SshAskpassFile {
readonly path: string;
readonly contents: string;
readonly mode?: number;
}
export interface SshAskpassHelperDescriptor {
readonly launcherPath: string;
readonly files: ReadonlyArray<SshAskpassFile>;
}
export interface SshAuthOptions {
readonly authSecret?: string | null;
readonly batchMode?: "yes" | "no";
readonly interactiveAuth?: boolean;
}
export interface SshPasswordPromptShape {
readonly isAvailable: boolean;
readonly request: (
request: SshPasswordRequest,
) => Effect.Effect<string | null, SshPasswordPromptError>;
}
export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPasswordPromptShape>()(
"@t3tools/ssh/SshPasswordPrompt",
) {
static readonly disabledLayer = Layer.succeed(
SshPasswordPrompt,
SshPasswordPrompt.of({
isAvailable: false,
request: () => Effect.succeed(null),
}),
);
}
export interface SshChildEnvironmentOptions {
readonly interactiveAuth?: boolean;
readonly baseEnv?: NodeJS.ProcessEnv;
readonly askpassDirectory?: string;
readonly authSecret?: string | null;
readonly platform?: NodeJS.Platform;
}
const SSH_ASKPASS_DIR_NAME = "t3code-ssh-askpass";
function joinSshAskpassPath(
directory: string,
fileName: string,
platform: NodeJS.Platform,
): string {
const trimmed = directory.replace(/[\\/]+$/u, "");
return platform === "win32" ? `${trimmed}\\${fileName}` : `${trimmed}/${fileName}`;
}
export const ASKPASS_POSIX_SCRIPT = `#!/bin/sh
# Invoked by ssh via SSH_ASKPASS when T3 Code re-runs ssh with a cached password
# from the renderer's in-app prompt. We never expose a native dialog here - if
# T3_SSH_AUTH_SECRET is missing, that's a caller bug and we fail loudly.
if [ "\${T3_SSH_AUTH_SECRET+x}" = "x" ]; then
printf "%s\\n" "$T3_SSH_AUTH_SECRET"
exit 0
fi
printf 'T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.\\n' >&2
exit 1
`;
export const ASKPASS_WINDOWS_LAUNCHER_SCRIPT = `@echo off\r
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*\r
`;
export const ASKPASS_WINDOWS_SCRIPT = `# Invoked by ssh via SSH_ASKPASS (through ssh-askpass.cmd) when T3 Code re-runs\r
# ssh with a cached password from the renderer's in-app prompt. We never expose\r
# a native dialog here - if T3_SSH_AUTH_SECRET is missing, that's a caller bug\r
# and we fail loudly.\r
if ($null -ne $env:T3_SSH_AUTH_SECRET) {\r
[Console]::Out.WriteLine($env:T3_SSH_AUTH_SECRET)\r
exit 0\r
}\r
[Console]::Error.WriteLine("T3 Code ssh-askpass invoked without T3_SSH_AUTH_SECRET.")\r
exit 1\r
`;
export const getDefaultSshAskpassDirectory = Effect.fn("ssh/auth.getDefaultSshAskpassDirectory")(
function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parentDirectory = yield* fs.makeTempDirectory({ prefix: "t3code-ssh-runtime-" });
return path.join(parentDirectory, SSH_ASKPASS_DIR_NAME);
},
);
export const buildSshAskpassHelperDescriptor = Effect.fn(
"ssh/auth.buildSshAskpassHelperDescriptor",
)(function* (input: {
readonly directory: string;
readonly platform?: NodeJS.Platform;
}): Effect.fn.Return<SshAskpassHelperDescriptor, never, Path.Path> {
const platform = input.platform ?? process.platform;
const path = yield* Path.Path;
const directory = input.directory;
if (platform === "win32") {
const powershellPath = joinSshAskpassPath(directory, "ssh-askpass.ps1", platform);
return {
launcherPath: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
files: [
{
path: joinSshAskpassPath(directory, "ssh-askpass.cmd", platform),
contents: ASKPASS_WINDOWS_LAUNCHER_SCRIPT,
},
{
path: powershellPath,
contents: ASKPASS_WINDOWS_SCRIPT,
},
],
};
}
return {
launcherPath: path.join(directory, "ssh-askpass.sh"),
files: [
{
path: path.join(directory, "ssh-askpass.sh"),
contents: ASKPASS_POSIX_SCRIPT,
mode: 0o700,
},
],
};
});
export const ensureSshAskpassHelpers = Effect.fn("ssh/auth.ensureSshAskpassHelpers")(
function* (input: {
readonly directory: string;
readonly platform?: NodeJS.Platform;
}): Effect.fn.Return<string, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const descriptor = yield* buildSshAskpassHelperDescriptor(input);
const platform = input.platform ?? process.platform;
yield* fs.makeDirectory(path.dirname(descriptor.launcherPath), { recursive: true });
for (const file of descriptor.files) {
const existing = yield* fs.exists(file.path);
const current = existing ? yield* fs.readFileString(file.path) : null;
if (current !== file.contents) {
yield* fs.writeFileString(file.path, file.contents);
}
if (file.mode !== undefined && platform !== "win32") {
yield* fs.chmod(file.path, file.mode);
}
}
return descriptor.launcherPath;
},
);
export const buildSshChildEnvironment = Effect.fn("ssh/auth.buildSshChildEnvironment")(function* (
input: SshChildEnvironmentOptions = {},
): Effect.fn.Return<
NodeJS.ProcessEnv,
PlatformError.PlatformError,
FileSystem.FileSystem | Path.Path
> {
const baseEnv = { ...(input.baseEnv ?? process.env) };
if (!input.interactiveAuth) {
return baseEnv;
}
const platform = input.platform ?? process.platform;
const directory = input.askpassDirectory ?? (yield* getDefaultSshAskpassDirectory());
const sshAskpass = yield* ensureSshAskpassHelpers({ directory, platform });
return {
...baseEnv,
SSH_ASKPASS: sshAskpass,
SSH_ASKPASS_REQUIRE: "force",
...(input.authSecret === undefined ? {} : { T3_SSH_AUTH_SECRET: input.authSecret ?? "" }),
...(platform === "win32" || baseEnv.DISPLAY ? {} : { DISPLAY: "t3code" }),
};
});
export function isSshAuthFailure(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
const normalized = message.toLowerCase();
return (
/permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]*\)/u.test(
normalized,
) ||
/authentication failed/u.test(normalized) ||
/too many authentication failures/u.test(normalized)
);
}
+151
View File
@@ -0,0 +1,151 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Duration, Effect, Fiber, Layer, Result, Sink, Stream } from "effect";
import { TestClock } from "effect/testing";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
baseSshArgs,
getLastNonEmptyOutputLine,
parseSshResolveOutput,
resolveRemoteT3CliPackageSpec,
runSshCommand,
} from "./command.ts";
const makeNeverFinishingProcess = () => {
let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
finish = (exitCode) => resume(Effect.succeed(exitCode));
return Effect.sync(() => {
finish = null;
});
}),
isRunning: Effect.succeed(true),
kill: () =>
Effect.sync(() => {
finish?.(ChildProcessSpawner.ExitCode(143));
}),
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
};
describe("ssh command", () => {
it.effect("parses resolved ssh config output into a target", () =>
Effect.sync(() => {
assert.deepEqual(
parseSshResolveOutput(
"devbox",
["hostname devbox.example.com", "user julius", "port 2222", ""].join("\n"),
),
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
);
}),
);
it.effect("builds interactive ssh args without forcing batch mode", () =>
Effect.sync(() => {
assert.deepEqual(
baseSshArgs(
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ batchMode: "no" },
),
["-o", "BatchMode=no", "-o", "ConnectTimeout=10", "-p", "2222"],
);
}),
);
it.effect("resolves the remote t3 package spec from the desktop release channel", () =>
Effect.sync(() => {
assert.equal(
resolveRemoteT3CliPackageSpec({
appVersion: "0.0.17",
updateChannel: "latest",
}),
"[email protected]",
);
assert.equal(
resolveRemoteT3CliPackageSpec({
appVersion: "0.0.17-nightly.20260415.44",
updateChannel: "nightly",
}),
"[email protected]",
);
assert.equal(
resolveRemoteT3CliPackageSpec({
appVersion: "0.0.0-dev",
updateChannel: "nightly",
isDevelopment: true,
}),
"t3@nightly",
);
assert.equal(
resolveRemoteT3CliPackageSpec({
appVersion: "0.0.0-dev",
updateChannel: "latest",
isDevelopment: true,
}),
"t3@nightly",
);
}),
);
it.effect("reads the last non-empty ssh output line", () =>
Effect.sync(() => {
assert.equal(
getLastNonEmptyOutputLine(
["Welcome to the host", "", '{"credential":"pairing-token"}', ""].join("\n"),
),
'{"credential":"pairing-token"}',
);
}),
);
it.effect("fails commands that never finish", () => {
const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeNeverFinishingProcess()));
const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
return Effect.gen(function* () {
const fiber = yield* Effect.forkChild(
Effect.result(
runSshCommand(
{
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
},
{ timeoutMs: 1 },
),
),
);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(1));
const result = yield* Fiber.join(fiber);
assert.isTrue(Result.isFailure(result));
if (Result.isFailure(result)) {
assert.include(result.failure.message, "SSH command timed out after 1ms.");
}
}).pipe(Effect.provide(processLayer));
});
});
+337
View File
@@ -0,0 +1,337 @@
import * as Crypto from "node:crypto";
import type { DesktopSshEnvironmentTarget, DesktopUpdateChannel } from "@t3tools/contracts";
import { Duration, Effect, FileSystem, Option, Path, Scope, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
const encoder = new TextEncoder();
export interface SshCommandResult {
readonly stdout: string;
readonly stderr: string;
}
export interface RunSshCommandOptions extends SshAuthOptions {
readonly preHostArgs?: ReadonlyArray<string>;
readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string;
readonly timeoutMs?: number;
}
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
const values = new Map<string, string>();
for (const line of stdout.split(/\r?\n/u)) {
const trimmed = line.trim();
if (trimmed.length === 0) {
continue;
}
const [key, ...rest] = trimmed.split(/\s+/u);
if (!key || rest.length === 0 || values.has(key)) {
continue;
}
values.set(key, rest.join(" ").trim());
}
const hostname = values.get("hostname")?.trim() || alias;
const username = values.get("user")?.trim() || null;
const rawPort = values.get("port")?.trim() ?? "";
const parsedPort = Number.parseInt(rawPort, 10);
return {
alias,
hostname,
username,
port: Number.isInteger(parsedPort) ? parsedPort : null,
};
}
export function targetConnectionKey(target: DesktopSshEnvironmentTarget): string {
return `${target.alias}\u0000${target.hostname}\u0000${target.username ?? ""}\u0000${target.port ?? ""}`;
}
export function remoteStateKey(target: DesktopSshEnvironmentTarget): string {
return Crypto.createHash("sha256").update(targetConnectionKey(target)).digest("hex").slice(0, 16);
}
export function buildSshHostSpec(target: DesktopSshEnvironmentTarget): string {
const destination = target.alias.trim() || target.hostname.trim();
if (destination.length === 0) {
throw new Error("SSH target is missing its alias/hostname.");
}
return target.username ? `${target.username}@${destination}` : destination;
}
export const buildSshHostSpecEffect = (
target: DesktopSshEnvironmentTarget,
): Effect.Effect<string, SshInvalidTargetError> =>
Effect.try({
try: () => buildSshHostSpec(target),
catch: (cause) =>
new SshInvalidTargetError({
message: cause instanceof Error ? cause.message : "SSH target is invalid.",
}),
});
export function baseSshArgs(
target: DesktopSshEnvironmentTarget,
input?: { readonly batchMode?: "yes" | "no" },
): string[] {
return [
"-o",
`BatchMode=${input?.batchMode ?? "no"}`,
"-o",
"ConnectTimeout=10",
...(target.port !== null ? ["-p", String(target.port)] : []),
];
}
export function getLastNonEmptyOutputLine(stdout: string): string | null {
return (
stdout
.trim()
.split(/\r?\n/u)
.map((entry) => entry.trim())
.findLast((entry) => entry.length > 0) ?? null
);
}
export const collectProcessOutput = <E>(
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {
const cleaned = stderr.trim();
return cleaned.length > 0 ? cleaned : fallbackMessage;
}
function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
return {
alias: target.alias,
hostname: target.hostname,
username: target.username,
port: target.port,
};
}
function stdinStream(input: string | undefined) {
return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
}
const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
target: DesktopSshEnvironmentTarget,
input: RunSshCommandOptions,
commandScope: Scope.Scope,
): Effect.fn.Return<
SshCommandResult,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const hostSpec = yield* buildSshHostSpecEffect(target);
const environment = yield* buildSshChildEnvironment({
...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
}).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: "Failed to prepare SSH authentication helpers.",
cause,
}),
),
);
const args = [
...baseSshArgs(target, {
batchMode: input.batchMode ?? (input.interactiveAuth ? "no" : "yes"),
}),
...(input.preHostArgs ?? []),
hostSpec,
...(input.remoteCommandArgs ?? []),
];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
yield* Effect.logDebug("ssh.command.start", {
...sshTargetLogFields(target),
command: ["ssh", ...args],
hasStdin: input.stdin !== undefined,
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
});
const child = yield* spawner
.spawn(
ChildProcess.make("ssh", args, {
env: environment,
shell: process.platform === "win32",
stdin: {
stream: stdinStream(input.stdin),
endOnDone: true,
},
}),
)
.pipe(
Effect.provideService(Scope.Scope, commandScope),
Effect.mapError(
(cause) =>
new SshCommandError({
command: ["ssh", ...args],
exitCode: null,
stderr: "",
message:
cause instanceof Error
? cause.message
: `Failed to spawn SSH command for ${hostSpec}.`,
cause,
}),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectProcessOutput(child.stdout),
collectProcessOutput(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
command: ["ssh", ...args],
exitCode: null,
stderr: "",
message:
cause instanceof Error ? cause.message : `Failed to run SSH command for ${hostSpec}.`,
cause,
}),
),
);
if (exitCode !== 0) {
yield* Effect.logWarning("ssh.command.failed", {
...sshTargetLogFields(target),
command: ["ssh", ...args],
exitCode,
stderr,
});
return yield* new SshCommandError({
command: ["ssh", ...args],
exitCode,
stderr,
message: normalizeSshErrorMessage(
stderr,
`SSH command failed for ${hostSpec} (exit ${exitCode}).`,
),
});
}
yield* Effect.logDebug("ssh.command.succeeded", {
...sshTargetLogFields(target),
command: ["ssh", ...args],
});
return { stdout, stderr };
});
export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
target: DesktopSshEnvironmentTarget,
input: RunSshCommandOptions = {},
): Effect.fn.Return<
SshCommandResult,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
return yield* Effect.scopedWith((commandScope) =>
runSshCommandInScope(target, input, commandScope),
).pipe(
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onSome: Effect.succeed,
onNone: () =>
Effect.gen(function* () {
yield* Effect.logWarning("ssh.command.timedOut", {
...sshTargetLogFields(target),
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
remoteCommandArgs: input.remoteCommandArgs ?? [],
preHostArgs: input.preHostArgs ?? [],
hasStdin: input.stdin !== undefined,
});
return yield* new SshCommandError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
});
}),
}),
),
);
});
export const resolveSshTarget = Effect.fn("ssh/command.resolveSshTarget")(function* (
alias: string,
): Effect.fn.Return<
DesktopSshEnvironmentTarget,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const trimmedAlias = alias.trim();
if (trimmedAlias.length === 0) {
return yield* new SshInvalidTargetError({ message: "SSH host alias is required." });
}
yield* Effect.logDebug("ssh.target.resolve.start", { alias: trimmedAlias });
return yield* runSshCommand(
{
alias: trimmedAlias,
hostname: trimmedAlias,
username: null,
port: null,
},
{ preHostArgs: ["-G"] },
).pipe(
Effect.map((result) => parseSshResolveOutput(trimmedAlias, result.stdout)),
Effect.tap((target) =>
Effect.logDebug("ssh.target.resolve.succeeded", sshTargetLogFields(target)),
),
Effect.catch((cause) =>
Effect.logDebug("ssh.target.resolve.fallback", { alias: trimmedAlias, cause }).pipe(
Effect.as({
alias: trimmedAlias,
hostname: trimmedAlias,
username: null,
port: null,
}),
),
),
);
});
export function resolveRemoteT3CliPackageSpec(input: {
readonly appVersion: string;
readonly updateChannel: DesktopUpdateChannel;
readonly isDevelopment?: boolean;
}): string {
const appVersion = input.appVersion.trim();
if (!input.isDevelopment && PUBLISHABLE_T3_VERSION_PATTERN.test(appVersion)) {
return `t3@${appVersion}`;
}
if (input.isDevelopment) {
return "t3@nightly";
}
return input.updateChannel === "nightly" ? "t3@nightly" : "t3@latest";
}
+123
View File
@@ -0,0 +1,123 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { Effect, FileSystem, Path } from "effect";
import {
discoverSshHosts,
parseKnownHostsHostnames,
resolveSshConfigIncludePattern,
} from "./config.ts";
function makeTempHomeDir() {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-test-" });
});
}
describe("ssh config", () => {
it.effect("discovers ssh config hosts across included files", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const homeDir = yield* makeTempHomeDir();
const sshDir = path.join(homeDir, ".ssh");
yield* fs.makeDirectory(path.join(sshDir, "config.d"), { recursive: true });
yield* fs.writeFileString(
path.join(sshDir, "config"),
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
);
yield* fs.writeFileString(
path.join(sshDir, "config.d", "team.conf"),
[
"Host staging",
" HostName staging.example.com",
"Host *",
" ServerAliveInterval 30",
"",
].join("\n"),
);
yield* fs.writeFileString(
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"),
);
const hosts = yield* discoverSshHosts({ homeDir });
assert.deepEqual(hosts, [
{
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",
},
]);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("parses known_hosts entries without returning hashed hosts", () =>
Effect.sync(() => {
assert.deepEqual(
parseKnownHostsHostnames(
[
"github.com ssh-ed25519 AAAA",
"gitlab.com,gitlab-alias ssh-ed25519 BBBB",
"|1|hashed|entry ssh-ed25519 CCCC",
"@cert-authority *.example.com ssh-ed25519 DDDD",
"[ssh.example.com]:2200 ssh-ed25519 EEEE",
"port.example.com:22 ssh-ed25519 HHHH",
"::1 ssh-ed25519 FFFF",
"2001:db8::1 ssh-ed25519 GGGG",
"",
].join("\n"),
),
[
"::1",
"2001:db8::1",
"github.com",
"gitlab-alias",
"gitlab.com",
"port.example.com",
"ssh.example.com",
],
);
}),
);
it.effect("expands tilde-prefixed ssh config include patterns", () =>
Effect.gen(function* () {
const pattern = yield* resolveSshConfigIncludePattern(
"~/.ssh/config.d/*.conf",
"/tmp/project",
"/tmp/home",
);
assert.equal(pattern, "/tmp/home/.ssh/config.d/*.conf");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
+250
View File
@@ -0,0 +1,250 @@
import type { DesktopDiscoveredSshHost } from "@t3tools/contracts";
import { Effect, FileSystem, Path, PlatformError } from "effect";
import { SshHostDiscoveryError } from "./errors.ts";
const NO_HOSTS: ReadonlyArray<string> = [] as const;
function stripInlineComment(line: string): string {
const hashIndex = line.indexOf("#");
return (hashIndex >= 0 ? line.slice(0, hashIndex) : line).trim();
}
function splitDirectiveArgs(value: string): ReadonlyArray<string> {
return value
.trim()
.split(/\s+/u)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
}
function expandHomePath(input: string, homeDir: string): string {
return input.replace(/^~(?=$|\/|\\)/u, homeDir);
}
export const resolveSshConfigIncludePattern = Effect.fnUntraced(function* (
includePattern: string,
_directory: string,
homeDir: string,
) {
const path = yield* Path.Path;
const expandedPattern = expandHomePath(includePattern, homeDir);
return path.isAbsolute(expandedPattern)
? expandedPattern
: path.resolve(path.join(homeDir, ".ssh"), expandedPattern);
});
function hasSshPattern(value: string): boolean {
return value.includes("*") || value.includes("?") || value.startsWith("!");
}
function escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
}
function globToRegExp(pattern: string): RegExp {
return new RegExp(
`^${escapeRegex(pattern).replace(/\\\*/gu, ".*").replace(/\\\?/gu, ".")}$`,
"u",
);
}
const expandGlob = Effect.fnUntraced(function* (pattern: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (!pattern.includes("*") && !pattern.includes("?")) {
return (yield* fs.exists(pattern)) ? [pattern] : NO_HOSTS;
}
const directory = path.dirname(pattern);
const basePattern = path.basename(pattern);
if (!(yield* fs.exists(directory))) {
return NO_HOSTS;
}
const matcher = globToRegExp(basePattern);
const entries = yield* fs.readDirectory(directory);
const matchedPaths: string[] = [];
for (const entry of entries) {
if (!matcher.test(entry)) {
continue;
}
const entryPath = path.join(directory, entry);
if (yield* fs.exists(entryPath)) {
matchedPaths.push(entryPath);
}
}
return matchedPaths.toSorted((left, right) => left.localeCompare(right));
});
export const collectSshConfigAliasesFromFile = Effect.fnUntraced(function* (
filePath: string,
visited = new Set<string>(),
homeDir: string,
): Effect.fn.Return<
ReadonlyArray<string>,
PlatformError.PlatformError,
FileSystem.FileSystem | Path.Path
> {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const resolvedPath = path.resolve(filePath);
if (visited.has(resolvedPath) || !(yield* fs.exists(resolvedPath))) {
return NO_HOSTS;
}
visited.add(resolvedPath);
const aliases = new Set<string>();
const directory = path.dirname(resolvedPath);
const raw = yield* fs.readFileString(resolvedPath);
for (const line of raw.split(/\r?\n/u)) {
const stripped = stripInlineComment(line);
if (stripped.length === 0) {
continue;
}
const [directive = "", ...rawArgs] = splitDirectiveArgs(stripped);
const normalizedDirective = directive.toLowerCase();
if (normalizedDirective === "include") {
for (const includePattern of rawArgs) {
const resolvedPattern = yield* resolveSshConfigIncludePattern(
includePattern,
directory,
homeDir,
);
const includedPaths = yield* expandGlob(resolvedPattern);
for (const includedPath of includedPaths) {
const includedAliases = yield* collectSshConfigAliasesFromFile(
includedPath,
visited,
homeDir,
);
for (const alias of includedAliases) {
aliases.add(alias);
}
}
}
continue;
}
if (normalizedDirective !== "host") {
continue;
}
for (const alias of rawArgs) {
if (alias.length === 0 || hasSshPattern(alias)) {
continue;
}
aliases.add(alias);
}
}
return [...aliases].toSorted((left, right) => left.localeCompare(right));
});
function normalizeKnownHostsHostname(rawHost: string): string {
const bracketMatch = /^\[([^\]]+)\]:(\d+)$/u.exec(rawHost);
if (bracketMatch?.[1]) {
return bracketMatch[1];
}
if (!rawHost.includes(":")) {
return rawHost;
}
const firstColonIndex = rawHost.indexOf(":");
const lastColonIndex = rawHost.lastIndexOf(":");
return firstColonIndex === lastColonIndex ? rawHost.slice(0, lastColonIndex) : rawHost;
}
export function parseKnownHostsHostnames(raw: string): ReadonlyArray<string> {
const hostnames = new Set<string>();
for (const line of raw.split(/\r?\n/u)) {
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith("#")) {
continue;
}
const withoutMarker = trimmed.startsWith("@")
? trimmed.split(/\s+/u).slice(1).join(" ")
: trimmed;
const [hostField = ""] = withoutMarker.split(/\s+/u);
if (hostField.length === 0 || hostField.startsWith("|")) {
continue;
}
for (const rawHost of hostField.split(",")) {
const host = normalizeKnownHostsHostname(rawHost).trim();
if (host.length === 0 || hasSshPattern(host)) {
continue;
}
hostnames.add(host);
}
}
return [...hostnames].toSorted((left, right) => left.localeCompare(right));
}
const readKnownHostsHostnames = Effect.fnUntraced(function* (filePath: string) {
const fs = yield* FileSystem.FileSystem;
if (!(yield* fs.exists(filePath))) {
return NO_HOSTS;
}
return parseKnownHostsHostnames(yield* fs.readFileString(filePath));
});
export const discoverSshHosts = Effect.fnUntraced(
function* (input: { readonly homeDir?: string }) {
const path = yield* Path.Path;
const homeDir = input?.homeDir ?? process.env.HOME ?? process.env.USERPROFILE ?? "";
if (homeDir.trim().length === 0) {
return [];
}
const sshDirectory = path.join(homeDir, ".ssh");
const configAliases = yield* collectSshConfigAliasesFromFile(
path.join(sshDirectory, "config"),
new Set<string>(),
homeDir,
);
const knownHosts = yield* readKnownHostsHostnames(path.join(sshDirectory, "known_hosts"));
const discovered = new Map<string, DesktopDiscoveredSshHost>();
for (const alias of configAliases) {
discovered.set(alias, {
alias,
hostname: alias,
username: null,
port: null,
source: "ssh-config",
});
}
for (const hostname of knownHosts) {
if (discovered.has(hostname)) {
continue;
}
discovered.set(hostname, {
alias: hostname,
hostname,
username: null,
port: null,
source: "known-hosts",
});
}
return [...discovered.values()].toSorted((left, right) =>
left.alias.localeCompare(right.alias),
);
},
Effect.mapError(
(cause) =>
new SshHostDiscoveryError({
message: "Failed to discover SSH hosts.",
cause,
}),
),
);
+46
View File
@@ -0,0 +1,46 @@
import { Data } from "effect";
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
readonly message: string;
readonly cause: unknown;
}> {}
export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
readonly message: string;
}> {}
export class SshCommandError extends Data.TaggedError("SshCommandError")<{
readonly message: string;
readonly command: readonly string[];
readonly exitCode: number | null;
readonly stderr: string;
readonly cause?: unknown;
}> {}
export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
readonly message: string;
readonly stdout: string;
readonly cause?: unknown;
}> {}
export class SshPairingError extends Data.TaggedError("SshPairingError")<{
readonly message: string;
readonly stdout: string;
readonly cause?: unknown;
}> {}
export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
readonly message: string;
readonly status?: number;
readonly cause?: unknown;
}> {}
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
+210
View File
@@ -0,0 +1,210 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { Effect, Layer, Sink, Stream } from "effect";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { SshPasswordPrompt } from "./auth.ts";
import {
buildRemoteLaunchScript,
buildRemotePairingScript,
buildRemoteStopScript,
buildRemoteT3RunnerScript,
issueRemotePairingToken,
REMOTE_PICK_PORT_SCRIPT,
SshEnvironmentManager,
} from "./tunnel.ts";
const makeSuccessfulProcess = (stdout: string) => {
const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: stdoutStream,
stderr: Stream.empty,
all: stdoutStream,
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
};
const makeRunningProcess = (onKill: () => void) => {
let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
finish = (exitCode) => resume(Effect.succeed(exitCode));
return Effect.sync(() => {
finish = null;
});
}),
isRunning: Effect.succeed(true),
kill: () =>
Effect.sync(() => {
onKill();
finish?.(ChildProcessSpawner.ExitCode(143));
}),
stdin: Sink.drain,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.succeed(Effect.void),
});
};
const testHttpClient = HttpClient.make((request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
);
const testNetService = NetService.of({
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(41_773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
});
function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
return command._tag === "StandardCommand" ? command.args : [];
}
describe("ssh tunnel scripts", () => {
it("builds the remote t3 runner with npx and npm fallbacks", () => {
const script = buildRemoteT3RunnerScript();
assert.include(script, "T3_NODE_SCRIPT_PATH=''");
assert.include(script, 'exec t3 "$@"');
assert.include(script, 'exec npx --yes t3@latest "$@"');
assert.include(script, 'exec npm exec --yes t3@latest -- "$@"');
assert.include(script, "could not install t3@latest");
});
it("builds the remote t3 runner with a node script override", () => {
const script = buildRemoteT3RunnerScript({
nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
});
assert.include(
script,
"T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
);
assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
});
it("uses the remote t3 runner for launch and pairing scripts", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
assert.include(
buildRemoteLaunchScript(),
'[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
);
assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
assert.include(
buildRemotePairingScript(target),
'"$RUNNER_FILE" auth pairing create --base-dir "$SERVER_HOME" --json',
);
assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE"');
});
it("allows the remote port picker to run without a state file path", () => {
assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
});
it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
const spawner = ChildProcessSpawner.make(() =>
Effect.succeed(
makeSuccessfulProcess(`{
"id": "88941235-6ed5-4184-a2ff-5339e2075958",
"credential": "LCL4R2TPHDKQ",
"role": "client",
"expiresAt": "2026-04-29T01:01:20.994Z"
}
`),
),
);
const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
return Effect.gen(function* () {
const credential = yield* issueRemotePairingToken(target);
assert.equal(credential, "LCL4R2TPHDKQ");
}).pipe(Effect.provide(processLayer));
});
it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
const spawnedCommands: Array<ReadonlyArray<string>> = [];
let tunnelKillCount = 0;
let stopCommandCount = 0;
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
const args = commandArgs(command);
spawnedCommands.push(args);
if (args.includes("-N")) {
return makeRunningProcess(() => {
tunnelKillCount += 1;
});
}
if (args.includes("sh") && args.includes("--")) {
return makeSuccessfulProcess('{"remotePort":3773}\n');
}
if (args.includes("sh")) {
stopCommandCount += 1;
return makeSuccessfulProcess('{"stopped":true}\n');
}
return makeSuccessfulProcess("\n");
}),
);
const layer = Layer.mergeAll(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, testHttpClient),
Layer.succeed(NetService, testNetService),
SshPasswordPrompt.disabledLayer,
SshEnvironmentManager.layer(),
);
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
return Effect.gen(function* () {
const manager = yield* SshEnvironmentManager;
const first = yield* manager.ensureEnvironment(target);
assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
yield* manager.disconnectEnvironment(target);
assert.equal(tunnelKillCount, 1);
assert.equal(stopCommandCount, 1);
yield* manager.ensureEnvironment(target);
assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
assert.equal(tunnelKillCount, 1);
}).pipe(Effect.provide(layer), Effect.scoped);
});
});
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"plugins": [
{
"name": "@effect/language-service",
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
}
]
},
"include": ["src"]
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@t3tools/tailscale",
"version": "0.0.0-alpha.1",
"private": true,
"type": "module",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
}
},
"scripts": {
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+1
View File
@@ -0,0 +1 @@
export * from "./tailscale.ts";
+131
View File
@@ -0,0 +1,131 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Layer, Sink, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
buildTailscaleHttpsBaseUrl,
disableTailscaleServe,
ensureTailscaleServe,
isTailscaleIpv4Address,
parseTailscaleMagicDnsName,
parseTailscaleStatus,
readTailscaleStatus,
} from "./tailscale.ts";
const encoder = new TextEncoder();
const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`;
const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`;
function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function mockSpawnerLayer(
handler: (
command: string,
args: ReadonlyArray<string>,
) => { stdout?: string; stderr?: string; code?: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
}),
);
}
describe("tailscale", () => {
it.effect("detects Tailnet IPv4 addresses", () =>
Effect.sync(() => {
assert.equal(isTailscaleIpv4Address("100.64.0.1"), true);
assert.equal(isTailscaleIpv4Address("100.127.255.254"), true);
assert.equal(isTailscaleIpv4Address("100.128.0.1"), false);
assert.equal(isTailscaleIpv4Address("192.168.1.44"), false);
}),
);
it.effect("parses MagicDNS names from tailscale status", () =>
Effect.gen(function* () {
const dnsName = yield* parseTailscaleMagicDnsName(tailscaleStatusJson);
assert.equal(dnsName, "desktop.tail.ts.net");
assert.equal(yield* parseTailscaleMagicDnsName("{}"), null);
}),
);
it.effect("parses status facts", () =>
Effect.gen(function* () {
const status = yield* parseTailscaleStatus(tailscaleStatusJson);
assert.deepEqual(status, {
magicDnsName: "desktop.tail.ts.net",
tailnetIpv4Addresses: ["100.100.100.100"],
});
}),
);
it.effect("builds clean HTTPS base URLs", () =>
Effect.sync(() => {
assert.equal(
buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net" }),
"https://desktop.tail.ts.net/",
);
assert.equal(
buildTailscaleHttpsBaseUrl({ magicDnsName: "desktop.tail.ts.net", servePort: 8443 }),
"https://desktop.tail.ts.net:8443/",
);
}),
);
it.effect("reads tailscale status through the process spawner service", () => {
const layer = mockSpawnerLayer((command, args) => {
assert.equal(command, "tailscale");
assert.deepEqual(args, ["status", "--json"]);
return {
stdout: tailscaleStatusWithSingleIpJson,
};
});
return Effect.gen(function* () {
const status = yield* readTailscaleStatus.pipe(Effect.provide(layer));
assert.deepEqual(status, {
magicDnsName: "desktop.tail.ts.net",
tailnetIpv4Addresses: ["100.90.1.2"],
});
});
});
it.effect("configures tailscale serve through the process spawner service", () => {
const layer = mockSpawnerLayer((command, args) => {
assert.equal(command, "tailscale");
assert.deepEqual(args, ["serve", "--bg", "--https=8443", "http://127.0.0.1:13773"]);
return {};
});
return ensureTailscaleServe({ localPort: 13773, servePort: 8443 }).pipe(Effect.provide(layer));
});
it.effect("disables tailscale serve through the process spawner service", () => {
const layer = mockSpawnerLayer((command, args) => {
assert.equal(command, "tailscale");
assert.deepEqual(args, ["serve", "off"]);
return {};
});
return disableTailscaleServe.pipe(Effect.provide(layer));
});
});
+316
View File
@@ -0,0 +1,316 @@
import { Data, Effect, Option, Schema, Stream } from "effect";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
export const TAILSCALE_STATUS_TIMEOUT_MS = 1_500;
export const TAILSCALE_SERVE_TIMEOUT_MS = 10_000;
export const TAILSCALE_PROBE_TIMEOUT_MS = 2_500;
export class TailscaleCommandError extends Data.TaggedError("TailscaleCommandError")<{
readonly command: readonly string[];
readonly message: string;
readonly exitCode: number | null;
readonly stderr: string;
}> {}
export class TailscaleStatusParseError extends Data.TaggedError("TailscaleStatusParseError")<{
readonly cause: unknown;
}> {}
export class TailscaleUnavailableError extends Data.TaggedError("TailscaleUnavailableError")<{
readonly reason: string;
}> {}
const TailscaleStatusSelf = Schema.Struct({
DNSName: Schema.optional(Schema.Unknown),
TailscaleIPs: Schema.optional(Schema.Unknown),
});
const TailscaleStatusJson = Schema.Struct({
Self: Schema.optional(TailscaleStatusSelf),
});
export type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;
export type TailscaleStatusJson = typeof TailscaleStatusJson.Type;
export interface TailscaleStatus {
readonly magicDnsName: string | null;
readonly tailnetIpv4Addresses: readonly string[];
}
const collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
const collectStderr = collectStdout;
const tailscaleCommandError = (
args: readonly string[],
message: string,
exitCode: number | null,
stderr = "",
): TailscaleCommandError =>
new TailscaleCommandError({
command: ["tailscale", ...args],
message,
exitCode,
stderr,
});
const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));
function normalizeMagicDnsName(status: TailscaleStatusJson): string | null {
const dnsName = status.Self?.DNSName;
if (typeof dnsName !== "string") {
return null;
}
const normalized = dnsName.trim().replace(/\.$/u, "");
return normalized.length > 0 ? normalized : null;
}
export const parseTailscaleMagicDnsName = (
rawStatusJson: string,
): Effect.Effect<string | null, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map(normalizeMagicDnsName),
);
export function isTailscaleIpv4Address(address: string): boolean {
const parts = address.split(".");
if (parts.length !== 4) {
return false;
}
const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));
if (
first === undefined ||
second === undefined ||
third === undefined ||
fourth === undefined ||
[first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)
) {
return false;
}
return first === 100 && second >= 64 && second <= 127;
}
export const parseTailscaleStatus = (
rawStatusJson: string,
): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>
decodeTailscaleStatusJson(rawStatusJson).pipe(
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
Effect.map((parsed) => {
const rawIps = parsed.Self?.TailscaleIPs;
const tailnetIpv4Addresses = Array.isArray(rawIps)
? rawIps
.filter((address): address is string => typeof address === "string")
.filter(isTailscaleIpv4Address)
: [];
return {
magicDnsName: normalizeMagicDnsName(parsed),
tailnetIpv4Addresses,
};
}),
);
export const readTailscaleStatus: Effect.Effect<
TailscaleStatus,
TailscaleCommandError | TailscaleStatusParseError,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const args = ["status", "--json"];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner
.spawn(
ChildProcess.make("tailscale", args, {
shell: process.platform === "win32",
}),
)
.pipe(
Effect.mapError((cause) =>
tailscaleCommandError(
args,
cause instanceof Error ? cause.message : "Failed to spawn tailscale status.",
null,
),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStdout(child.stdout),
collectStderr(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError((cause) =>
tailscaleCommandError(
args,
cause instanceof Error ? cause.message : "Failed to run tailscale status.",
null,
),
),
);
if (exitCode !== 0) {
return yield* tailscaleCommandError(
args,
`Tailscale status exited with code ${exitCode}.`,
exitCode,
stderr,
);
}
return yield* parseTailscaleStatus(stdout);
}).pipe(
Effect.scoped,
Effect.timeoutOption(TAILSCALE_STATUS_TIMEOUT_MS),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
tailscaleCommandError(["status", "--json"], "Tailscale status timed out.", null),
),
onSome: Effect.succeed,
}),
),
);
export function buildTailscaleHttpsBaseUrl(input: {
readonly magicDnsName: string;
readonly servePort?: number;
}): string {
const url = new URL(`https://${input.magicDnsName}`);
const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {
url.port = String(servePort);
}
url.pathname = "/";
return url.toString();
}
const runTailscaleCommand = (
args: readonly string[],
input: {
readonly spawnMessage: string;
readonly runMessage: string;
readonly exitMessage: (exitCode: number) => string;
readonly timeoutMessage: string;
readonly timeoutMs: number;
},
): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner
.spawn(
ChildProcess.make("tailscale", args, {
shell: process.platform === "win32",
}),
)
.pipe(
Effect.mapError((cause) =>
tailscaleCommandError(
args,
cause instanceof Error ? cause.message : input.spawnMessage,
null,
),
),
);
const [stderr, exitCode] = yield* Effect.all(
[collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError((cause) =>
tailscaleCommandError(
args,
cause instanceof Error ? cause.message : input.runMessage,
null,
),
),
);
if (exitCode !== 0) {
return yield* tailscaleCommandError(args, input.exitMessage(exitCode), exitCode, stderr);
}
}).pipe(
Effect.scoped,
Effect.timeoutOption(input.timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(tailscaleCommandError(args, input.timeoutMessage, null)),
onSome: Effect.succeed,
}),
),
);
export const ensureTailscaleServe = (input: {
readonly localPort: number;
readonly servePort?: number;
readonly localHost?: string;
}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {
const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
const localHost = input.localHost ?? "127.0.0.1";
const args = ["serve", "--bg", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];
return runTailscaleCommand(args, {
spawnMessage: "Failed to spawn tailscale serve.",
runMessage: "Failed to run tailscale serve.",
exitMessage: (exitCode) => `Tailscale serve exited with code ${exitCode}.`,
timeoutMessage: "Tailscale serve timed out.",
timeoutMs: TAILSCALE_SERVE_TIMEOUT_MS,
});
};
export const disableTailscaleServe: Effect.Effect<
void,
TailscaleCommandError,
ChildProcessSpawner.ChildProcessSpawner
> = runTailscaleCommand(["serve", "off"], {
spawnMessage: "Failed to spawn tailscale serve off.",
runMessage: "Failed to run tailscale serve off.",
exitMessage: (exitCode) => `Tailscale serve off exited with code ${exitCode}.`,
timeoutMessage: "Tailscale serve off timed out.",
timeoutMs: TAILSCALE_SERVE_TIMEOUT_MS,
});
export const probeTailscaleHttpsEndpoint = (input: {
readonly baseUrl: string;
readonly timeoutMs?: number;
}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* Effect.gen(function* () {
const url = new URL("/.well-known/t3/environment", input.baseUrl);
const request = HttpClientRequest.get(url.toString());
return yield* client.execute(request);
}).pipe(Effect.timeoutOption(input.timeoutMs ?? TAILSCALE_PROBE_TIMEOUT_MS));
return Option.match(response, {
onNone: () => false,
onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
});
}).pipe(Effect.catch(() => Effect.succeed(false)));
export const resolveTailscaleHttpsBaseUrl = (
input: {
readonly servePort?: number;
} = {},
): Effect.Effect<
string | null,
TailscaleCommandError | TailscaleStatusParseError,
ChildProcessSpawner.ChildProcessSpawner
> =>
readTailscaleStatus.pipe(
Effect.map((status) =>
status.magicDnsName
? buildTailscaleHttpsBaseUrl({
magicDnsName: status.magicDnsName,
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
})
: null,
),
);
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more