Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(renderer): bound the unattended hosted reconnect and tie it to its tab (R40)
review0a5dcb27832f
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex c521ca7aa..62f753323 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -484,7 +484,7 @@ import { HostedApprovalDialog } from '../components/HostedApprovalDialog'import { emitLocalRelayClose, onLocalRelayClose } from '../bridge/relay-local-close'import { isJoinCode } from '@shared/relay-join-code'import { createHostedJoiner, type HostedJoiner, type HostedMountOutcome } from '../lib/hostedJoin'-import { HOSTED_APPROVAL_WAIT_MS, isReadOnlyRole, stripIpcPrefix, viewerBannerText, waitingForOwnerText } from '../lib/hostedTeam'+import { HOSTED_APPROVAL_WAIT_MS, isReadOnlyRole, stripIpcPrefix, viewerBannerText } from '../lib/hostedTeam'import { answerHostedRequest, type HostedAnswer } from '../lib/hostedOwner'import { headRequest, type QueuedRequest } from '../lib/hostedPendingQueue'import { useHostedPending } from '../state/hostedPending'@@ -713,6 +713,12 @@ function noticeDwellMs(text: string): number {/** React Flow props for a hosted team tab whose role is below Editor. */const HOSTED_READ_ONLY_FLOW = { nodesDraggable: false, nodesConnectable: false } as const+/** Is this project an open tab (not closed, not deleted)? What a hosted reconnect is for (R40). */+function isOpenTab(projectId: string): boolean {+ const p = useProjects.getState().getProject(projectId)+ return !!p && !p.closed+}+/** The confirm dialogs, named so their setters can be wrapped in a synchronous open-guard (see* `confirmFlags`): ONE confirm at a time, decided at call time rather than at the next render. */interface ConfirmState {@@ -1317,6 +1323,9 @@ export function Canvas() {// Live relay tabs, keyed by relay connectionId, so a host/relay drop can dispose the right one// (a remote connection is now a project TAB, not a full-surface overlay — Stage 4 Task 6).const relayTabsRef = useRef<Map<string, RelayTab>>(new Map())+ // The hosted-team joiner (created below, with the relay mount it drives): here so the tab disposal+ // can stop a closed tab's reconnect.+ const hostedJoinerRef = useRef<HostedJoiner | null>(null)// A relay tab is a live client of a remote core — closing/deleting its project must tear the// relay session down (held presence teardown + socket close), or the peer lingers in the host's// facepile and the socket leaks until quit. Runs on BOTH close and delete (unlike a local tmux@@ -1329,6 +1338,8 @@ export function Canvas() {// a still-live tab, no-ops them for an already-offline one, and unbinds + drops the entry either// way. We also sweep any live relayTabsRef entry for the project so a dead connectionId can't linger.const disposeRelayTabForProject = useCallback((projectId: string) => {+ // A hosted tab's team stops trying to come back into it, in any phase (R40). A no-op otherwise.+ hostedJoinerRef.current?.tabClosed(projectId)for (const [connectionId, tab] of relayTabsRef.current) {if (tab.projectId === projectId) relayTabsRef.current.delete(connectionId)}@@ -1369,10 +1380,9 @@ export function Canvas() {if (hostedPendingNotice) setNotice({ kind: 'info', text: hostedPendingNotice.text })}, [hostedPendingNotice])const answerHosted = useCallback((item: QueuedRequest, answer: HostedAnswer) => {- // Off the queue at once (the dialog closes; the host's own close follows), then say only what- // did not land.- useHostedPending.getState().settle(item.pending.pendingId)- void answerHostedRequest(item, answer).then((line) => {+ // Off the screen at once; settled only once the host answers (R40), then say what did not land.+ const q = useHostedPending.getState()+ void answerHostedRequest(item, answer, { begin: q.beginAnswer, finish: q.finishAnswer }).then((line) => {if (line) setNotice(line)})}, [])@@ -4192,7 +4202,14 @@ export function Canvas() {return openRelayTab(connectionId, label, {relayClient: window.nodeTerminal.relayClient,addProject: reconnectProjectId- ? () => ({ id: reconnectProjectId }) // reconnect: reuse the existing tab, don't spawn one+ ? () => {+ // A hosted reconnect whose tab was closed or deleted while it connected must never+ // bind to it (or un-grey it): refused here, the new session is disposed (R40).+ if (hosted && !isOpenTab(reconnectProjectId)) {+ throw new Error('The tab this reconnect was for is closed.')+ }+ return { id: reconnectProjectId } // reconnect: reuse the existing tab, don't spawn one+ }: (name) => useProjects.getState().addProject(name),// First connect adopts the host's shared project (its nodes, fresh id). On reconnect the// existing tab (with its nodes) is reused via addProject above, so no adopt lever is passed.@@ -4267,8 +4284,6 @@ export function Canvas() {: `Verify this code matches the one shown on the host:\n\n${sas}`if (sas && window.confirm(question)) {window.nodeTerminal.relayClient.confirm(connectionId)- // A first join waits for an owner — up to ten minutes. Say so rather than hang silently.- if (hosted) setNotice({ kind: 'info', text: waitingForOwnerText(label), sticky: true })} else {// Deliberate decline: mark it so the bootstrap's close-reject isn't surfaced as an error.cancelledConnsRef.current.add(connectionId)@@ -4284,10 +4299,9 @@ export function Canvas() {// Hosted teams (a Server Edition hosting over the relay, joined by a `nodeterm://join` code): the// ONE owner of every (re)join — boot, a dropped tab, a click on a greyed tab, a pasted code — so a- // team never has two attempts or two connections at once (lib/hostedJoin.ts). Created once; it- // reconnects every approved bookmark at boot. The Server Edition's `relayHosted` answers no- // bookmarks, so there it does nothing.- const hostedJoinerRef = useRef<HostedJoiner | null>(null)+ // team never has two attempts or two connections at once (lib/hostedJoin.ts). Created once+ // (`hostedJoinerRef` is declared beside relayTabsRef); it reconnects every approved bookmark at+ // boot. The Server Edition's `relayHosted` answers no bookmarks, so there it does nothing.useEffect(() => {const joiner = createHostedJoiner({connect: (code) => window.nodeTerminal.relayClient.connect(code),@@ -4301,7 +4315,13 @@ export function Canvas() {unLocal()}},- disconnect: (id) => window.nodeTerminal.relayClient.disconnect(id),+ onApproved: (id, listener) => window.nodeTerminal.relayClient.onApproved(id, listener),+ // A connection the joiner gives up on (its tab closed mid-approval, a cancelled late connect):+ // main never reports a close it was asked for, so it is announced here too.+ disconnect: (id) => {+ window.nodeTerminal.relayClient.disconnect(id)+ emitLocalRelayClose(id)+ },bookmarks: async () => (await window.nodeTerminal.relayHosted?.bookmarks()) ?? [],removeBookmark: (hostId) => window.nodeTerminal.relayHosted.removeBookmark(hostId),mount: (connectionId, req) => {@@ -4313,16 +4333,12 @@ export function Canvas() {bound?.source === 'relay' ? bound.id : undefined,// Only a reconnect the user asked for takes the screen (or one with nothing on it).{ activate: req.manual || !useProjects.getState().activeProjectId }- )- .then((o): HostedMountOutcome => o ?? { error: new Error('That connection is already open.'), declined: true })- .finally(() => setNotice((n) => (n?.text === waitingForOwnerText(req.label || 'Hosted team') ? null : n)))- },- tabOpen: (projectId) => {- const p = useProjects.getState().getProject(projectId)- return !!p && !p.closed+ ).then((o): HostedMountOutcome => o ?? { error: new Error('That connection is already open.'), declined: true })},+ tabOpen: isOpenTab,notify: (n) => setNotice(n),- promptForCode: (label) => promptDialog({ message: `Paste a fresh invite code for ${label || 'the team'}:` }),+ clearNotice: (text) => setNotice((n) => (n?.text === text ? null : n)),+ promptForCode: (label) => promptDialog({ message: `Paste an invite code for ${label || 'the team'}:` }),setTimer: (fn, ms) => setTimeout(fn, ms),clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>)})diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.tsindex 70d8d14d2..39014e9b8 100644--- a/src/renderer/canvas/hosted-team.source.test.ts+++ b/src/renderer/canvas/hosted-team.source.test.ts@@ -51,7 +51,7 @@ describe('hosted team glue in Canvas', () => {})it('the joiner is created once and reconnects the approved bookmarks at boot', () => {- const body = between('const hostedJoinerRef = useRef<HostedJoiner | null>(null)', '}, [confirmAndMount])')+ const body = between('const joiner = createHostedJoiner({', '}, [confirmAndMount])')expect(body).toContain('createHostedJoiner({')expect(body).toContain('void joiner.bootReconnect()')expect(body).toContain('joiner.dispose()')@@ -72,4 +72,29 @@ describe('hosted team glue in Canvas', () => {expect(body).toContain('<HostedApprovalDialog')expect(body).toContain('key={hostedHead.pending.pendingId}')})++ it('R40: closing or deleting a tab stops its team\'s attempt (the one disposal both paths share)', () => {+ const body = between('const disposeRelayTabForProject = useCallback(', '}, [])')+ expect(body).toContain('hostedJoinerRef.current?.tabClosed(projectId)')+ expect(src).toContain('disposeRelayTabForProject(id)\n store.closeProject(id)')+ expect(src).toContain('disposeRelayTabForProject(id)\n store.deleteProject(id)')+ })++ it('R40: a hosted reconnect refuses to bind to a tab that is no longer open; a Team Access one is unchanged', () => {+ const body = between('const mountRemoteMirror = useCallback(', 'const confirmAndMount = useCallback(')+ expect(body).toContain('if (hosted && !isOpenTab(reconnectProjectId)) {')+ expect(body).toContain('return { id: reconnectProjectId } // reconnect: reuse the existing tab')+ })++ it('R40: the waiting notice is the joiner\'s (every hosted mount), not tied to the SAS dialog', () => {+ const body = between('const confirmAndMount = useCallback(', 'return mountRemoteMirror(')+ expect(body).not.toContain('waitingForOwnerText')+ expect(between('const joiner = createHostedJoiner({', '}, [confirmAndMount])')).toContain('clearNotice:')+ })++ it('R40: an owner\'s answer is settled only once the host answered', () => {+ const body = between('const answerHosted = useCallback(', '}, [])')+ expect(body).toContain('{ begin: q.beginAnswer, finish: q.finishAnswer }')+ expect(body).not.toContain('.settle(')+ })})diff --git a/src/renderer/lib/hostedAttempts.test.ts b/src/renderer/lib/hostedAttempts.test.tsindex 204f1c524..3cf7e566d 100644--- a/src/renderer/lib/hostedAttempts.test.ts+++ b/src/renderer/lib/hostedAttempts.test.ts@@ -16,7 +16,11 @@ function harness() {const stopped: Array<{ req: HostedAttemptRequest; f: JoinFailure }> = []const ended: Array<{ req: HostedAttemptRequest; projectId: string; reason?: RelayClosedReason }> = []const disconnected: string[] = []+ const exhausted: HostedAttemptRequest[] = []+ const wanted = { value: true }const deps: HostedAttemptDeps = {+ exhausted: (req) => exhausted.push(req),+ wanted: () => wanted.value,connect: (code) => new Promise((resolve, reject) => connects.push({ code, resolve, reject })),mount: (id, req) => new Promise((resolve) => mounts.push({ id, req, resolve })),onClosed: (id, cb) => {@@ -42,7 +46,7 @@ function harness() {t.fn()}const armed = () => timers.filter((t) => !t.cleared)- return { deps, connects, mounts, closeCbs, unsubs, timers, armed, fire, stopped, ended, disconnected }+ return { deps, connects, mounts, closeCbs, unsubs, timers, armed, fire, stopped, ended, disconnected, exhausted, wanted }}const boot = (over: Partial<HostedAttemptRequest> = {}): HostedAttemptRequest => ({@@ -304,4 +308,150 @@ describe('hosted attempts: one attempt and one live connection per team (R38/R39await flush()expect(a.phase('H1')).toBeNull()})++ // ── R40 ─────────────────────────────────────────────────────────────────────────────────────────+ it('R40: a drop the host did not explain is retried at most 5 times on 1/2/4/8/15 s, then gives up ONCE', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ const delays: number[] = []+ for (let i = 0; i < 6; i++) {+ h.connects[i].resolve(`c${i}`)+ await flush()+ h.mounts[i].resolve({ retry: true })+ await flush()+ if (i < 5) {+ delays.push(h.armed()[0].ms)+ h.fire()+ }+ }+ expect(delays).toEqual([1000, 2000, 4000, 8000, 15000])+ expect(h.connects).toHaveLength(6)+ expect(h.armed()).toEqual([])+ expect(a.phase('H1')).toBeNull()+ expect(h.exhausted).toEqual([expect.objectContaining({ hostId: 'H1', reconnectProjectId: 'proj-1' })])+ expect(h.stopped).toEqual([])+ })++ it('R40: network failures keep the R35 60 s tail — the bound is for the pre-approval drop only', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot())+ for (let i = 0; i < 8; i++) {+ h.connects[i].reject(wrap('[E_JOIN_NETWORK] x'))+ await flush()+ h.fire()+ }+ expect(h.connects).toHaveLength(9)+ expect(h.exhausted).toEqual([])+ })++ it('R40: the drop budget starts over after the connection went live', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot())+ for (let i = 0; i < 4; i++) {+ h.connects[i].resolve(`c${i}`)+ await flush()+ h.mounts[i].resolve({ retry: true })+ await flush()+ h.fire()+ }+ h.connects[4].resolve('c4')+ await flush()+ h.mounts[4].resolve({ projectId: 'proj-1' })+ await flush()+ h.closeCbs.get('c4')!(undefined)+ a.run(boot())+ h.connects[5].resolve('c5')+ await flush()+ h.mounts[5].resolve({ retry: true })+ await flush()+ expect(h.armed()[0].ms).toBe(1000)+ })++ it('R40: a retry whose tab is gone does not happen', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))+ await flush()+ h.wanted.value = false // the tab was closed while the loop backed off+ h.fire()+ await flush()+ expect(h.connects).toHaveLength(1)+ expect(a.phase('H1')).toBeNull()+ expect(h.stopped).toEqual([])+ })++ it('R40: a connection that arrives after its tab is gone is closed, never mounted', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ h.wanted.value = false+ h.connects[0].resolve('c0')+ await flush()+ expect(h.mounts).toEqual([])+ expect(h.disconnected).toEqual(['c0'])+ expect(a.phase('H1')).toBeNull()+ })++ it('R40: closing a tab cancels its team\'s attempt in every phase, and releases the slot', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ // waiting+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))+ await flush()+ a.cancelProject('proj-1')+ expect(h.armed()).toEqual([])+ expect(a.phase('H1')).toBeNull()+ // connecting: the late connection is closed, not mounted+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ a.cancelProject('proj-1')+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts).toEqual([])+ expect(h.disconnected).toContain('c1')+ // mounting (the approval wait): the connection is closed and the slot is free at once+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ h.connects[2].resolve('c2')+ await flush()+ expect(a.phase('H1')).toBe('mounting')+ a.cancelProject('proj-1')+ expect(h.disconnected).toContain('c2')+ expect(a.phase('H1')).toBeNull()+ h.mounts[0].resolve({ projectId: 'proj-1' }) // lands late: ignored+ await flush()+ expect(a.phase('H1')).toBeNull()+ expect(a.run(boot())).toBe('started')+ })++ it('R40: cancelProject leaves other tabs\' teams alone, and releases a LIVE tab\'s team without reconnecting it', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ hostId: 'H2', reconnectProjectId: 'proj-2' }))+ a.run(boot())+ h.connects[1].resolve('c1')+ await flush()+ h.mounts[0].resolve({ projectId: 'proj-1' })+ await flush()+ expect(a.phase('H1')).toBe('live')+ a.cancelProject('proj-1')+ expect(a.phase('H1')).toBeNull()+ expect(a.phase('H2')).toBe('connecting')+ expect(h.ended).toEqual([]) // a closed tab is not a drop: nothing to reconnect+ })++ it('R40: a manual hurry that names no tab keeps the tab the waiting loop was reconnecting', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ reconnectProjectId: 'proj-1' }))+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))+ await flush()+ expect(a.run(boot({ manual: true, retry: false }))).toBe('started')+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[0].req.reconnectProjectId).toBe('proj-1')+ })})diff --git a/src/renderer/lib/hostedAttempts.ts b/src/renderer/lib/hostedAttempts.tsindex b9fcce261..a08d10044 100644--- a/src/renderer/lib/hostedAttempts.ts+++ b/src/renderer/lib/hostedAttempts.ts@@ -11,10 +11,14 @@//// Why only network failures retry (R35): every other code needs a person (a fresh code, an unlocked// keyring, an owner) or a new day, and a loop on one of them spends the team's damped device mints.+// A connection that drops before the host answered (a host restarting) is the one other retry, and+// it is BOUNDED (R40): the 1/2/4/8/15 s steps, then it stops and says so once — every try mints a+// join token and opens a relay socket. And no attempt outlives its tab: `wanted` is asked before+// every retry and before every mount, and closing the tab cancels the attempt in any phase.// Pure orchestration over injected deps, so every rule is testable without React or a relay.// See docs/hosted-team-relay.md.import type { RelayClosedReason } from '@shared/types'-import { classifyJoinFailure, reconnectDelayMs, type JoinFailure } from './hostedTeam'+import { classifyJoinFailure, DROP_RETRY_MAX, reconnectDelayMs, type JoinFailure } from './hostedTeam'export interface HostedAttemptRequest {hostId: string@@ -52,6 +56,12 @@ export interface HostedAttemptDeps {stopped(req: HostedAttemptRequest, failure: JoinFailure): void/** A live connection ended; `reason` is set only when the host refused this device. */ended(req: HostedAttemptRequest, projectId: string, reason?: RelayClosedReason): void+ /** An unattended attempt used up its retries for a drop the host did not explain (R40). Called+ * once; the team is released, and the next try is the user's. */+ exhausted(req: HostedAttemptRequest): void+ /** Is this attempt still wanted? Asked before every retry and before every mount — an attempt+ * reconnecting a tab that has since been closed or deleted must stop (R40). Default: yes. */+ wanted?(req: HostedAttemptRequest): booleansetTimer(fn: () => void, ms: number): unknownclearTimer(handle: unknown): void}@@ -64,6 +74,10 @@ export interface HostedAttempts {/** Stop a pending backoff or an in-flight connect for good. A connection already past its* connect (approval wait, live tab) is the user's and is left alone. */cancel(hostId: string): void+ /** The tab `projectId` was closed or deleted: every attempt for it stops in whatever phase it is+ * in, and its team's slot is free at once. A connection waiting for approval is closed; a live+ * one is the tab's own to close (its session teardown does), and is not reported as a drop. */+ cancelProject(projectId: string): void/** Stop everything (the canvas is going away). */dispose(): void}@@ -72,6 +86,8 @@ interface Entry {req: HostedAttemptRequestphase: HostedAttemptPhaseattempt: number+ /** Retries spent on drops the host did not explain (bounded by DROP_RETRY_MAX). */+ drops: numbertimer: unknownconnectionId: string | nullprojectId: string | null@@ -100,13 +116,25 @@ export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {if (projectId) deps.ended(e.req, projectId, reason)}- /** Back off, then try again (the 1/2/4/8/15/60 s ladder). */- const backOff = (e: Entry): void => {+ const wanted = (e: Entry): boolean => (deps.wanted ? deps.wanted(e.req) : true)++ /** Wait `ms`, then try again — unless the attempt was cancelled or is no longer wanted. */+ const retryAfter = (e: Entry, ms: number): void => {e.phase = 'waiting'e.timer = deps.setTimer(() => {e.timer = null- if (current(e)) attempt(e)- }, reconnectDelayMs(e.attempt))+ if (!current(e)) return+ if (!wanted(e)) {+ release(e)+ return+ }+ attempt(e)+ }, ms)+ }++ /** A network failure: the 1/2/4/8/15 s steps, then every 60 s (R35). */+ const backOff = (e: Entry): void => {+ retryAfter(e, reconnectDelayMs(e.attempt))e.attempt += 1}@@ -125,6 +153,12 @@ export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {deps.disconnect(connectionId)return}+ if (!wanted(e)) {+ // Its tab went away while it connected: never bind this connection to it.+ deps.disconnect(connectionId)+ release(e)+ return+ }e.phase = 'mounting'e.connectionId = connectionIde.unClose = deps.onClosed(connectionId, (reason) => {@@ -147,13 +181,25 @@ export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {e.unClose = nulle.connectionId = nulle.closedEarly = null- if ('retry' in result && result.retry && e.req.retry) backOff(e)- else release(e)+ if (!('retry' in result && result.retry && e.req.retry)) {+ release(e)+ return+ }+ // A drop before the host answered: worth a few quick tries (a host restarting), never+ // an open-ended loop — each try mints a join token and opens a socket (R40).+ if (e.drops >= DROP_RETRY_MAX) {+ release(e)+ deps.exhausted(e.req)+ return+ }+ retryAfter(e, reconnectDelayMs(e.drops))+ e.drops += 1return}const projectId = result.projectIde.projectId = projectIde.attempt = 0+ e.drops = 0if (e.closedEarly) {endLive(e, e.closedEarly.reason)return@@ -184,11 +230,16 @@ export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {// now, with the manual request's terms (it may name the tab to reconnect in place).deps.clearTimer(existing.timer)existing.timer = null- existing.req = req+ // A request that names no tab keeps the tab the loop was reconnecting: a pasted code must+ // not drop a greyed tab's binding and open a second one.+ existing.req =+ req.reconnectProjectId || !existing.req.reconnectProjectId+ ? req+ : { ...req, reconnectProjectId: existing.req.reconnectProjectId }attempt(existing)return 'started'}- const e: Entry = { req, phase: 'connecting', attempt: 0, timer: null, connectionId: null, projectId: null, unClose: null, closedEarly: null }+ const e: Entry = { req, phase: 'connecting', attempt: 0, drops: 0, timer: null, connectionId: null, projectId: null, unClose: null, closedEarly: null }entries.set(req.hostId, e)attempt(e)return 'started'@@ -203,6 +254,16 @@ export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {e.timer = nullrelease(e)},+ cancelProject(projectId) {+ for (const e of [...entries.values()]) {+ if (e.req.reconnectProjectId !== projectId && e.projectId !== projectId) continue+ if (e.timer !== null) deps.clearTimer(e.timer)+ e.timer = null+ // Waiting for approval: nobody will ever look at that tab, so the connection goes too.+ if (e.phase === 'mounting' && e.connectionId) deps.disconnect(e.connectionId)+ release(e)+ }+ },dispose() {disposed = truefor (const e of entries.values()) {diff --git a/src/renderer/lib/hostedJoin.test.ts b/src/renderer/lib/hostedJoin.test.tsindex 6f1a22667..3cb554ccc 100644--- a/src/renderer/lib/hostedJoin.test.ts+++ b/src/renderer/lib/hostedJoin.test.ts@@ -4,6 +4,7 @@ import { JOIN_CODE_PREFIX } from '@shared/relay-join-code'import { createHostedJoiner, type HostedJoinerDeps, type HostedMountOutcome, type HostedNotice } from './hostedJoin'import type { HostedAttemptRequest } from './hostedAttempts'import { RelayApprovalError } from './hostedTeam'+import { WAITING_NOTICE_DELAY_MS } from './hostedJoin'const wrap = (m: string) => new Error(`Error invoking remote method 'relay:client:connect': Error: ${m}`)const flush = async () => {@@ -20,8 +21,15 @@ function harness(bookmarks: Bookmark[] = []) {const notices: HostedNotice[] = []const timers: Array<{ fn: () => void; ms: number; cleared: boolean }> = []const open = new Set<string>()+ const approvedCbs = new Map<string, () => void>()+ const cleared: string[] = []let list = [...bookmarks]const deps: HostedJoinerDeps = {+ onApproved: (id, cb) => {+ approvedCbs.set(id, cb)+ return () => approvedCbs.delete(id)+ },+ clearNotice: (text) => cleared.push(text),connect: (code) => new Promise((resolve, reject) => connects.push({ code, resolve, reject })),onClosed: (id, cb) => {closeCbs.set(id, cb)@@ -45,7 +53,7 @@ function harness(bookmarks: Bookmark[] = []) {;(t as { cleared: boolean }).cleared = true}}- return { deps, connects, mounts, closeCbs, notices, timers, open, setList: (l: Bookmark[]) => { list = l } }+ return { deps, connects, mounts, closeCbs, notices, timers, open, approvedCbs, cleared, setList: (l: Bookmark[]) => { list = l } }}/** Connect + mount one attempt to a live tab. */@@ -87,6 +95,7 @@ describe('hosted joiner', () => {it('a code pasted into a greyed tab\'s prompt reconnects THAT tab (never a second one)', async () => {const h = harness()+ h.open.add('proj-7') // the greyed tab the prompt was raised onconst j = createHostedJoiner(h.deps)j.joinWithCode(codeFor('H1'), 'proj-7')h.connects[0].resolve('c0')@@ -271,4 +280,196 @@ describe('hosted joiner', () => {j.dispose()expect(h.timers.filter((t) => !t.cleared)).toHaveLength(0)})++ // ── R40 ─────────────────────────────────────────────────────────────────────────────────────────+ it('the waiting-notice delay is none of the retry ladder\'s steps (the helper below tells them apart by it)', () => {+ expect([1000, 2000, 4000, 8000, 15000, 60000]).not.toContain(WAITING_NOTICE_DELAY_MS)+ })++ /** Fire the newest armed timer that is not the waiting-notice one. */+ const fireRetry = (h: ReturnType<typeof harness>) => {+ const t = h.timers.filter((x) => !x.cleared && x.ms !== WAITING_NOTICE_DELAY_MS).pop()+ if (!t) throw new Error('no armed retry')+ t.cleared = true+ t.fn()+ }++ it('R40: a dropped tab that cannot come back gives up after 5 quick tries with ONE notice naming the team', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.closeCbs.get('c0')!(undefined) // the drop+ await flush()+ for (let i = 1; i <= 6; i++) {+ h.connects[i].resolve(`c${i}`)+ await flush()+ h.mounts[i].resolve({ error: new RelayApprovalError('The relay connection closed before it was approved.'), declined: false })+ await flush()+ if (i < 6) fireRetry(h)+ }+ expect(h.connects).toHaveLength(7) // the drop's reconnect + 5 retries+ expect(h.notices).toEqual([{ kind: 'error', text: "Couldn't reconnect to box. Click its tab to try again." }])+ expect(h.timers.filter((t) => !t.cleared && t.ms !== WAITING_NOTICE_DELAY_MS)).toEqual([])+ // The tab stays greyed and clickable: a click is a fresh try.+ expect(j.reconnectTab('proj-1')).toBe(true)+ expect(h.connects).toHaveLength(8)+ })++ it('R40: a boot reconnect that gives up (no tab yet) says how to try again', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ for (let i = 0; i <= 5; i++) {+ h.connects[i].resolve(`c${i}`)+ await flush()+ h.mounts[i].resolve({ error: new RelayApprovalError('closed'), declined: false })+ await flush()+ if (i < 5) fireRetry(h)+ }+ expect(h.notices).toEqual([{ kind: 'error', text: "Couldn't reconnect to box. Paste its invite code to try again." }])+ })++ it('R40: closing the tab while its reconnect backs off stops the loop — no further connect', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.closeCbs.get('c0')!(undefined)+ await flush()+ h.connects[1].reject(wrap('[E_JOIN_NETWORK] x'))+ await flush()+ j.tabClosed('proj-1')+ h.open.delete('proj-1')+ expect(h.timers.filter((t) => !t.cleared && t.ms !== WAITING_NOTICE_DELAY_MS)).toEqual([])+ await flush()+ expect(h.connects).toHaveLength(2)+ // The slot is free: a later paste is a fresh join, not "already connected".+ j.joinWithCode(codeFor('H1'))+ expect(h.connects).toHaveLength(3)+ expect(h.notices).toEqual([])+ })++ it('R40: deleting the tab while its connect is in flight: no mount, the connection closed, the slot released', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.closeCbs.get('c0')!(undefined)+ await flush()+ expect(h.connects).toHaveLength(2) // the in-place reconnect is connecting+ j.tabClosed('proj-1')+ h.open.delete('proj-1')+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts).toHaveLength(1) // only the first, long-gone mount+ expect(h.deps.disconnect).toHaveBeenCalledWith('c1')+ j.joinWithCode(codeFor('H1'))+ expect(h.connects).toHaveLength(3)+ })++ it('R40: a reconnect whose tab closed while it waited for approval ends silently (it was closed for it)', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.closeCbs.get('c0')!(undefined)+ await flush()+ h.connects[1].resolve('c1')+ await flush()+ j.tabClosed('proj-1')+ h.open.delete('proj-1')+ expect(h.deps.disconnect).toHaveBeenCalledWith('c1')+ h.mounts[1].resolve({ error: new Error('The tab this reconnect was for is gone.'), declined: false })+ await flush()+ expect(h.notices).toEqual([])+ expect(j.isHostedTab('proj-1')).toBe(false)+ })++ it('R40: after "forget", the greyed tab asks for a code instead of rejoining with the stored one', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ ;(h.deps.promptForCode as ReturnType<typeof vi.fn>).mockResolvedValue(codeFor('H1', 'box'))+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.setList([]) // no automatic reconnect after the drop+ h.closeCbs.get('c0')!(undefined)+ await flush()+ await j.forget('H1', 'box')+ expect(j.reconnectTab('proj-1')).toBe(true)+ expect(h.connects).toHaveLength(1) // nothing re-minted from the stored code+ await flush()+ expect(h.deps.promptForCode).toHaveBeenCalledWith('box')+ // The code the user pasted reconnects THAT tab.+ expect(h.connects).toHaveLength(2)+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[1].req).toMatchObject({ reconnectProjectId: 'proj-1', manual: true })+ })++ it('R40: a cancelled "Remove and rejoin" also leaves the tab asking for a code', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.setList([])+ h.closeCbs.get('c0')!(undefined)+ await flush()+ j.reconnectTab('proj-1')+ h.connects[1].reject(wrap("[E_JOIN_REVOKED] revoked"))+ await flush()+ h.notices.at(-1)!.action!.run() // promptForCode answers null: cancelled+ await flush()+ expect(h.deps.removeBookmark).toHaveBeenCalledWith('H1')+ ;(h.deps.promptForCode as ReturnType<typeof vi.fn>).mockClear()+ expect(j.reconnectTab('proj-1')).toBe(true)+ await flush()+ expect(h.deps.promptForCode).toHaveBeenCalledWith('box')+ expect(h.connects).toHaveLength(2)+ })++ it('R40: a code pasted for a team whose tab is greyed reconnects that tab, never a second one', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ await goLive(h, 0, 'proj-1')+ h.setList([])+ h.closeCbs.get('c0')!(undefined)+ await flush()+ j.joinWithCode(codeFor('H1'))+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[1].req.reconnectProjectId).toBe('proj-1')+ })++ it('R40: every hosted mount still waiting for approval says so after a moment — a bookmarked reconnect too', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ h.connects[0].resolve('c0')+ await flush()+ const wait = h.timers.find((t) => t.ms === WAITING_NOTICE_DELAY_MS && !t.cleared)!+ wait.cleared = true+ wait.fn()+ expect(h.notices).toEqual([{ kind: 'info', text: 'Waiting for an owner of box to approve this device…', sticky: true }])+ h.approvedCbs.get('c0')!()+ expect(h.cleared).toEqual(['Waiting for an owner of box to approve this device…'])+ h.mounts[0].resolve({ projectId: 'proj-1' })+ await flush()+ expect(h.approvedCbs.has('c0')).toBe(false) // unsubscribed once settled+ })++ it('R40: an approval that lands quickly never shows the waiting notice', async () => {+ const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])+ const j = createHostedJoiner(h.deps)+ await j.bootReconnect()+ h.connects[0].resolve('c0')+ await flush()+ h.approvedCbs.get('c0')!()+ h.mounts[0].resolve({ projectId: 'proj-1' })+ await flush()+ expect(h.timers.filter((t) => t.ms === WAITING_NOTICE_DELAY_MS).every((t) => t.cleared)).toBe(true)+ expect(h.notices).toEqual([])+ expect(h.cleared).toEqual([])+ })})diff --git a/src/renderer/lib/hostedJoin.ts b/src/renderer/lib/hostedJoin.tsindex 28f88ab3a..ea5278a44 100644--- a/src/renderer/lib/hostedJoin.ts+++ b/src/renderer/lib/hostedJoin.ts@@ -3,16 +3,32 @@// - a drop: a live hosted tab whose connection dropped (no host reason) reconnects in place, in the// background, while its team is still bookmarked and approved and the tab is still open;// - a click on the greyed tab: reconnects in place now (no pairing-code prompt — the bookmark is the-// credential);-// - a pasted join code: joins now, and is told why if it cannot;-// - forgetting a team: stops its loop and removes its bookmark (the host is not touched).-// And what the user is told for each: one sentence per stop, nothing for a retry in progress, a-// "remove and rejoin" offer after a revocation. Pure over injected deps (no React, no window).+// credential) — unless the team was forgotten since, and then it asks for a code;+// - a pasted join code: joins now, into the team's own tab when it has one, and is told why if it+// cannot;+// - forgetting a team: stops its loop and removes its bookmark (the host is not touched);+// - closing or deleting a tab: its team's attempt stops, in any phase (R40).+// And what the user is told for each: one sentence per stop, nothing for a retry in progress, one+// notice when the quick retries of a drop run out, a "remove and rejoin" offer after a revocation,+// and "waiting for an owner" whenever a mount is still unapproved after a moment. Pure over+// injected deps (no React, no window).// See docs/hosted-team-relay.md.import type { RelayClosedReason, RelayHostedApi } from '@shared/types'import { peekJoinCode } from '@shared/relay-join-code'import { createHostedAttempts, type HostedAttemptRequest, type HostedMountResult } from './hostedAttempts'-import { closedReasonMessage, joinStopMessage, mountFailureMessage, mountFailureRetries, stripIpcPrefix } from './hostedTeam'+import {+ closedReasonMessage,+ joinStopMessage,+ mountFailureMessage,+ mountFailureRetries,+ stripIpcPrefix,+ waitingForOwnerText+} from './hostedTeam'++/** How long a hosted mount waits for approval before it says it is waiting for an owner. A+ * bookmarked reconnect is normally approved well inside this, so it never flashes the notice; one+ * whose device the host no longer knows waits for an owner like a first join (R40). */+export const WAITING_NOTICE_DELAY_MS = 2500/** How a mount ended, as the canvas reports it: a live tab, or the error it failed with. `declined`* = this user declined the SAS themselves (nothing to tell them). */@@ -21,6 +37,8 @@ export type HostedMountOutcome = { projectId: string } | { error: unknown; decliexport interface HostedNotice {kind: 'info' | 'error'text: string+ /** Stays until cleared (the waiting-for-an-owner notice). */+ sticky?: booleanaction?: { label: string; run: () => void }}@@ -28,6 +46,9 @@ export interface HostedJoinerDeps {/** `relayClient.connect` — a join code in, a connection id out (or main's `[E_JOIN_…]` refusal). */connect(code: string): Promise<string>onClosed(connectionId: string, listener: (reason?: RelayClosedReason) => void): () => void+ /** Both humans approved this connection (`relayClient.onApproved`). */+ onApproved(connectionId: string, listener: () => void): () => void+ /** Close a connection this joiner no longer wants (it must also count as closed locally). */disconnect(connectionId: string): voidbookmarks: RelayHostedApi['bookmarks']removeBookmark: RelayHostedApi['removeBookmark']@@ -37,6 +58,8 @@ export interface HostedJoinerDeps {/** Is this project still an open tab (not closed, not deleted)? */tabOpen(projectId: string): booleannotify(notice: HostedNotice): void+ /** Take down the notice with this text, if it is still the one showing. */+ clearNotice(text: string): void/** Ask the user for a fresh invite code for `teamLabel`; null = cancelled. */promptForCode(teamLabel: string): Promise<string | null>setTimer(fn: () => void, ms: number): unknown@@ -51,6 +74,8 @@ export interface HostedJoiner {* takes its pairing-code path). */reconnectTab(projectId: string): booleanisHostedTab(projectId: string): boolean+ /** The user closed or deleted this tab: its team's attempt stops now, in any phase (R40). */+ tabClosed(projectId: string): void/** Reconnect every approved bookmark (once, at boot). */bootReconnect(): Promise<void>/** Forget a team: its loop stops and its bookmark goes. Refused while it is connecting. */@@ -63,28 +88,74 @@ export interface HostedJoiner {const team = (label: string): string => label.trim() || 'the team'export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {- /** The team each hosted tab this joiner opened belongs to, by project id. */- const tabs = new Map<string, { hostId: string; code: string; label: string }>()+ /** The team each hosted tab this joiner opened belongs to, by project id. `forgotten` = the user+ * forgot that team since: the tab asks for a code rather than rejoin with the stored one (which+ * would mint a fresh device token and bring the bookmark back). */+ const tabs = new Map<string, { hostId: string; code: string; label: string; forgotten?: boolean }>()let run: (req: HostedAttemptRequest) => 'started' | 'busy' = () => 'busy'+ /** A reconnect is wanted only while the tab it reconnects is still open (R40). */+ const tabWanted = (req: HostedAttemptRequest): boolean => !req.reconnectProjectId || deps.tabOpen(req.reconnectProjectId)++ /** An open tab this joiner opened for `hostId`, if any. */+ const tabFor = (hostId: string): string | undefined => {+ for (const [projectId, t] of tabs) if (t.hostId === hostId && deps.tabOpen(projectId)) return projectId+ return undefined+ }++ const markForgotten = (hostId: string): void => {+ for (const [projectId, t] of tabs) if (t.hostId === hostId) tabs.set(projectId, { ...t, forgotten: true })+ }+const attempts = createHostedAttempts({connect: deps.connect,onClosed: deps.onClosed,disconnect: deps.disconnect,setTimer: deps.setTimer,clearTimer: deps.clearTimer,+ wanted: tabWanted,+ exhausted(req) {+ deps.notify({+ kind: 'error',+ text: req.reconnectProjectId+ ? `Couldn't reconnect to ${team(req.label)}. Click its tab to try again.`+ : `Couldn't reconnect to ${team(req.label)}. Paste its invite code to try again.`+ })+ },async mount(connectionId, req): Promise<HostedMountResult> {+ // Any hosted mount still waiting for approval after a moment says so — a first join and a+ // bookmarked reconnect alike (the host may no longer know this device and ask an owner).+ const waiting = waitingForOwnerText(req.label)+ let approved = false+ let shown = false+ const unApproved = deps.onApproved(connectionId, () => {+ approved = true+ if (shown) {+ shown = false+ deps.clearNotice(waiting)+ }+ })+ const waitTimer = deps.setTimer(() => {+ if (approved) return+ shown = true+ deps.notify({ kind: 'info', text: waiting, sticky: true })+ }, WAITING_NOTICE_DELAY_MS)let outcome: HostedMountOutcometry {outcome = await deps.mount(connectionId, req)} catch (error) {outcome = { error, declined: false }+ } finally {+ deps.clearTimer(waitTimer)+ unApproved()+ if (shown) deps.clearNotice(waiting)}if ('projectId' in outcome) {tabs.set(outcome.projectId, { hostId: req.hostId, code: req.code, label: req.label })return { projectId: outcome.projectId }}- if (outcome.declined) return { retry: false }+ // Declined by this user, or its tab was closed meanwhile (closed for it): nothing to say.+ if (outcome.declined || !tabWanted(req)) return { retry: false }const retry = mountFailureRetries(outcome.error)// An unattended attempt that will try again says nothing; the next one may well work.if (retry && req.retry) return { retry: true }@@ -133,8 +204,10 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {deps.notify({ kind: 'error', text: `Could not forget ${team(req.label)}: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}` })return}+ // Gone from this device now, whether or not a fresh code follows: its tab asks for one.+ markForgotten(req.hostId)const code = (await deps.promptForCode(req.label))?.trim()- if (code) joiner.joinWithCode(code)+ if (code) joiner.joinWithCode(code, req.reconnectProjectId)}const joiner: HostedJoiner = {@@ -145,7 +218,10 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {// this one; its key is the text itself, so a double paste of it is still one attempt.const hostId = peek?.hostId ?? `unreadable:${code}`const label = peek?.label ?? ''- const req: HostedAttemptRequest = { hostId, code, label, manual: true, retry: false, ...(reconnectProjectId ? { reconnectProjectId } : {}) }+ // The team's own tab, when it has one open (greyed or not), is the one this code is for: a+ // greyed tab reconnects in place, a live one answers "already connected" — never a second tab.+ const target = reconnectProjectId ?? tabFor(hostId)+ const req: HostedAttemptRequest = { hostId, code, label, manual: true, retry: false, ...(target ? { reconnectProjectId: target } : {}) }if (run(req) === 'busy') {deps.notify({ kind: 'info', text: busyText(hostId, label) })}@@ -153,7 +229,18 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {reconnectTab(projectId) {const t = tabs.get(projectId)if (!t) return false- if (run({ ...t, manual: true, retry: true, reconnectProjectId: projectId }) === 'busy') {+ if (t.forgotten) {+ // Forgotten: no stored code to rejoin with — ask, as the forget dialog promised.+ void deps.promptForCode(t.label).then(+ (code) => {+ const c = code?.trim()+ if (c) joiner.joinWithCode(c, projectId)+ },+ () => {}+ )+ return true+ }+ if (run({ hostId: t.hostId, code: t.code, label: t.label, manual: true, retry: true, reconnectProjectId: projectId }) === 'busy') {deps.notify({ kind: 'info', text: `Already reconnecting to ${team(t.label)}…` })}return true@@ -161,6 +248,10 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {isHostedTab(projectId) {return tabs.has(projectId)},+ tabClosed(projectId) {+ tabs.delete(projectId)+ attempts.cancelProject(projectId)+ },async bootReconnect() {const list = await deps.bookmarks().catch(() => [])for (const b of list) {@@ -179,6 +270,7 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {deps.notify({ kind: 'error', text: `Could not forget ${team(label)}: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}` })return}+ markForgotten(hostId)deps.notify({ kind: 'info', text: `Forgot ${team(label)}. This device will not reconnect to it.` })},connecting(hostId) {diff --git a/src/renderer/lib/hostedOwner.test.ts b/src/renderer/lib/hostedOwner.test.tsindex 5775ae86e..bd02e7b0f 100644--- a/src/renderer/lib/hostedOwner.test.ts+++ b/src/renderer/lib/hostedOwner.test.ts@@ -84,22 +84,42 @@ describe('attachHostedOwner (R25)', () => {describe('answerHostedRequest', () => {const item = (hosted: HostedSessionApi): QueuedRequest => ({ projectId: 'p1', teamLabel: 'box', pending: P('x'), answerer: hosted })+ const ledger = () => {+ const log: string[] = []+ return { log, begin: (id: string) => log.push(`begin:${id}`), finish: (id: string, landed: boolean) => log.push(`finish:${id}:${landed}`) }+ }++ it('R40: settles only once the host ANSWERED (true or false); a rejection leaves the request answerable', async () => {+ const f = fakeHosted()+ const ok = ledger()+ await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'viewer' }, ok)+ expect(ok.log).toEqual(['begin:x', 'finish:x:true'])+ ;(f.hosted.deny as ReturnType<typeof vi.fn>).mockResolvedValue(false)+ const gone = ledger()+ await answerHostedRequest(item(f.hosted), { kind: 'deny' }, gone)+ expect(gone.log).toEqual(['begin:x', 'finish:x:true'])+ ;(f.hosted.approve as ReturnType<typeof vi.fn>).mockRejectedValue(Object.assign(new Error('The connection to the server was lost.'), { code: 'E_DISCONNECTED' }))+ const dropped = ledger()+ const line = await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'viewer' }, dropped)+ expect(dropped.log).toEqual(['begin:x', 'finish:x:false'])+ expect(line?.kind).toBe('error')+ })it('approves with the chosen role and says nothing when it landed', async () => {const f = fakeHosted()- expect(await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'commenter' })).toBeNull()+ expect(await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'commenter' }, ledger())).toBeNull()expect(f.hosted.approve).toHaveBeenCalledWith('x', 'commenter')})it('a false answer means another owner (or the device leaving) got there first', async () => {const f = fakeHosted();(f.hosted.deny as ReturnType<typeof vi.fn>).mockResolvedValue(false)- expect(await answerHostedRequest(item(f.hosted), { kind: 'deny' })).toEqual({ kind: 'info', text: 'That request was already answered or has gone.' })+ expect(await answerHostedRequest(item(f.hosted), { kind: 'deny' }, ledger())).toEqual({ kind: 'info', text: 'That request was already answered or has gone.' })})it('a refused answer says so, in the host\'s words', async () => {const f = fakeHosted();(f.hosted.approve as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('Only an owner can approve.'))- expect(await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'viewer' })).toEqual({ kind: 'error', text: 'Could not answer the request: Only an owner can approve.' })+ expect(await answerHostedRequest(item(f.hosted), { kind: 'approve', role: 'viewer' }, ledger())).toEqual({ kind: 'error', text: 'Could not answer the request: Only an owner can approve.' })})})diff --git a/src/renderer/lib/hostedOwner.ts b/src/renderer/lib/hostedOwner.tsindex c3359b902..dc7ac59f7 100644--- a/src/renderer/lib/hostedOwner.ts+++ b/src/renderer/lib/hostedOwner.ts@@ -48,17 +48,30 @@ export function attachHostedOwner(export type HostedAnswer = { kind: 'approve'; role: HostedRole } | { kind: 'deny' }-/** Send an owner's answer. Resolves with the line to show the owner, or null when it landed. */+/** Where an answer's progress is recorded (the queue store's `beginAnswer` / `finishAnswer`). */+export interface AnswerLedger {+ begin(pendingId: string): void+ /** `landed` = the host answered (true or false); false = it never did. */+ finish(pendingId: string, landed: boolean): void+}++/** Send an owner's answer. The request leaves the screen at once, and is settled only if the host+ * ANSWERED (true or false) — an answer that never landed leaves it answerable (R40). Resolves with+ * the line to show the owner, or null when it landed. */export async function answerHostedRequest(item: QueuedRequest,- answer: HostedAnswer+ answer: HostedAnswer,+ ledger: AnswerLedger): Promise<{ kind: 'info' | 'error'; text: string } | null> {const id = item.pending.pendingId+ ledger.begin(id)try {const ok = answer.kind === 'approve' ? await item.answerer.approve(id, answer.role) : await item.answerer.deny(id)+ ledger.finish(id, true)// False is an answer, not a failure: another owner got there first, or the device left.return ok ? null : { kind: 'info', text: 'That request was already answered or has gone.' }} catch (err) {+ ledger.finish(id, false)return { kind: 'error', text: `Could not answer the request: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}` }}}diff --git a/src/renderer/lib/hostedPendingQueue.test.ts b/src/renderer/lib/hostedPendingQueue.test.tsindex 011bbf12b..5fdb301c4 100644--- a/src/renderer/lib/hostedPendingQueue.test.ts+++ b/src/renderer/lib/hostedPendingQueue.test.ts@@ -6,6 +6,8 @@ import {settleRequest,dropProjectRequests,headRequest,+ beginAnswer,+ finishAnswer,SETTLED_MEMORY,type QueuedRequest} from './hostedPendingQueue'@@ -89,4 +91,21 @@ describe('hosted pending queue (R37)', () => {expect(addRequest(EMPTY_PENDING_QUEUE, { ...req('a', 1), pending: bad as never }).items).toEqual([])}})++ it('R40: an answer in flight leaves the screen and cannot be re-added; one that LANDED is settled for good', () => {+ let q = addRequest(addRequest(EMPTY_PENDING_QUEUE, req('a', 10)), req('b', 20))+ q = beginAnswer(q, 'a')+ expect(headRequest(q)?.pending.pendingId).toBe('b')+ expect(addRequest(q, req('a', 10)).items.map((i) => i.pending.pendingId)).toEqual(['b']) // a replay mid-flight+ q = finishAnswer(q, 'a', true)+ expect(addRequest(q, req('a', 10)).items.map((i) => i.pending.pendingId)).toEqual(['b'])+ })++ it('R40: an answer that never landed (the tab dropped) stays answerable — the reconnect\'s pull brings it back', () => {+ let q = addRequest(EMPTY_PENDING_QUEUE, req('a', 10))+ q = beginAnswer(q, 'a')+ q = finishAnswer(q, 'a', false)+ expect(q.settled).not.toContain('a')+ expect(addRequest(q, req('a', 10)).items.map((i) => i.pending.pendingId)).toEqual(['a'])+ })})diff --git a/src/renderer/lib/hostedPendingQueue.ts b/src/renderer/lib/hostedPendingQueue.tsindex 7f965b1eb..02ccbc79d 100644--- a/src/renderer/lib/hostedPendingQueue.ts+++ b/src/renderer/lib/hostedPendingQueue.ts@@ -25,9 +25,12 @@ export interface PendingQueue {/** Requests already answered here or closed at the host, most recent last: a late replay or pull* of one must not bring its dialog back. */settled: readonly string[]+ /** Requests whose answer is on its way: off the screen, and not re-added by a replay meanwhile.+ * Settled only once the host answers; an answer that never landed leaves them answerable. */+ answering?: readonly string[]}-export const EMPTY_PENDING_QUEUE: PendingQueue = Object.freeze({ items: [], settled: [] })+export const EMPTY_PENDING_QUEUE: PendingQueue = Object.freeze({ items: [], settled: [], answering: [] })/** How many closed request ids are remembered (4× the host's concurrent cap). */export const SETTLED_MEMORY = 64@@ -54,7 +57,7 @@ const remember = (settled: readonly string[], id: string): string[] =>export function addRequest(q: PendingQueue, item: QueuedRequest): PendingQueue {if (!wellFormed(item.pending)) return qconst id = item.pending.pendingId- if (q.settled.includes(id) || q.items.some((i) => i.pending.pendingId === id)) return q+ if (q.settled.includes(id) || (q.answering ?? []).includes(id) || q.items.some((i) => i.pending.pendingId === id)) return qconst at = q.items.findIndex((i) => i.pending.since > item.pending.since)const items = at < 0 ? [...q.items, item] : [...q.items.slice(0, at), item, ...q.items.slice(at)]return { ...q, items }@@ -70,14 +73,37 @@ export function closeRequest(const wasHead = headRequest(q)?.pending.pendingId === pendingIdconst queue: PendingQueue = {items: q.items.filter((i) => i.pending.pendingId !== pendingId),- settled: remember(q.settled, pendingId)+ settled: remember(q.settled, pendingId),+ answering: (q.answering ?? []).filter((x) => x !== pendingId)}return { queue, notice: wasHead ? pendingClosedNotice(reason) : null }}-/** This owner answered a request: it leaves the queue now (the host's own close follows). */+/** Remember a request as answered for good (the host's own close follows). */export function settleRequest(q: PendingQueue, pendingId: string): PendingQueue {- return { items: q.items.filter((i) => i.pending.pendingId !== pendingId), settled: remember(q.settled, pendingId) }+ return {+ items: q.items.filter((i) => i.pending.pendingId !== pendingId),+ settled: remember(q.settled, pendingId),+ answering: (q.answering ?? []).filter((x) => x !== pendingId)+ }+}++/** This owner answered: the request leaves the screen now, and a replay cannot bring it back while+ * the answer is on its way. */+export function beginAnswer(q: PendingQueue, pendingId: string): PendingQueue {+ return {+ ...q,+ items: q.items.filter((i) => i.pending.pendingId !== pendingId),+ answering: [...(q.answering ?? []).filter((x) => x !== pendingId), pendingId]+ }+}++/** The answer came back. `landed` (the host said true or false) settles it; an answer that never+ * landed (the tab dropped, the call failed) leaves it answerable: the reconnect's pull brings the+ * request back if it is still pending (R40). */+export function finishAnswer(q: PendingQueue, pendingId: string, landed: boolean): PendingQueue {+ if (landed) return settleRequest(q, pendingId)+ return { ...q, answering: (q.answering ?? []).filter((x) => x !== pendingId) }}/** The owner's tab went away (dropped, closed): its requests leave the queue unanswered — itsdiff --git a/src/renderer/lib/hostedTeam.ts b/src/renderer/lib/hostedTeam.tsindex 892e34e47..480631b84 100644--- a/src/renderer/lib/hostedTeam.ts+++ b/src/renderer/lib/hostedTeam.ts@@ -11,6 +11,12 @@ export function reconnectDelayMs(attempt: number): number {return attempt < BACKOFF.length ? BACKOFF[attempt] : 60_000}+/** How many times an unattended attempt retries a connection that dropped before the host answered+ * (a host restarting): the short steps of the ladder, 1/2/4/8/15 s, and then it stops and says so+ * (R40). Each try mints a join token and opens a relay socket, so this one is bounded — unlike a+ * network failure, which keeps the 60 s tail (R35). */+export const DROP_RETRY_MAX = 5+/** The sentence for a close the HOST explained (it refused this device), or null for a close it did* not — only reasons the host actually sent are named, never a guessed cause. */export function closedReasonMessage(reason?: string): string | null {diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.tsindex 7b2c4dcb1..c232398d5 100644--- a/src/renderer/session/relay-tab.test.ts+++ b/src/renderer/session/relay-tab.test.ts@@ -475,6 +475,22 @@ describe('openRelayTab — hosted team tabs', () => {await expect(bootstrap).rejects.toThrow(/^The relay connection closed before it was approved\.$/)})+ it('R40: a hosted reconnect whose tab closed meanwhile never binds to it: no owner subscription, no role, closed', async () => {+ const h = fakeHostedApi({ role: 'owner', label: 'me', hostLabel: 'box' }, [])+ const close = vi.fn()+ const handle: RelayApiHandle = { api: h.api, ready: () => Promise.resolve(), close, setHostedRole: vi.fn() }+ const { deps } = makeDeps({ handle })+ const gone = () => {+ throw new Error('The tab this reconnect was for is closed.')+ }+ await expect(openRelayTab('conn-gone', 'box', { ...deps, addProject: gone, adoptProject: undefined })).rejects.toThrow(/closed/)+ expect(h.log).not.toContain('sub:pending')+ expect(h.log).not.toContain('pending')+ expect(useHostedTeams.getState().bySession).toEqual({})+ expect(close).toHaveBeenCalledTimes(1)+ expect(sessionCount()).toBe(1) // only the local session+ })+it('a background reconnect binds the tab without switching to it (activate: false)', async () => {const h = fakeHostedApi({ role: 'editor', label: '', hostLabel: 'box' })const handle: RelayApiHandle = { api: h.api, ready: () => Promise.resolve(), close: vi.fn(), setHostedRole: vi.fn() }diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.tsindex 72a9e0db2..8f865fac4 100644--- a/src/renderer/session/relay-tab.ts+++ b/src/renderer/session/relay-tab.ts@@ -156,6 +156,7 @@ export async function openRelayTab(}} catch (err) {disposeSession(session.id)+ if (hostedInfo) useHostedTeams.getState().forget(session.id)throw err}}diff --git a/src/renderer/state/hostedPending.ts b/src/renderer/state/hostedPending.tsindex 1b06e7fd1..8df24680e 100644--- a/src/renderer/state/hostedPending.ts+++ b/src/renderer/state/hostedPending.ts@@ -3,7 +3,9 @@ import type { HostedPendingClosedReason } from '@shared/types'import {EMPTY_PENDING_QUEUE,addRequest,+ beginAnswer,closeRequest,+ finishAnswer,dropProjectRequests,settleRequest,type PendingQueue,@@ -23,6 +25,10 @@ interface HostedPendingStore {add: (item: QueuedRequest) => voidclose: (pendingId: string, reason: HostedPendingClosedReason) => voidsettle: (pendingId: string) => void+ /** An answer is on its way (off the screen, not re-added by a replay). */+ beginAnswer: (pendingId: string) => void+ /** It came back; `landed` settles it, otherwise it stays answerable. */+ finishAnswer: (pendingId: string, landed: boolean) => voiddrop: (projectId: string) => void}@@ -39,6 +45,8 @@ export const useHostedPending = create<HostedPendingStore>((set) => ({return r.notice ? { queue: r.queue, notice: { seq: (s.notice?.seq ?? 0) + 1, text: r.notice } } : { queue: r.queue }}),settle: (pendingId) => set((s) => ({ queue: settleRequest(s.queue, pendingId) })),+ beginAnswer: (pendingId) => set((s) => ({ queue: beginAnswer(s.queue, pendingId) })),+ finishAnswer: (pendingId, landed) => set((s) => ({ queue: finishAnswer(s.queue, pendingId, landed) })),drop: (projectId) => set((s) => {const queue = dropProjectRequests(s.queue, projectId)return queue === s.queue ? s : { queue }