Repository navigation
feat(mobile): terminal-first — delete chat stacks, terminals as sessions, agent launch from home - #6366
Conversation
… reconnecting socket
expo-font 56.0.7 (June 15 batch) references a Record symbol added to expo-modules-core after 56.0.15, crashing the app at launch with a DYLD missing-symbol abort. Pin to 56.0.5, the newest build predating the symbol.
…ys, glass input modules/composer: an ExpoView overlay whose bar pins to keyboardLayoutGuide, so input rides the keyboard's real animation curve. Owns the growing UITextView, send button, quick-keys row (data-driven), and glass background (UIGlassEffect on iOS 26, thick material fallback before). The terminal screen drops KeyboardAvoidingView + the RN quick-keys row for it.
…ons, agent launch from home Removes both chat surfaces (ACP + legacy Mastra, ~3k LOC) and the tab-bar module; home rows become live terminals joined with agent bindings; the NewChatWidget prompts existing workspaces via agents.run (or terminal.send into a live claude) and new projects via the workspaces.create agent sugar.
|
Too many files changed for review (174 files, 100 file limit). Bypass the limit by tagging |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe mobile app replaces ACP chat flows with host terminal sessions. It adds terminal discovery, startup, streaming, input, tabs, agent selection, workspace actions, terminal routes, and agent preset settings. ChangesMobile terminal migration
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant HomeScreen
participant useStartWorkspaceTerminal
participant HostService
participant WorkspaceScreen
participant TerminalWebView
HomeScreen->>useStartWorkspaceTerminal: submit prompt and agent
useStartWorkspaceTerminal->>HostService: reuse or launch terminal
HostService-->>useStartWorkspaceTerminal: return terminal identifiers
useStartWorkspaceTerminal->>WorkspaceScreen: navigate with terminalId
WorkspaceScreen->>TerminalWebView: open terminal session
TerminalWebView-->>WorkspaceScreen: stream output and connection state
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
25 issues found across 174 files
You’re at about 93% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx:65">
P1: The Finish review target list now includes plain shell terminals, so a user can send review text to a shell rather than to an agent. Restrict existing targets to terminals with an attached agent (or route the selection through the agent launch/reuse flow).</violation>
<violation number="2" location="apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx:162">
P2: Agents waiting for permission are shown as `Idle`, hiding a blocked state and making the target status misleading. Render the permission state distinctly, such as `Permission needed`.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts">
<violation number="1" location="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts:72">
P1: Switching organizations can briefly show the previous organization's terminal rows, and can keep them when the new fetch fails. Including the organization-scoped URL in this query key keeps terminal inventories isolated per host.</violation>
<violation number="2" location="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts:82">
P2: A transient failure in `terminalAgents.list` hides every live terminal, even though unbound shells are valid rows. Fetch the terminal inventory independently and use an empty binding list when only the status join fails.</violation>
<violation number="3" location="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts:95">
P2: Attention dots can remain visible after a failed refresh. Requiring `query.isSuccess` for the binding map clears cached statuses when the host query is no longer live while preserving the cache-first terminal rows.</violation>
</file>
<file name="apps/mobile/lib/host/client.ts">
<violation number="1" location="apps/mobile/lib/host/client.ts:13">
P1: Host requests can use the wrong relay after an account switch or while initial priming is still pending, making overridden hosts appear offline and terminal actions fail. The global override needs an auth-scoped reset and stale-result protection, and consumers need to be notified or gated until the current user's relay is resolved.</violation>
</file>
<file name="packages/trpc/src/lib/relay-url.ts">
<violation number="1" location="packages/trpc/src/lib/relay-url.ts:24">
P2: Run-now automation dispatch fails when the valid relay override has a trailing slash because this returns it unchanged and the relay client adds another slash before `/hosts`. Normalizing trailing slashes when resolving the base URL keeps the override compatible with the existing relay request builder.</violation>
<violation number="2" location="packages/trpc/src/lib/relay-url.ts:25">
P2: Relay-resolution failures are silently hidden, making a PostHog outage or bad flag configuration difficult to diagnose while users are routed to the wrong relay. Logging the caught error with the resolver context before returning the fallback would preserve the intended best-effort behavior without swallowing the failure.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/WorkspaceScreen/WorkspaceScreen.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/WorkspaceScreen/WorkspaceScreen.tsx:65">
P2: Closing a terminal can fail silently while leaving an unhandled promise rejection because the rejected `killSession` chain is discarded. Returning the invalidation promise and adding a final `.catch` that logs or surfaces the failure would keep this best-effort action observable.
(Based on your team's feedback about handling rejected asynchronous calls.)</violation>
</file>
<file name="plans/20260804-1815-relay2-durable-objects-canonical.md">
<violation number="1" location="plans/20260804-1815-relay2-durable-objects-canonical.md:48">
P3: Milestone 5 strategy contradicts D-20, which this line cites as its basis. The edited line labels the cutover "wait-for-drain", but D-20 (line 112) explicitly rejects that: "The M5 all-users cutover is ops-only, accept-the-churn ... we do not need to carefully wait for full drain." Use the same terminology as D-20 to keep the canonical plan internally consistent.</violation>
<violation number="2" location="plans/20260804-1815-relay2-durable-objects-canonical.md:268">
P3: The 2026-08-10 revision note mislabels D-20 as the "wait-for-drain cutover". D-20 is explicitly the opposite (ops-only, accept-the-churn, no waiting for full drain). Correct the shorthand so the canonical plan doesn't record a strategy D-20 rejects.</violation>
</file>
<file name="apps/desktop/src/renderer/components/Redirect/Redirect.test.tsx">
<violation number="1" location="apps/desktop/src/renderer/components/Redirect/Redirect.test.tsx:163">
P3: The "renders nothing" test does not verify its claim: `expect(html).not.toContain("undefined")` only checks that the literal string "undefined" is absent from the container, which is trivially true for both a null-rendering and a content-rendering Redirect. The test would pass even if Redirect leaked real output into the DOM, so it adds no coverage for the behavior it names.</violation>
</file>
<file name="apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/collections.ts">
<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/collections.ts:254">
P3: This header addition to the collections apiClient appears unrelated to this PR's stated mobile terminal-first scope, and it duplicates the identical x-superset-client block already in lib/api-trpc-client.ts. Consider moving this header logic into the shared spot (or a small helper) and landing it in its own PR so the cross-cutting client-version change is reviewed and rolled back independently.</violation>
</file>
<file name="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardContentError/DashboardContentError.tsx">
<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardContentError/DashboardContentError.tsx:22">
P2: Sentry reports for dashboard content crashes omit the React component stack, making pane-specific failures harder to diagnose than root route failures. Destructure `info` and include its `componentStack` in `captureException` (ideally through a shared error-reporting helper).</violation>
</file>
<file name="apps/desktop/src/renderer/components/Redirect/Redirect.tsx">
<violation number="1" location="apps/desktop/src/renderer/components/Redirect/Redirect.tsx:31">
P2: A failed redirect is not retried on a later render with the same destination: clearing this ref does not retrigger the effect because its dependencies are unchanged. Track a retry signal in the effect dependencies or expose an explicit, bounded retry path so transient route-load/guard failures can recover.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/(home)/home/components/NewChatWidget/hooks/useStartWorkspaceTerminal/useStartWorkspaceTerminal.ts">
<violation number="1" location="apps/mobile/screens/(authenticated)/(home)/home/components/NewChatWidget/hooks/useStartWorkspaceTerminal/useStartWorkspaceTerminal.ts:37">
P2: Attachment messages fail for existing workspaces even though the home composer enables and submits them; users get “Attachments are not supported…” instead of an agent launch or message. Reuse the upload/`attachmentIds` forwarding path used by `useCreateTerminalWorkspace` for the `agents.run` branch, and define an equivalent terminal-send behavior (or disable attachments for this target) rather than rejecting after submission.</violation>
</file>
<file name="packages/host-service/src/runtime/pull-requests/pull-requests.test.ts">
<violation number="1" location="packages/host-service/src/runtime/pull-requests/pull-requests.test.ts:1020">
P3: The `resumes sync and logs degraded-exit` test depends on an unverified timing window: the first `await waitFor(() => refsReads() > 0, 100)` never satisfies (reads are pinned at 0 while the worktree is missing), so it is only a fixed 100ms sleep and gives no guarantee the first event's missing-state sync actually completed before `disk.exists = true` is flipped. If that first sync is slow or coalesces with the second emit (enqueueWorkspaceSync sets rerunPending on an in-flight entry), `noteWorktreePresent` finds no missing state, the `Worktree reappeared` warning never fires, and the assertion fails flakily.</violation>
</file>
<file name="apps/mobile/app/(authenticated)/_layout.tsx">
<violation number="1" location="apps/mobile/app/(authenticated)/_layout.tsx:29">
P1: Home host rows and live terminal requests can use the wrong relay on the first authenticated render or immediately after switching accounts. This layout starts relay discovery asynchronously, but child host hooks synchronously capture the fallback or stale module-global URL, so users assigned to a non-default relay can see missing/offline sessions until the screen is remounted or its queries are rebuilt; priming readiness should gate these requests or update/invalidate them after resolution.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/(home)/home/components/NewChatWidget/hooks/useCreateTerminalWorkspace/useCreateTerminalWorkspace.ts">
<violation number="1" location="apps/mobile/screens/(authenticated)/(home)/home/components/NewChatWidget/hooks/useCreateTerminalWorkspace/useCreateTerminalWorkspace.ts:55">
P2: New-workspace launches ignore the model selected in the mobile picker: switching to the `claude` terminal preset makes every current `SUPERSET_CHAT_MODELS` ID unsupported, so the host drops `--model` and Claude uses its default. A Claude-compatible picker or an explicit ID translation before `workspaces.create` would preserve the existing model-picker behavior.</violation>
</file>
<file name="apps/mobile/hooks/usePrimeRelayUrl/usePrimeRelayUrl.ts">
<violation number="1" location="apps/mobile/hooks/usePrimeRelayUrl/usePrimeRelayUrl.ts:15">
P3: Relay priming can issue redundant API requests whenever auth publishes a new session object even though the relay is user-scoped; depending on `session?.user?.id` would preserve re-resolution on account changes without rerunning on unrelated session updates.
(Based on your team's feedback about narrow React effect dependencies.)</violation>
</file>
<file name="packages/host-service/src/runtime/pull-requests/pull-requests.ts">
<violation number="1" location="packages/host-service/src/runtime/pull-requests/pull-requests.ts:591">
P2: A workspace moved to a new worktree path can remain paused because the degraded-state map keeps probing the old path. Key the early return on both workspace ID and current path, so a later sync replaces the path being probed.</violation>
<violation number="2" location="packages/host-service/src/runtime/pull-requests/pull-requests.ts:597">
P2: Host shutdown can leak a missing-worktree probe timer when an already-running sync observes a missing path after `stop()` has cleared the timer. A stopped manager needs a lifecycle guard in `noteWorktreeMissing`, or shutdown must await/cancel in-flight syncs before allowing new timers.</violation>
</file>
<file name="apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/BackgroundTerminalsButton/BackgroundTerminalsButton.tsx">
<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/BackgroundTerminalsButton/BackgroundTerminalsButton.tsx:100">
P2: A newly backgrounded terminal can disappear from the button because the always-enabled list query exposes stale data to the marker cleanup effect before the terminal appears in a poll. Preserving markers until a list response newer than the marker timestamp is available (or limiting this cleanup to a fresh/open list) keeps the optimistic background flow intact.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/(home)/home/HomeScreen.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/(home)/home/HomeScreen.tsx:97">
P2: Pull-to-refresh does not refresh the terminal rows introduced here; it only refetches workspaces, so a newly started or closed terminal can remain visible for up to the polling interval. Include the host-terminals query in the refresh operation.</violation>
<violation number="2" location="apps/mobile/screens/(authenticated)/(home)/home/HomeScreen.tsx:281">
P2: Closing a terminal that has already exited or when the relay request fails produces an unhandled rejected promise. Catch and surface the mutation failure before invalidating the terminal list.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Mobile as Mobile App
participant Auth as Auth Client
participant API as Cloud API
participant Relay as Relay Service
participant Host as Host Service
participant Terminal as Terminal Agent
Note over Mobile,Terminal: NEW: Terminal-First Architecture
rect rgb(240, 248, 255)
Note over Mobile,Host: Session Initialization
Mobile->>Auth: Authenticate
Auth-->>Mobile: session token
Mobile->>API: primeRelayUrl() - resolve relay endpoint
API-->>Mobile: relay URL
end
rect rgb(255, 248, 240)
Note over Mobile,Terminal: Home Screen - Live Terminal Rows
Mobile->>Host: terminal.list query (poll 5s)
Host->>Terminal: List all host terminals
Terminal-->>Host: terminal sessions status
Host-->>Mobile: terminal list (all workspaces)
Mobile->>Host: terminalAgents.list query (parallel)
Host-->>Mobile: agent bindings
Mobile->>Mobile: JOIN terminals + agent bindings
Mobile->>Mobile: render TerminalRow (per workspace)
end
rect rgb(240, 255, 240)
Note over Mobile,Terminal: NEW: Launch Agent from Home
Mobile->>Host: terminalAgents.findActive (workspaceId, "claude")
alt Active terminal exists
Host-->>Mobile: active terminal found
Mobile->>Host: terminal.send (terminalId, text)
else No active terminal
Host-->>Mobile: no active terminal
Mobile->>Host: agents.run (agent: "claude", prompt, model)
Host->>Terminal: Bootstrap claude agent in new terminal
Terminal-->>Host: terminal session ID
Host-->>Mobile: terminal session created
end
Mobile->>Mobile: Navigate to /workspace/{id}/terminal/{terminalId}
Mobile->>Terminal: Subscribe to terminal output (native composer)
Terminal-->>Mobile: stream output + quick keys
end
rect rgb(255, 240, 240)
Note over Mobile,Host: Kill Terminal Session
Mobile->>Host: terminal.killSession mutate
Host->>Terminal: Kill process/bin/bash
Host-->>Mobile: kill confirmed
Mobile->>Mobile: invalidate terminal list cache
end
Note over Host: CHANGED: Terminal is now the session abstraction<br/>- Unified terminal.list replaces chat/ACP endpoints<br/>- Host-wide per-host listing<br/>- Real-time agent status via lifecycle hooks
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| ), | ||
| [sessionsByWorkspace, workspaceId], | ||
| const terminalRows = useMemo( | ||
| () => (workspaceId ? (terminalsByWorkspace.get(workspaceId) ?? []) : []), |
There was a problem hiding this comment.
P1: The Finish review target list now includes plain shell terminals, so a user can send review text to a shell rather than to an agent. Restrict existing targets to terminals with an attached agent (or route the selection through the agent launch/reuse flow).
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx, line 65:
<comment>The Finish review target list now includes plain shell terminals, so a user can send review text to a shell rather than to an agent. Restrict existing targets to terminals with an attached agent (or route the selection through the agent launch/reuse flow).</comment>
<file context>
@@ -53,14 +58,12 @@ export function FinishReviewSheet() {
- ),
- [sessionsByWorkspace, workspaceId],
+ const terminalRows = useMemo(
+ () => (workspaceId ? (terminalsByWorkspace.get(workspaceId) ?? []) : []),
+ [terminalsByWorkspace, workspaceId],
);
</file context>
| () => (workspaceId ? (terminalsByWorkspace.get(workspaceId) ?? []) : []), | |
| () => | |
| workspaceId | |
| ? (terminalsByWorkspace.get(workspaceId) ?? []).filter( | |
| (row) => row.agentId !== null, | |
| ) | |
| : [], |
| : null; | ||
|
|
||
| const query = useQuery({ | ||
| queryKey: getHostTerminalsQueryKey(host?.machineId ?? null), |
There was a problem hiding this comment.
P1: Switching organizations can briefly show the previous organization's terminal rows, and can keep them when the new fetch fails. Including the organization-scoped URL in this query key keeps terminal inventories isolated per host.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts, line 72:
<comment>Switching organizations can briefly show the previous organization's terminal rows, and can keep them when the new fetch fails. Including the organization-scoped URL in this query key keeps terminal inventories isolated per host.</comment>
<file context>
@@ -0,0 +1,136 @@
+ : null;
+
+ const query = useQuery({
+ queryKey: getHostTerminalsQueryKey(host?.machineId ?? null),
+ enabled: hostUrl !== null,
+ refetchInterval: TERMINALS_REFETCH_INTERVAL_MS,
</file context>
| // Primed once after sign-in and cached; the Expo env is the fallback until | ||
| // then and if the API is unreachable. Sync getter so the URL builders that | ||
| // depend on it stay sync. | ||
| let relayOverride: string | null = null; |
There was a problem hiding this comment.
P1: Host requests can use the wrong relay after an account switch or while initial priming is still pending, making overridden hosts appear offline and terminal actions fail. The global override needs an auth-scoped reset and stale-result protection, and consumers need to be notified or gated until the current user's relay is resolved.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/lib/host/client.ts, line 13:
<comment>Host requests can use the wrong relay after an account switch or while initial priming is still pending, making overridden hosts appear offline and terminal actions fail. The global override needs an auth-scoped reset and stale-result protection, and consumers need to be notified or gated until the current user's relay is resolved.</comment>
<file context>
@@ -1,22 +1,28 @@
+// Primed once after sign-in and cached; the Expo env is the fallback until
+// then and if the API is unreachable. Sync getter so the URL builders that
+// depend on it stay sync.
+let relayOverride: string | null = null;
+
+export async function primeRelayUrl(): Promise<void> {
</file context>
|
|
||
| export default function AuthenticatedLayout() { | ||
| useDevicePresence(); | ||
| usePrimeRelayUrl(); |
There was a problem hiding this comment.
P1: Home host rows and live terminal requests can use the wrong relay on the first authenticated render or immediately after switching accounts. This layout starts relay discovery asynchronously, but child host hooks synchronously capture the fallback or stale module-global URL, so users assigned to a non-default relay can see missing/offline sessions until the screen is remounted or its queries are rebuilt; priming readiness should gate these requests or update/invalidate them after resolution.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/app/(authenticated)/_layout.tsx, line 29:
<comment>Home host rows and live terminal requests can use the wrong relay on the first authenticated render or immediately after switching accounts. This layout starts relay discovery asynchronously, but child host hooks synchronously capture the fallback or stale module-global URL, so users assigned to a non-default relay can see missing/offline sessions until the screen is remounted or its queries are rebuilt; priming readiness should gate these requests or update/invalidate them after resolution.</comment>
<file context>
@@ -25,6 +26,7 @@ const glassHeaderOptions = {
export default function AuthenticatedLayout() {
useDevicePresence();
+ usePrimeRelayUrl();
return (
</file context>
| subtitle={row.status === "running" ? "Running" : "Idle"} | ||
| selected={target === row.id} | ||
| onPress={() => setTarget(row.id)} | ||
| subtitle={row.attention === "working" ? "Running" : "Idle"} |
There was a problem hiding this comment.
P2: Agents waiting for permission are shown as Idle, hiding a blocked state and making the target status misleading. Render the permission state distinctly, such as Permission needed.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx, line 162:
<comment>Agents waiting for permission are shown as `Idle`, hiding a blocked state and making the target status misleading. Render the permission state distinctly, such as `Permission needed`.</comment>
<file context>
@@ -153,13 +155,13 @@ export function FinishReviewSheet() {
- subtitle={row.status === "running" ? "Running" : "Idle"}
- selected={target === row.id}
- onPress={() => setTarget(row.id)}
+ subtitle={row.attention === "working" ? "Running" : "Idle"}
+ selected={target === row.terminalId}
+ onPress={() => setTarget(row.terminalId)}
</file context>
| subtitle={row.attention === "working" ? "Running" : "Idle"} | |
| subtitle={ | |
| row.attention === "permission" | |
| ? "Permission needed" | |
| : row.attention === "working" | |
| ? "Running" | |
| : "Idle" | |
| } |
| - [x] (2026-08-10) Milestone 3 RESOLVED as not-needed for terminals: the terminal already has app-layer resumable catch-up (`host-service/src/terminal/terminal.ts` retained ring + `?seq=<epoch>:<n>` anchor; renderer `terminal-ws-transport.ts` tracks the anchor and reconnects with it). It is transport-agnostic, so it resumes gap-free through relay2's byte splice — verified by a live `wrangler deploy` mid-session: host reconnected on v2 in ~15s, zero `session-gone`. A relay-layer DO buffer (original D-7) would duplicate this; not building it. The event bus is the only stream without app-layer resume, but a dropped event just triggers a refetch — not worth a DO buffer. | ||
| - [x] (2026-08-10) Milestone 4 SHIPPED: v2 client + API-served relay config in stable desktop 1.20.2. `host.relayEndpoint` (jwtProcedure) is the single server-side resolver — the host-service asks for it after authenticating, killing the identify-race that stranded hosts on the wrong relay. Desktop renderer/main, CLI, web, and mobile all read it. Root cause of the rollout pain reproduced under controlled conditions (old code took the fallback relay, new code resolved the flag). Relay-consumer gap sweep merged: automation dispatch (#6337), trpc runNow + shared `resolveUserRelayUrl` + CLI resolveHostTarget + web CSP + mobile (#6340). Web CSP allowlists the relay2 origin. | ||
| - [ ] Milestone 4 remaining: internal team fully ported (flag = `@superset.sh`; Satya on relay2 and verified via live traffic; Kiet/Avi move on their next canary restart). Web CSP allowlist and all the per-consumer flag plumbing are cutover-temporary (see D-20). | ||
| - [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the hostname cutover with **wait-for-drain**, not a v1 compat layer (D-20). |
There was a problem hiding this comment.
P3: Milestone 5 strategy contradicts D-20, which this line cites as its basis. The edited line labels the cutover "wait-for-drain", but D-20 (line 112) explicitly rejects that: "The M5 all-users cutover is ops-only, accept-the-churn ... we do not need to carefully wait for full drain." Use the same terminology as D-20 to keep the canonical plan internally consistent.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plans/20260804-1815-relay2-durable-objects-canonical.md, line 48:
<comment>Milestone 5 strategy contradicts D-20, which this line cites as its basis. The edited line labels the cutover "wait-for-drain", but D-20 (line 112) explicitly rejects that: "The M5 all-users cutover is ops-only, accept-the-churn ... we do not need to carefully wait for full drain." Use the same terminology as D-20 to keep the canonical plan internally consistent.</comment>
<file context>
@@ -40,9 +41,11 @@ A working prototype already validated the platform (PR #6165, `apps/relay-do`):
+- [x] (2026-08-10) Milestone 3 RESOLVED as not-needed for terminals: the terminal already has app-layer resumable catch-up (`host-service/src/terminal/terminal.ts` retained ring + `?seq=<epoch>:<n>` anchor; renderer `terminal-ws-transport.ts` tracks the anchor and reconnects with it). It is transport-agnostic, so it resumes gap-free through relay2's byte splice — verified by a live `wrangler deploy` mid-session: host reconnected on v2 in ~15s, zero `session-gone`. A relay-layer DO buffer (original D-7) would duplicate this; not building it. The event bus is the only stream without app-layer resume, but a dropped event just triggers a refetch — not worth a DO buffer.
+- [x] (2026-08-10) Milestone 4 SHIPPED: v2 client + API-served relay config in stable desktop 1.20.2. `host.relayEndpoint` (jwtProcedure) is the single server-side resolver — the host-service asks for it after authenticating, killing the identify-race that stranded hosts on the wrong relay. Desktop renderer/main, CLI, web, and mobile all read it. Root cause of the rollout pain reproduced under controlled conditions (old code took the fallback relay, new code resolved the flag). Relay-consumer gap sweep merged: automation dispatch (#6337), trpc runNow + shared `resolveUserRelayUrl` + CLI resolveHostTarget + web CSP + mobile (#6340). Web CSP allowlists the relay2 origin.
+- [ ] Milestone 4 remaining: internal team fully ported (flag = `@superset.sh`; Satya on relay2 and verified via live traffic; Kiet/Avi move on their next canary restart). Web CSP allowlist and all the per-consumer flag plumbing are cutover-temporary (see D-20).
+- [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the hostname cutover with **wait-for-drain**, not a v1 compat layer (D-20).
## Surprises & Discoveries
</file context>
| - [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the hostname cutover with **wait-for-drain**, not a v1 compat layer (D-20). | |
| - [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the ops-only hostname cutover with **accept-the-churn** (no v1 compat layer, no wait-for-drain), per D-20. |
| // target route renders <div>target</div>; Redirect itself emits nothing | ||
| html = container.innerHTML; | ||
| }); | ||
| expect(html).not.toContain("undefined"); |
There was a problem hiding this comment.
P3: The "renders nothing" test does not verify its claim: expect(html).not.toContain("undefined") only checks that the literal string "undefined" is absent from the container, which is trivially true for both a null-rendering and a content-rendering Redirect. The test would pass even if Redirect leaked real output into the DOM, so it adds no coverage for the behavior it names.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/components/Redirect/Redirect.test.tsx, line 163:
<comment>The "renders nothing" test does not verify its claim: `expect(html).not.toContain("undefined")` only checks that the literal string "undefined" is absent from the container, which is trivially true for both a null-rendering and a content-rendering Redirect. The test would pass even if Redirect leaked real output into the DOM, so it adds no coverage for the behavior it names.</comment>
<file context>
@@ -0,0 +1,165 @@
+ // target route renders <div>target</div>; Redirect itself emits nothing
+ html = container.innerHTML;
+ });
+ expect(html).not.toContain("undefined");
+ });
+});
</file context>
| return token ? { Authorization: `Bearer ${token}` } : {}; | ||
| return { | ||
| ...(token ? { Authorization: `Bearer ${token}` } : {}), | ||
| ...(window.App?.appVersion |
There was a problem hiding this comment.
P3: This header addition to the collections apiClient appears unrelated to this PR's stated mobile terminal-first scope, and it duplicates the identical x-superset-client block already in lib/api-trpc-client.ts. Consider moving this header logic into the shared spot (or a small helper) and landing it in its own PR so the cross-cutting client-version change is reviewed and rolled back independently.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/collections.ts, line 254:
<comment>This header addition to the collections apiClient appears unrelated to this PR's stated mobile terminal-first scope, and it duplicates the identical x-superset-client block already in lib/api-trpc-client.ts. Consider moving this header logic into the shared spot (or a small helper) and landing it in its own PR so the cross-cutting client-version change is reviewed and rolled back independently.</comment>
<file context>
@@ -249,7 +249,12 @@ const apiClient = createTRPCProxyClient<AppRouter>({
- return token ? { Authorization: `Bearer ${token}` } : {};
+ return {
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
+ ...(window.App?.appVersion
+ ? { "x-superset-client": `desktop/${window.App.appVersion}` }
+ : {}),
</file context>
|
|
||
| const { warnings } = await withCapturedWarnings(async () => { | ||
| bus.emit(createdEvent); | ||
| await waitFor(() => refsReads() > 0, 100); |
There was a problem hiding this comment.
P3: The resumes sync and logs degraded-exit test depends on an unverified timing window: the first await waitFor(() => refsReads() > 0, 100) never satisfies (reads are pinned at 0 while the worktree is missing), so it is only a fixed 100ms sleep and gives no guarantee the first event's missing-state sync actually completed before disk.exists = true is flipped. If that first sync is slow or coalesces with the second emit (enqueueWorkspaceSync sets rerunPending on an in-flight entry), noteWorktreePresent finds no missing state, the Worktree reappeared warning never fires, and the assertion fails flakily.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/runtime/pull-requests/pull-requests.test.ts, line 1020:
<comment>The `resumes sync and logs degraded-exit` test depends on an unverified timing window: the first `await waitFor(() => refsReads() > 0, 100)` never satisfies (reads are pinned at 0 while the worktree is missing), so it is only a fixed 100ms sleep and gives no guarantee the first event's missing-state sync actually completed before `disk.exists = true` is flipped. If that first sync is slow or coalesces with the second emit (enqueueWorkspaceSync sets rerunPending on an in-flight entry), `noteWorktreePresent` finds no missing state, the `Worktree reappeared` warning never fires, and the assertion fails flakily.</comment>
<file context>
@@ -955,3 +959,105 @@ describe("workspace-created event trigger", () => {
+
+ const { warnings } = await withCapturedWarnings(async () => {
+ bus.emit(createdEvent);
+ await waitFor(() => refsReads() > 0, 100);
+ bus.emit(createdEvent);
+ await waitFor(() => refsReads() > 0, 100);
</file context>
|
|
||
| useEffect(() => { | ||
| if (session) void primeRelayUrl(); | ||
| }, [session]); |
There was a problem hiding this comment.
P3: Relay priming can issue redundant API requests whenever auth publishes a new session object even though the relay is user-scoped; depending on session?.user?.id would preserve re-resolution on account changes without rerunning on unrelated session updates.
(Based on your team's feedback about narrow React effect dependencies.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/hooks/usePrimeRelayUrl/usePrimeRelayUrl.ts, line 15:
<comment>Relay priming can issue redundant API requests whenever auth publishes a new session object even though the relay is user-scoped; depending on `session?.user?.id` would preserve re-resolution on account changes without rerunning on unrelated session updates.
(Based on your team's feedback about narrow React effect dependencies.) </comment>
<file context>
@@ -0,0 +1,16 @@
+
+ useEffect(() => {
+ if (session) void primeRelayUrl();
+ }, [session]);
+}
</file context>
There was a problem hiding this comment.
21 issues found across 174 files
You’re at about 93% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="plans/20260804-1815-relay2-durable-objects-canonical.md">
<violation number="1" location="plans/20260804-1815-relay2-durable-objects-canonical.md:48">
P3: Milestone 5 strategy contradicts D-20, which this line cites as its basis. The edited line labels the cutover "wait-for-drain", but D-20 (line 112) explicitly rejects that: "The M5 all-users cutover is ops-only, accept-the-churn ... we do not need to carefully wait for full drain." Use the same terminology as D-20 to keep the canonical plan internally consistent.</violation>
<violation number="2" location="plans/20260804-1815-relay2-durable-objects-canonical.md:268">
P3: The 2026-08-10 revision note mislabels D-20 as the "wait-for-drain cutover". D-20 is explicitly the opposite (ops-only, accept-the-churn, no waiting for full drain). Correct the shorthand so the canonical plan doesn't record a strategy D-20 rejects.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx:65">
P1: The Finish review target list now includes plain shell terminals, so a user can send review text to a shell rather than to an agent. Restrict existing targets to terminals with an attached agent (or route the selection through the agent launch/reuse flow).</violation>
<violation number="2" location="apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx:162">
P2: Agents waiting for permission are shown as `Idle`, hiding a blocked state and making the target status misleading. Render the permission state distinctly, such as `Permission needed`.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts">
<violation number="1" location="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts:72">
P1: Switching organizations can briefly show the previous organization's terminal rows, and can keep them when the new fetch fails. Including the organization-scoped URL in this query key keeps terminal inventories isolated per host.</violation>
<violation number="2" location="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts:82">
P2: A transient failure in `terminalAgents.list` hides every live terminal, even though unbound shells are valid rows. Fetch the terminal inventory independently and use an empty binding list when only the status join fails.</violation>
<violation number="3" location="apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts:95">
P2: Attention dots can remain visible after a failed refresh. Requiring `query.isSuccess` for the binding map clears cached statuses when the host query is no longer live while preserving the cache-first terminal rows.</violation>
</file>
<file name="apps/mobile/lib/host/client.ts">
<violation number="1" location="apps/mobile/lib/host/client.ts:13">
P1: Host requests can use the wrong relay after an account switch or while initial priming is still pending, making overridden hosts appear offline and terminal actions fail. The global override needs an auth-scoped reset and stale-result protection, and consumers need to be notified or gated until the current user's relay is resolved.</violation>
</file>
<file name="packages/trpc/src/lib/relay-url.ts">
<violation number="1" location="packages/trpc/src/lib/relay-url.ts:24">
P2: Run-now automation dispatch fails when the valid relay override has a trailing slash because this returns it unchanged and the relay client adds another slash before `/hosts`. Normalizing trailing slashes when resolving the base URL keeps the override compatible with the existing relay request builder.</violation>
<violation number="2" location="packages/trpc/src/lib/relay-url.ts:25">
P2: Relay-resolution failures are silently hidden, making a PostHog outage or bad flag configuration difficult to diagnose while users are routed to the wrong relay. Logging the caught error with the resolver context before returning the fallback would preserve the intended best-effort behavior without swallowing the failure.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/WorkspaceScreen/WorkspaceScreen.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/WorkspaceScreen/WorkspaceScreen.tsx:65">
P2: Closing a terminal can fail silently while leaving an unhandled promise rejection because the rejected `killSession` chain is discarded. Returning the invalidation promise and adding a final `.catch` that logs or surfaces the failure would keep this best-effort action observable.
(Based on your team's feedback about handling rejected asynchronous calls.)</violation>
</file>
<file name="apps/desktop/src/renderer/components/Redirect/Redirect.test.tsx">
<violation number="1" location="apps/desktop/src/renderer/components/Redirect/Redirect.test.tsx:163">
P3: The "renders nothing" test does not verify its claim: `expect(html).not.toContain("undefined")` only checks that the literal string "undefined" is absent from the container, which is trivially true for both a null-rendering and a content-rendering Redirect. The test would pass even if Redirect leaked real output into the DOM, so it adds no coverage for the behavior it names.</violation>
</file>
<file name="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardContentError/DashboardContentError.tsx">
<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardContentError/DashboardContentError.tsx:22">
P2: Sentry reports for dashboard content crashes omit the React component stack, making pane-specific failures harder to diagnose than root route failures. Destructure `info` and include its `componentStack` in `captureException` (ideally through a shared error-reporting helper).</violation>
</file>
<file name="apps/desktop/src/renderer/components/Redirect/Redirect.tsx">
<violation number="1" location="apps/desktop/src/renderer/components/Redirect/Redirect.tsx:31">
P2: A failed redirect is not retried on a later render with the same destination: clearing this ref does not retrigger the effect because its dependencies are unchanged. Track a retry signal in the effect dependencies or expose an explicit, bounded retry path so transient route-load/guard failures can recover.</violation>
</file>
<file name="packages/host-service/src/runtime/pull-requests/pull-requests.test.ts">
<violation number="1" location="packages/host-service/src/runtime/pull-requests/pull-requests.test.ts:1020">
P3: The `resumes sync and logs degraded-exit` test depends on an unverified timing window: the first `await waitFor(() => refsReads() > 0, 100)` never satisfies (reads are pinned at 0 while the worktree is missing), so it is only a fixed 100ms sleep and gives no guarantee the first event's missing-state sync actually completed before `disk.exists = true` is flipped. If that first sync is slow or coalesces with the second emit (enqueueWorkspaceSync sets rerunPending on an in-flight entry), `noteWorktreePresent` finds no missing state, the `Worktree reappeared` warning never fires, and the assertion fails flakily.</violation>
</file>
<file name="apps/mobile/app/(authenticated)/_layout.tsx">
<violation number="1" location="apps/mobile/app/(authenticated)/_layout.tsx:29">
P1: Home host rows and live terminal requests can use the wrong relay on the first authenticated render or immediately after switching accounts. This layout starts relay discovery asynchronously, but child host hooks synchronously capture the fallback or stale module-global URL, so users assigned to a non-default relay can see missing/offline sessions until the screen is remounted or its queries are rebuilt; priming readiness should gate these requests or update/invalidate them after resolution.</violation>
</file>
<file name="apps/mobile/hooks/usePrimeRelayUrl/usePrimeRelayUrl.ts">
<violation number="1" location="apps/mobile/hooks/usePrimeRelayUrl/usePrimeRelayUrl.ts:15">
P3: Relay priming can issue redundant API requests whenever auth publishes a new session object even though the relay is user-scoped; depending on `session?.user?.id` would preserve re-resolution on account changes without rerunning on unrelated session updates.
(Based on your team's feedback about narrow React effect dependencies.)</violation>
</file>
<file name="packages/host-service/src/runtime/pull-requests/pull-requests.ts">
<violation number="1" location="packages/host-service/src/runtime/pull-requests/pull-requests.ts:591">
P2: A workspace moved to a new worktree path can remain paused because the degraded-state map keeps probing the old path. Key the early return on both workspace ID and current path, so a later sync replaces the path being probed.</violation>
<violation number="2" location="packages/host-service/src/runtime/pull-requests/pull-requests.ts:597">
P2: Host shutdown can leak a missing-worktree probe timer when an already-running sync observes a missing path after `stop()` has cleared the timer. A stopped manager needs a lifecycle guard in `noteWorktreeMissing`, or shutdown must await/cancel in-flight syncs before allowing new timers.</violation>
</file>
<file name="apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/BackgroundTerminalsButton/BackgroundTerminalsButton.tsx">
<violation number="1" location="apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/BackgroundTerminalsButton/BackgroundTerminalsButton.tsx:100">
P2: A newly backgrounded terminal can disappear from the button because the always-enabled list query exposes stale data to the marker cleanup effect before the terminal appears in a poll. Preserving markers until a list response newer than the marker timestamp is available (or limiting this cleanup to a fresh/open list) keeps the optimistic background flow intact.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/(home)/home/HomeScreen.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/(home)/home/HomeScreen.tsx:97">
P2: Pull-to-refresh does not refresh the terminal rows introduced here; it only refetches workspaces, so a newly started or closed terminal can remain visible for up to the polling interval. Include the host-terminals query in the refresh operation.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Mobile as Mobile App
participant Auth as Auth Client
participant API as Cloud API
participant Relay as Relay Service
participant Host as Host Service
participant Terminal as Terminal Agent
Note over Mobile,Terminal: NEW: Terminal-First Architecture
rect rgb(240, 248, 255)
Note over Mobile,Host: Session Initialization
Mobile->>Auth: Authenticate
Auth-->>Mobile: session token
Mobile->>API: primeRelayUrl() - resolve relay endpoint
API-->>Mobile: relay URL
end
rect rgb(255, 248, 240)
Note over Mobile,Terminal: Home Screen - Live Terminal Rows
Mobile->>Host: terminal.list query (poll 5s)
Host->>Terminal: List all host terminals
Terminal-->>Host: terminal sessions status
Host-->>Mobile: terminal list (all workspaces)
Mobile->>Host: terminalAgents.list query (parallel)
Host-->>Mobile: agent bindings
Mobile->>Mobile: JOIN terminals + agent bindings
Mobile->>Mobile: render TerminalRow (per workspace)
end
rect rgb(240, 255, 240)
Note over Mobile,Terminal: NEW: Launch Agent from Home
Mobile->>Host: terminalAgents.findActive (workspaceId, "claude")
alt Active terminal exists
Host-->>Mobile: active terminal found
Mobile->>Host: terminal.send (terminalId, text)
else No active terminal
Host-->>Mobile: no active terminal
Mobile->>Host: agents.run (agent: "claude", prompt, model)
Host->>Terminal: Bootstrap claude agent in new terminal
Terminal-->>Host: terminal session ID
Host-->>Mobile: terminal session created
end
Mobile->>Mobile: Navigate to /workspace/{id}/terminal/{terminalId}
Mobile->>Terminal: Subscribe to terminal output (native composer)
Terminal-->>Mobile: stream output + quick keys
end
rect rgb(255, 240, 240)
Note over Mobile,Host: Kill Terminal Session
Mobile->>Host: terminal.killSession mutate
Host->>Terminal: Kill process/bin/bash
Host-->>Mobile: kill confirmed
Mobile->>Mobile: invalidate terminal list cache
end
Note over Host: CHANGED: Terminal is now the session abstraction<br/>- Unified terminal.list replaces chat/ACP endpoints<br/>- Host-wide per-host listing<br/>- Real-time agent status via lifecycle hooks
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| ), | ||
| [sessionsByWorkspace, workspaceId], | ||
| const terminalRows = useMemo( | ||
| () => (workspaceId ? (terminalsByWorkspace.get(workspaceId) ?? []) : []), |
There was a problem hiding this comment.
P1: The Finish review target list now includes plain shell terminals, so a user can send review text to a shell rather than to an agent. Restrict existing targets to terminals with an attached agent (or route the selection through the agent launch/reuse flow).
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx, line 65:
<comment>The Finish review target list now includes plain shell terminals, so a user can send review text to a shell rather than to an agent. Restrict existing targets to terminals with an attached agent (or route the selection through the agent launch/reuse flow).</comment>
<file context>
@@ -53,14 +58,12 @@ export function FinishReviewSheet() {
- ),
- [sessionsByWorkspace, workspaceId],
+ const terminalRows = useMemo(
+ () => (workspaceId ? (terminalsByWorkspace.get(workspaceId) ?? []) : []),
+ [terminalsByWorkspace, workspaceId],
);
</file context>
| () => (workspaceId ? (terminalsByWorkspace.get(workspaceId) ?? []) : []), | |
| () => | |
| workspaceId | |
| ? (terminalsByWorkspace.get(workspaceId) ?? []).filter( | |
| (row) => row.agentId !== null, | |
| ) | |
| : [], |
| : null; | ||
|
|
||
| const query = useQuery({ | ||
| queryKey: getHostTerminalsQueryKey(host?.machineId ?? null), |
There was a problem hiding this comment.
P1: Switching organizations can briefly show the previous organization's terminal rows, and can keep them when the new fetch fails. Including the organization-scoped URL in this query key keeps terminal inventories isolated per host.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/(home)/home/hooks/useHostTerminals/useHostTerminals.ts, line 72:
<comment>Switching organizations can briefly show the previous organization's terminal rows, and can keep them when the new fetch fails. Including the organization-scoped URL in this query key keeps terminal inventories isolated per host.</comment>
<file context>
@@ -0,0 +1,136 @@
+ : null;
+
+ const query = useQuery({
+ queryKey: getHostTerminalsQueryKey(host?.machineId ?? null),
+ enabled: hostUrl !== null,
+ refetchInterval: TERMINALS_REFETCH_INTERVAL_MS,
</file context>
| // Primed once after sign-in and cached; the Expo env is the fallback until | ||
| // then and if the API is unreachable. Sync getter so the URL builders that | ||
| // depend on it stay sync. | ||
| let relayOverride: string | null = null; |
There was a problem hiding this comment.
P1: Host requests can use the wrong relay after an account switch or while initial priming is still pending, making overridden hosts appear offline and terminal actions fail. The global override needs an auth-scoped reset and stale-result protection, and consumers need to be notified or gated until the current user's relay is resolved.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/lib/host/client.ts, line 13:
<comment>Host requests can use the wrong relay after an account switch or while initial priming is still pending, making overridden hosts appear offline and terminal actions fail. The global override needs an auth-scoped reset and stale-result protection, and consumers need to be notified or gated until the current user's relay is resolved.</comment>
<file context>
@@ -1,22 +1,28 @@
+// Primed once after sign-in and cached; the Expo env is the fallback until
+// then and if the API is unreachable. Sync getter so the URL builders that
+// depend on it stay sync.
+let relayOverride: string | null = null;
+
+export async function primeRelayUrl(): Promise<void> {
</file context>
|
|
||
| export default function AuthenticatedLayout() { | ||
| useDevicePresence(); | ||
| usePrimeRelayUrl(); |
There was a problem hiding this comment.
P1: Home host rows and live terminal requests can use the wrong relay on the first authenticated render or immediately after switching accounts. This layout starts relay discovery asynchronously, but child host hooks synchronously capture the fallback or stale module-global URL, so users assigned to a non-default relay can see missing/offline sessions until the screen is remounted or its queries are rebuilt; priming readiness should gate these requests or update/invalidate them after resolution.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/app/(authenticated)/_layout.tsx, line 29:
<comment>Home host rows and live terminal requests can use the wrong relay on the first authenticated render or immediately after switching accounts. This layout starts relay discovery asynchronously, but child host hooks synchronously capture the fallback or stale module-global URL, so users assigned to a non-default relay can see missing/offline sessions until the screen is remounted or its queries are rebuilt; priming readiness should gate these requests or update/invalidate them after resolution.</comment>
<file context>
@@ -25,6 +26,7 @@ const glassHeaderOptions = {
export default function AuthenticatedLayout() {
useDevicePresence();
+ usePrimeRelayUrl();
return (
</file context>
| subtitle={row.status === "running" ? "Running" : "Idle"} | ||
| selected={target === row.id} | ||
| onPress={() => setTarget(row.id)} | ||
| subtitle={row.attention === "working" ? "Running" : "Idle"} |
There was a problem hiding this comment.
P2: Agents waiting for permission are shown as Idle, hiding a blocked state and making the target status misleading. Render the permission state distinctly, such as Permission needed.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/finish-review/FinishReviewSheet.tsx, line 162:
<comment>Agents waiting for permission are shown as `Idle`, hiding a blocked state and making the target status misleading. Render the permission state distinctly, such as `Permission needed`.</comment>
<file context>
@@ -153,13 +155,13 @@ export function FinishReviewSheet() {
- subtitle={row.status === "running" ? "Running" : "Idle"}
- selected={target === row.id}
- onPress={() => setTarget(row.id)}
+ subtitle={row.attention === "working" ? "Running" : "Idle"}
+ selected={target === row.terminalId}
+ onPress={() => setTarget(row.terminalId)}
</file context>
| subtitle={row.attention === "working" ? "Running" : "Idle"} | |
| subtitle={ | |
| row.attention === "permission" | |
| ? "Permission needed" | |
| : row.attention === "working" | |
| ? "Running" | |
| : "Idle" | |
| } |
| - [x] (2026-08-10) Milestone 3 RESOLVED as not-needed for terminals: the terminal already has app-layer resumable catch-up (`host-service/src/terminal/terminal.ts` retained ring + `?seq=<epoch>:<n>` anchor; renderer `terminal-ws-transport.ts` tracks the anchor and reconnects with it). It is transport-agnostic, so it resumes gap-free through relay2's byte splice — verified by a live `wrangler deploy` mid-session: host reconnected on v2 in ~15s, zero `session-gone`. A relay-layer DO buffer (original D-7) would duplicate this; not building it. The event bus is the only stream without app-layer resume, but a dropped event just triggers a refetch — not worth a DO buffer. | ||
| - [x] (2026-08-10) Milestone 4 SHIPPED: v2 client + API-served relay config in stable desktop 1.20.2. `host.relayEndpoint` (jwtProcedure) is the single server-side resolver — the host-service asks for it after authenticating, killing the identify-race that stranded hosts on the wrong relay. Desktop renderer/main, CLI, web, and mobile all read it. Root cause of the rollout pain reproduced under controlled conditions (old code took the fallback relay, new code resolved the flag). Relay-consumer gap sweep merged: automation dispatch (#6337), trpc runNow + shared `resolveUserRelayUrl` + CLI resolveHostTarget + web CSP + mobile (#6340). Web CSP allowlists the relay2 origin. | ||
| - [ ] Milestone 4 remaining: internal team fully ported (flag = `@superset.sh`; Satya on relay2 and verified via live traffic; Kiet/Avi move on their next canary restart). Web CSP allowlist and all the per-consumer flag plumbing are cutover-temporary (see D-20). | ||
| - [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the hostname cutover with **wait-for-drain**, not a v1 compat layer (D-20). |
There was a problem hiding this comment.
P3: Milestone 5 strategy contradicts D-20, which this line cites as its basis. The edited line labels the cutover "wait-for-drain", but D-20 (line 112) explicitly rejects that: "The M5 all-users cutover is ops-only, accept-the-churn ... we do not need to carefully wait for full drain." Use the same terminology as D-20 to keep the canonical plan internally consistent.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plans/20260804-1815-relay2-durable-objects-canonical.md, line 48:
<comment>Milestone 5 strategy contradicts D-20, which this line cites as its basis. The edited line labels the cutover "wait-for-drain", but D-20 (line 112) explicitly rejects that: "The M5 all-users cutover is ops-only, accept-the-churn ... we do not need to carefully wait for full drain." Use the same terminology as D-20 to keep the canonical plan internally consistent.</comment>
<file context>
@@ -40,9 +41,11 @@ A working prototype already validated the platform (PR #6165, `apps/relay-do`):
+- [x] (2026-08-10) Milestone 3 RESOLVED as not-needed for terminals: the terminal already has app-layer resumable catch-up (`host-service/src/terminal/terminal.ts` retained ring + `?seq=<epoch>:<n>` anchor; renderer `terminal-ws-transport.ts` tracks the anchor and reconnects with it). It is transport-agnostic, so it resumes gap-free through relay2's byte splice — verified by a live `wrangler deploy` mid-session: host reconnected on v2 in ~15s, zero `session-gone`. A relay-layer DO buffer (original D-7) would duplicate this; not building it. The event bus is the only stream without app-layer resume, but a dropped event just triggers a refetch — not worth a DO buffer.
+- [x] (2026-08-10) Milestone 4 SHIPPED: v2 client + API-served relay config in stable desktop 1.20.2. `host.relayEndpoint` (jwtProcedure) is the single server-side resolver — the host-service asks for it after authenticating, killing the identify-race that stranded hosts on the wrong relay. Desktop renderer/main, CLI, web, and mobile all read it. Root cause of the rollout pain reproduced under controlled conditions (old code took the fallback relay, new code resolved the flag). Relay-consumer gap sweep merged: automation dispatch (#6337), trpc runNow + shared `resolveUserRelayUrl` + CLI resolveHostTarget + web CSP + mobile (#6340). Web CSP allowlists the relay2 origin.
+- [ ] Milestone 4 remaining: internal team fully ported (flag = `@superset.sh`; Satya on relay2 and verified via live traffic; Kiet/Avi move on their next canary restart). Web CSP allowlist and all the per-consumer flag plumbing are cutover-temporary (see D-20).
+- [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the hostname cutover with **wait-for-drain**, not a v1 compat layer (D-20).
## Surprises & Discoveries
</file context>
| - [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the hostname cutover with **wait-for-drain**, not a v1 compat layer (D-20). | |
| - [ ] Milestone 5: rollout to all users + decommission `apps/relay` + Fly fleet + Upstash + rename `relay2` → `relay`. Strategy is the ops-only hostname cutover with **accept-the-churn** (no v1 compat layer, no wait-for-drain), per D-20. |
| // target route renders <div>target</div>; Redirect itself emits nothing | ||
| html = container.innerHTML; | ||
| }); | ||
| expect(html).not.toContain("undefined"); |
There was a problem hiding this comment.
P3: The "renders nothing" test does not verify its claim: expect(html).not.toContain("undefined") only checks that the literal string "undefined" is absent from the container, which is trivially true for both a null-rendering and a content-rendering Redirect. The test would pass even if Redirect leaked real output into the DOM, so it adds no coverage for the behavior it names.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/components/Redirect/Redirect.test.tsx, line 163:
<comment>The "renders nothing" test does not verify its claim: `expect(html).not.toContain("undefined")` only checks that the literal string "undefined" is absent from the container, which is trivially true for both a null-rendering and a content-rendering Redirect. The test would pass even if Redirect leaked real output into the DOM, so it adds no coverage for the behavior it names.</comment>
<file context>
@@ -0,0 +1,165 @@
+ // target route renders <div>target</div>; Redirect itself emits nothing
+ html = container.innerHTML;
+ });
+ expect(html).not.toContain("undefined");
+ });
+});
</file context>
|
|
||
| const { warnings } = await withCapturedWarnings(async () => { | ||
| bus.emit(createdEvent); | ||
| await waitFor(() => refsReads() > 0, 100); |
There was a problem hiding this comment.
P3: The resumes sync and logs degraded-exit test depends on an unverified timing window: the first await waitFor(() => refsReads() > 0, 100) never satisfies (reads are pinned at 0 while the worktree is missing), so it is only a fixed 100ms sleep and gives no guarantee the first event's missing-state sync actually completed before disk.exists = true is flipped. If that first sync is slow or coalesces with the second emit (enqueueWorkspaceSync sets rerunPending on an in-flight entry), noteWorktreePresent finds no missing state, the Worktree reappeared warning never fires, and the assertion fails flakily.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/runtime/pull-requests/pull-requests.test.ts, line 1020:
<comment>The `resumes sync and logs degraded-exit` test depends on an unverified timing window: the first `await waitFor(() => refsReads() > 0, 100)` never satisfies (reads are pinned at 0 while the worktree is missing), so it is only a fixed 100ms sleep and gives no guarantee the first event's missing-state sync actually completed before `disk.exists = true` is flipped. If that first sync is slow or coalesces with the second emit (enqueueWorkspaceSync sets rerunPending on an in-flight entry), `noteWorktreePresent` finds no missing state, the `Worktree reappeared` warning never fires, and the assertion fails flakily.</comment>
<file context>
@@ -955,3 +959,105 @@ describe("workspace-created event trigger", () => {
+
+ const { warnings } = await withCapturedWarnings(async () => {
+ bus.emit(createdEvent);
+ await waitFor(() => refsReads() > 0, 100);
+ bus.emit(createdEvent);
+ await waitFor(() => refsReads() > 0, 100);
</file context>
|
|
||
| useEffect(() => { | ||
| if (session) void primeRelayUrl(); | ||
| }, [session]); |
There was a problem hiding this comment.
P3: Relay priming can issue redundant API requests whenever auth publishes a new session object even though the relay is user-scoped; depending on session?.user?.id would preserve re-resolution on account changes without rerunning on unrelated session updates.
(Based on your team's feedback about narrow React effect dependencies.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/hooks/usePrimeRelayUrl/usePrimeRelayUrl.ts, line 15:
<comment>Relay priming can issue redundant API requests whenever auth publishes a new session object even though the relay is user-scoped; depending on `session?.user?.id` would preserve re-resolution on account changes without rerunning on unrelated session updates.
(Based on your team's feedback about narrow React effect dependencies.) </comment>
<file context>
@@ -0,0 +1,16 @@
+
+ useEffect(() => {
+ if (session) void primeRelayUrl();
+ }, [session]);
+}
</file context>
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
Replaces the cramped UIKit modules/composer with TerminalComposer — the home NewChatWidget's SwiftUI glass pill + draft-ref TextField, trimmed to the terminal's needs, with quick-keys floating above the pill. The screen tracks the keyboard height directly (a native header offsets KeyboardAvoidingView's own measurement) so the composer sits above the keyboard and the WebView reflows. Deletes the UIKit module entirely.
There was a problem hiding this comment.
2 issues found across 16 files (changes from recent commits).
You’re at about 96% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalComposer/TerminalComposer.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalComposer/TerminalComposer.tsx:65">
P2: Users cannot send a bare Enter in the terminal, so TUIs that accept an empty response/default or require a blank line cannot be operated from this composer. An explicit empty submit path or an Enter quick key would preserve terminal input semantics.</violation>
<violation number="2" location="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalComposer/TerminalComposer.tsx:67">
P2: Input typed while the terminal is still connecting or reconnecting can be lost because the composer clears the draft immediately even though the WebView send has no success signal. Keeping the draft until the terminal is ready/acknowledges the write, or gating the composer on connection readiness, would avoid silent input loss.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
|
|
||
| const submit = () => { | ||
| const text = draftRef.current; | ||
| if (text.trim().length === 0) return; |
There was a problem hiding this comment.
P2: Users cannot send a bare Enter in the terminal, so TUIs that accept an empty response/default or require a blank line cannot be operated from this composer. An explicit empty submit path or an Enter quick key would preserve terminal input semantics.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalComposer/TerminalComposer.tsx, line 65:
<comment>Users cannot send a bare Enter in the terminal, so TUIs that accept an empty response/default or require a blank line cannot be operated from this composer. An explicit empty submit path or an Enter quick key would preserve terminal input semantics.</comment>
<file context>
@@ -0,0 +1,138 @@
+
+ const submit = () => {
+ const text = draftRef.current;
+ if (text.trim().length === 0) return;
+ onSubmit(text);
+ draftRef.current = "";
</file context>
| const text = draftRef.current; | ||
| if (text.trim().length === 0) return; | ||
| onSubmit(text); | ||
| draftRef.current = ""; |
There was a problem hiding this comment.
P2: Input typed while the terminal is still connecting or reconnecting can be lost because the composer clears the draft immediately even though the WebView send has no success signal. Keeping the draft until the terminal is ready/acknowledges the write, or gating the composer on connection readiness, would avoid silent input loss.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalComposer/TerminalComposer.tsx, line 67:
<comment>Input typed while the terminal is still connecting or reconnecting can be lost because the composer clears the draft immediately even though the WebView send has no success signal. Keeping the draft until the terminal is ready/acknowledges the write, or gating the composer on connection readiness, would avoid silent input loss.</comment>
<file context>
@@ -0,0 +1,138 @@
+ const text = draftRef.current;
+ if (text.trim().length === 0) return;
+ onSubmit(text);
+ draftRef.current = "";
+ setHasText(false);
+ void fieldRef.current?.clear();
</file context>
…iew pill top-right Tapping the header name (now with a caret) opens a bottom action sheet (the Cursor pattern) with Edit name / Copy ID / Share / Delete — the actions that lived in the header's ellipsis menu. The top-right becomes a single glass Review pill (relocated from the composer's floating chip) carrying the diff stat, shown only when there are changes; it links to the existing diff surface.
The Changes rows were PressableScales — a scroll drag starting on a row (most of the page) fired the shrink animation and fought the gesture, reading as the page refusing to scroll. Rows are plain Pressables with an opacity press state now. Composer circles shrink from filling the pill to ~12pt clearance on all three sides (frame 26→12; the collapsed row pulls -4pt horizontal to cancel the bordered style's intrinsic inset).
The -4pt experiment pressed the circles into the pill; tuned against the render to horizontal 7 / vertical 4, which lands ~8pt clearance on every side.
Dogfooding the fresh-session flow surfaced two bugs. Quick keys were dead: the glass Host renders taller than its reported frame and, as the later sibling, its invisible top edge sat over the RN chip row — taps fired the pill's tap-to-focus instead of the chip (verified with a dd|xxd byte probe; ^[[A now delivers). And the tab strip inherited home's activity sort, so tabs swapped places whenever relative activity changed — tabs now hold session creation order. Also final composer paddings from the pixel-measured tuning pass (horizontal 1, vertical 4).
…omments expo-application before expo-asset (Sherif's alphabetical rule); the terminal/[terminalId] redirect had zero referrers — every push became ?tab= and no shipped binary carries old links; route-option comments removed.
…6434) Teardown Wave A slice 2. ACP is dropped in favor of chat-v3: it was gated behind SUPERSET_ACP_SESSIONS=1 (internal builds only), had a mobile-only UI already removed in #6366, zero stable-build users, and emitted zero analytics. Removes the host-service ACP runtime + router + WS route and its gate, the acp_sessions host.db table (migration 0022), packages/session-protocol entirely, host-client's ACP arm, the @agentclientprotocol deps, the desktop env wiring, six integration tests and their fixture. HarnessKind/StopReason needed no inlining — acp_sessions was their only consumer. The two ACP plan docs move to plans/done/ so nothing new gets built on them.
The terminal-first pivot lands: both mobile chat surfaces are deleted, terminals become the session rows, and the home widget launches terminal agents. Stacked on #6356 (native composer) → #6342 (terminal screen); merges main, so it carries #6340's per-user relay resolution (every dial resolves relay2 for flagged users) and the #6341
terminal.listrename.Deleted (~3k LOC, mobile-side only — host-service chat/ACP routers untouched)
chat/acp/[sessionId], 25 files) and the dead legacy Mastra stack (chat/[sessionId], 16 files), their routes and layout entries.lib/trpc/host-chat-types.ts(the lossy hand-typed facade) +lib/trpc/host-client.ts(4 fps polling transport) — both documented INTERIM debts.SessionRowchat UI + fork stub +ClaudeLogohardcode,useHostAcpSessions, the unusedtab-barnative module.Replaced with
terminal.list, host-wide per host) left-joined with agent bindings (terminalAgents.list) — agent mark + status when an agent is attached, plain shell rows otherwise. Tapping opens the terminal screen.terminalAgents.findActive→terminal.sendinto a live agent terminal, elseagents.run. New workspaces:workspaces.createwith the agent sugar. Voice dictation and target chips unchanged; the model picker is replaced by an agent picker (see below).Fix found during E2E
The first re-plumb called
terminalAgents.getOrCreatebare — which spawns a plain shell and waits for an agent that nothing launched (10s timeout, terminal disposed). The launch responsibility belongs toagents.run; the hook now uses findActive→send / agents.run, matching desktop semantics.Workspace = tabbed terminal shell (final cut on this branch)
WorkspaceScreenis the terminal now: tab strip (agent mark + name, attention dots, long-press to close) + one liveTerminalWebViewkeyed by the active tab + the glassTerminalComposer. The session-list screen is deleted; home rows land directly on a tab viaworkspace/[id]?tab=, andterminal/[terminalId]redirects there for old links.+opens a native action sheet of the host'ssettings.agentConfigspresets (launched viaagents.runwith an empty prompt — host-side refine relaxed for terminal agents) plus a plain Shell (terminal.createSession).new-chat/routes renamednew-session/; the model picker became an agent picker over the target host's configs. The persisted preference is thepresetId(portable across hosts), not the per-host row UUID.settings/presets: read-only per-host listing of agent presets; editing stays on desktop.Verified E2E on iOS 26.5 simulator against prod
+sheet listed the host's real presets (Claude, Amp, Codex, Gemini, Copilot) + Shell; Shell launched in the workspace's worktree and became the active tab; tab switch re-attached the claude stream; long-press → Close killed the session and the strip updated.Dogfooding polish batch (day 2)
WorkspaceIconsemantics in the leading slot (brailleAsciiSpinnerwhile working beats the PR icon, corner ping overlays for permission/failed,FolderGit2when idle); PR icon routes to the in-app Changes screen.review(green, unseen Stop) derived against a persisted host-clock monotonic seen map, cleared by viewing the tab;failedjoins the set; rollups useSTATUS_PRIORITY; dot colors matchStatusIndicator, with theanimate-pinghalo ported to reanimated.switchmessage (generation-counter guarded) instead of remounting, keeping the 400KB xterm parse and TLS pool warm. Also a guard dropping NaN-corrupted SGR mouse reports that leaked asaN;NaNM…input spam.pinnedAtmap floating pins to the top of home.Stack.Toolbar.Buttonnow), title width fits the floating bar items, tab strip is square chips with a+that opens the sheet; tabs hold creation order instead of re-sorting by activity mid-session.z-10fix, verified with add|xxdbyte probe), home composer always launches a new session (thefindActivereuse path contradicted the "New agent in …" label), and workspace share links go through one env-based helper (/workspaces/<id>kept canonical — web side tracked in SUPER-1846).@gorhom/bottom-sheetremoved (last consumer was dead chat-era code).Notes for review
chat_sessionsElectric collection consumers are gone from mobile; the cloud rows remain (desktop still writes them) — coordinate final removal with feat(desktop,mobile,trpc): replace Electric sync with plain tRPC + React Query #6328.Summary by cubic
Makes mobile terminal-first: deletes chat stacks, turns Workspace into a tabbed terminal shell, and launches agents from Home or a New session sheet. Share links now use an env-based helper, with
EXPO_PUBLIC_WEB_URLdefaulting to https://app.superset.sh.settings.agentConfigsor a plain shell; compact header with an icon-only Review button; stable tab order; drops NaN-corrupted wheel reports.new-chat/*→new-session/*; model picker → Agent picker; selectedagentIdpersists across hosts; read‑only presets atsettings/presets; agent brand marks bundled viaexpo-asset; Home composer always runs a fresh agent viaagents.runand returns to the shell with the new tab active._whoownstunnel probes onv2_hosts.is_online; routes all host calls through the per‑user relay URL (typed clients inlib/host-service/client).@superset/host-clientbinding and chat types, the chat‑era model selector,@superset/tab-bar, and@gorhom/bottom-sheet.workspaceShareUrlonEXPO_PUBLIC_WEB_URL;/workspaces/<id>stays canonical; the legacy terminal redirect route is removed.Migration
/new-chat/*to/new-session/*; deep links should target/workspace/[id]?tab=<terminalId>.@superset/host-client,@superset/tab-bar,@gorhom/bottom-sheet.react-native-webview,@xterm/xterm,@xterm/addon-fit,expo-asset, and pinexpo-fontto56.0.5.Written for commit 34f24bc. Summary will update on new commits.
Summary by CodeRabbit
New Features
Updates