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
feat(relay): one hosted tab per shared project, opened and closed live on share changes
review928956784f5e
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 4b531bde3..9e713ffa3 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -79,7 +79,7 @@ import {useSharedGlyphActive} from './SharedGlyphLayer'import { SshReconnector } from '../lib/sshReconnect'-import { projectMayDialSsh, receivedCanvasMutation } from '../session/relay-ssh'+import { projectMayDialSsh, receivedCanvasMutation, sanitizeRelayProject } from '../session/relay-ssh'import {hostAttachmentsFor,planActiveProjectDials,@@ -563,6 +563,10 @@ import {presenceForProject,setActiveSession,disposeSession,+ holdSessionTeardown,+ projectIdsBoundToSession,+ unbindProject,+ bindProjectToSession,} from '../session/session'import {openRelayTab,@@ -574,6 +578,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 { createTeamTabs, openSuccessor, type TeamTabs } from '../lib/hostedTeamTabs'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'@@ -893,6 +898,18 @@ 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+/** How a hosted team's connection mounts (see `mountRemoteMirror`). */+interface HostedMountOpts {+ /** Switch to the team's tab once it is live (a reconnect nobody asked for does not). */+ activate: boolean+ /** This user confirmed the SAS: the owner's approval wait starts now. */+ onSasConfirmed?: () => void+ /** The team, for its tabs (one per project it shares). */+ hostId: string+ /** The tab to land on when the mount takes the screen, when it is among the placed ones. */+ focusProjectId?: string+}+/** 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)@@ -1529,6 +1546,35 @@ export function Canvas() {// 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)+ // One tab per shared project of a hosted team (lib/hostedTeamTabs.ts); store ops only — the relay+ // binding and the joiner bookkeeping stay here. Built once (the model holds every team's tab set,+ // and Canvas renders far too often to rebuild it each time).+ const [teamTabs] = useState<TeamTabs>(() => {+ const tabs: TeamTabs = createTeamTabs({+ getProject: (id) => useProjects.getState().getProject(id),+ isOpenTab,+ adoptProject: (p) => useProjects.getState().adoptProject(p),+ addPlaceholder: (label) => useProjects.getState().addProject(label),+ // The STORE delete, never Canvas's `deleteProject` (which ends the host's sessions through+ // the relay transport): a hosted tab leaves this desktop only. The store hands the active+ // slot to whichever project slides into it, closed or not; the user lands on an open tab+ // instead, another of the same team's when it has one.+ removeTab: (id, hostId) => {+ const store = useProjects.getState()+ const index = store.projects.findIndex((p) => p.id === id)+ if (index < 0) return+ const wasActive = store.activeProjectId === id+ const next = store.deleteProject(id)+ if (!wasActive || isOpenTab(next)) return+ store.setActive(openSuccessor(useProjects.getState().projects, index, (other) => tabs.teamOf(other) === hostId))+ },+ activeProjectId: () => useProjects.getState().activeProjectId ?? null,+ setActive: (id) => useProjects.getState().setActive(id),+ bind: (projectId, sessionId) => bindProjectToSession(projectId, sessionId),+ unbind: (projectId) => unbindProject(projectId)+ })+ return tabs+ })// 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@@ -1541,17 +1587,27 @@ 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) => {+ // One of a hosted team's several tabs: dismiss just this one. The team's connection lives on+ // for the others (and the joiner keeps reconnecting into one that is still open).+ const { remaining } = teamTabs.closeTab(projectId)+ if (remaining.length > 0) {+ hostedJoinerRef.current?.tabRemoved(projectId, remaining[0])+ return+ }// A hosted tab's team stops trying to come back into it, in any phase (R40). A no-op otherwise.hostedJoinerRef.current?.tabClosed(projectId)+ const s = sessionForProject(projectId)for (const [connectionId, tab] of relayTabsRef.current) {- if (tab.projectId === projectId) relayTabsRef.current.delete(connectionId)+ // By session too: a team's last tab may be one a share event opened after the mount.+ if (tab.projectIds.includes(projectId) || (s.source === 'relay' && tab.sessionId === s.id)) {+ relayTabsRef.current.delete(connectionId)+ }}- const s = sessionForProject(projectId)if (s.source === 'relay') {disposeSession(s.id)useHostedTeams.getState().forget(s.id) // a no-op for a Team Access relay tab}- }, [])+ }, [teamTabs])const [remoteDialogOpen, setRemoteDialogOpen] = useState(false)// "Connect over SSH…" project-creation dialog (from the Welcome screen).const [sshDialogOpen, setSshDialogOpen] = useState(false)@@ -5105,6 +5161,8 @@ export function Canvas() {// `hosted` (a hosted team's join code): build the tab with its hosted api, wait up to the host's// own ten-minute pending window for an owner, switch to it only when asked, and hand a failure// back to the caller (the hosted joiner decides whether to retry or say so) instead of alerting.+ // A hosted team's one connection serves one tab per project it shares (`teamTabs`), and follows+ // the host's share changes for as long as it lives.// Absent = a pairing offer, exactly as before. Resolves with the outcome only for `hosted`.const mountRemoteMirror = useCallback((@@ -5112,7 +5170,7 @@ export function Canvas() {label = 'Remote host',reconnectProjectId?: string,staleSessionId?: string,- hosted?: { activate: boolean; onSasConfirmed?: () => void }+ hosted?: HostedMountOpts): Promise<HostedMountOutcome | null> => {if (relayTabsRef.current.has(connectionId)) return Promise.resolve(null)return openRelayTab(connectionId, label, {@@ -5133,10 +5191,33 @@ export function Canvas() {? undefined: (p) => useProjects.getState().adoptProject(p),setActiveProject: (id) => useProjects.getState().setActive(id),- ...(hosted ? { hosted: true, timeoutMs: HOSTED_APPROVAL_WAIT_MS, activate: hosted.activate } : {}),+ ...(hosted+ ? {+ hosted: true,+ timeoutMs: HOSTED_APPROVAL_WAIT_MS,+ activate: hosted.activate,+ // One tab per project the team shares, under the host's own ids. A reconnect reuses+ // the tabs the stale (offline) session still holds, greyed, by id.+ placeProjects: (projects: Project[]) => {+ const existing = staleSessionId ? projectIdsBoundToSession(staleSessionId) : []+ // A reconnect whose team tabs were ALL closed meanwhile must not bring them back (R40).+ if (reconnectProjectId && !existing.some((id) => isOpenTab(id))) {+ throw new Error('The tab this reconnect was for is closed.')+ }+ return teamTabs.place({ hostId: hosted.hostId, label }, projects, existing, {+ keepActive: !hosted.activate+ })+ },+ ...(hosted.focusProjectId ? { focusProjectId: hosted.focusProjectId } : {}),+ }+ : {}),}).then((tab): HostedMountOutcome | null => {relayTabsRef.current.set(connectionId, tab)+ // The session's api, read ONCE while the mount's tab is surely bound to it: a share event+ // may close that tab later, and resolving through it then would answer the local session.+ const bound = sessionForProject(tab.projectId)+ const api = bound.id === tab.sessionId ? bound.api : nullif (reconnectProjectId) {// The fresh session is now bound to the tab (openRelayTab rebound the SAME project id),// so it is finally safe to drop the stale offline session it replaced. Disposing only@@ -5146,12 +5227,12 @@ export function Canvas() {disposeSession(staleSessionId)if (hosted) useHostedTeams.getState().forget(staleSessionId)}- // Back online: un-grey the reused tab.- useProjects.getState().setProjectUnavailable(reconnectProjectId, false)+ // Back online: un-grey every tab the connection serves (a hosted team's are several).+ for (const id of tab.projectIds) useProjects.getState().setProjectUnavailable(id, false)}- // A background (unrequested) reconnect did not switch tabs — but if its tab is the one on- // screen, the active session must follow the rebind (disposing the stale one reset it).- if (hosted && !hosted.activate && useProjects.getState().activeProjectId === tab.projectId) {+ // A background (unrequested) reconnect did not switch tabs — but if one of its tabs is+ // on screen, the active session must follow the rebind (disposing the stale one reset it).+ if (hosted && !hosted.activate && tab.projectIds.includes(useProjects.getState().activeProjectId)) {setActiveSession(tab.sessionId)}// A host/relay drop AFTER approval is INVOLUNTARY (not a user close): grey the tab to@@ -5164,7 +5245,52 @@ export function Canvas() {setProjectUnavailable: (id, v) => useProjects.getState().setProjectUnavailable(id, v),})})- return hosted ? { projectId: tab.projectId } : null+ // A hosted team follows the host's share changes while this connection lives: a project+ // it stops sharing loses its tab, a newly shared one gains one (without taking the screen).+ // Held by the session, so the subscription ends with it (a drop, a close).+ if (hosted && api?.hosted) {+ const hostId = hosted.hostId+ const teamTabIds = (): string[] =>+ useProjects+ .getState()+ .projects.filter((x) => !x.closed && teamTabs.teamOf(x.id) === hostId)+ .map((x) => x.id)+ const off = api.hosted.onSharedChanged((p) => {+ const ids = Array.isArray(p?.projectIds) ? p.projectIds : []+ // What the event changed is read back from the store once it settles. It can reject+ // (the load failed, the session went away mid-load) and still have closed tabs, so+ // its resolved value alone does not say what the joiner must follow.+ const before = teamTabIds()+ void teamTabs+ .sharedChanged(+ { hostId, label, sessionId: tab.sessionId },+ ids,+ async () => (await api.workspace.load()).projects.map(sanitizeRelayProject),+ { keepActive: true }+ )+ .catch(() => {}) // never the user's error: the tabs that stand are in the store+ .then(() => {+ const joiner = hostedJoinerRef.current+ if (!joiner) return+ const after = teamTabIds()+ const opened = after.filter((id) => !before.includes(id))+ if (opened.length) joiner.tabsAdded(hostId, opened)+ for (const id of before) {+ if (after.includes(id)) continue+ // The team lives on in its other tabs. With none left its session is gone (the+ // model always keeps a placeholder otherwise), and so is the attempt.+ if (after.length) joiner.tabRemoved(id, after[0])+ else joiner.tabClosed(id)+ }+ })+ })+ try {+ holdSessionTeardown(tab.sessionId, off)+ } catch {+ off() // the session is already gone: nothing to follow+ }+ }+ return hosted ? { projectId: tab.projectId, projectIds: tab.projectIds } : null}).catch((err): HostedMountOutcome | null => {// A user who declined the SAS triggered this close themselves — don't cry error.@@ -5175,7 +5301,7 @@ export function Canvas() {return null})},- []+ [teamTabs])// Surface the SAS so this human can verify it matches the host's before confirming (the@@ -5189,7 +5315,7 @@ export function Canvas() {label: string,reconnectProjectId?: string,staleSessionId?: string,- hosted?: { activate: boolean; onSasConfirmed?: () => void }+ hosted?: HostedMountOpts): Promise<HostedMountOutcome | null> => {const unSas = window.nodeTerminal.relayClient.onSas(connectionId, (sas) => {unSas()@@ -5250,8 +5376,15 @@ export function Canvas() {req.label || 'Hosted team',req.reconnectProjectId,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, onSasConfirmed: hooks.sasConfirmed }+ {+ // Only a reconnect the user asked for takes the screen (or one with nothing on it).+ activate: req.manual || !useProjects.getState().activeProjectId,+ onSasConfirmed: hooks.sasConfirmed,+ hostId: req.hostId,+ // Where it lands when it does: the project just shared, else the tab a reconnect is for+ // (a click on one of a team's greyed tabs keeps the user on that tab).+ focusProjectId: req.focusProjectId ?? req.reconnectProjectId+ }).then((o): HostedMountOutcome => o ?? { error: new Error('That connection is already open.'), declined: true })},tabOpen: isOpenTab,@@ -5269,6 +5402,13 @@ export function Canvas() {}}, [confirmAndMount])+ // The share flow's join: a team this desktop just set up over ssh, whose bookmark it seeded+ // pre-approved. Through the team's one attempt owner (retrying while the relay comes up, with no+ // SAS), landing on the project that was shared.+ const joinApprovedTeam = useCallback((code: string, focusProjectId?: string) => {+ hostedJoinerRef.current?.joinApproved(code, focusProjectId ? { focusProjectId } : undefined)+ }, [])+// Connect to a host from an already-collected pairing offer: open the relay socket, then run the// shared SAS-compare + mount flow. The SINGLE place `relayClient.connect` + `confirmAndMount` live,// so every entry (dock/palette prompt below, and the Settings/tab-menu dialogs via thediff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.tsindex aaea5be76..416b23925 100644--- a/src/renderer/canvas/hosted-team.source.test.ts+++ b/src/renderer/canvas/hosted-team.source.test.ts@@ -50,11 +50,64 @@ describe('hosted team glue in Canvas', () => {it('the relay tab is built with hosted options, a long approval wait and no alert ONLY when hosted', () => {const body = between('const mountRemoteMirror = useCallback(', 'const confirmAndMount = useCallback(')- expect(body).toContain('...(hosted ? { hosted: true, timeoutMs: HOSTED_APPROVAL_WAIT_MS, activate: hosted.activate } : {})')+ const opts = between(' ...(hosted\n ? {\n hosted: true,', ' : {}),')+ expect(opts).toContain('timeoutMs: HOSTED_APPROVAL_WAIT_MS,')+ expect(opts).toContain('activate: hosted.activate,')+ expect(body).toContain(opts)expect(body).toContain('if (hosted) return { error: err, declined }')expect(body).toContain("window.alert(`Remote session did not open: ${(err as Error).message}`)")})+ it('a hosted team places one tab per shared project; a reconnect reuses the stale session\'s tabs', () => {+ const opts = between(' ...(hosted\n ? {\n hosted: true,', ' : {}),')+ expect(opts).toContain('const existing = staleSessionId ? projectIdsBoundToSession(staleSessionId) : []')+ expect(opts).toContain('return teamTabs.place({ hostId: hosted.hostId, label }, projects, existing, {')+ expect(opts).toContain('keepActive: !hosted.activate')+ expect(opts).toContain('...(hosted.focusProjectId ? { focusProjectId: hosted.focusProjectId } : {}),')+ const body = between('const mountRemoteMirror = useCallback(', 'const confirmAndMount = useCallback(')+ // Back online: every tab the connection serves un-greys, not just the one the reconnect named.+ expect(body).toContain('for (const id of tab.projectIds) useProjects.getState().setProjectUnavailable(id, false)')+ expect(body).toContain('return hosted ? { projectId: tab.projectId, projectIds: tab.projectIds } : null')+ })++ it('share events follow the host live: keep the screen, reconcile the joiner from the store either way', () => {+ const body = between('const mountRemoteMirror = useCallback(', 'const confirmAndMount = useCallback(')+ // The api is read once, right after the mount; the event's load never re-resolves it through a tab.+ const capture = body.indexOf('const bound = sessionForProject(tab.projectId)')+ const listen = body.indexOf('api.hosted.onSharedChanged((p) => {')+ expect(capture).toBeGreaterThan(-1)+ expect(listen).toBeGreaterThan(capture)+ const handler = body.slice(listen)+ expect(handler).not.toContain('sessionForProject(')+ expect(handler).toContain('async () => (await api.workspace.load()).projects.map(sanitizeRelayProject)')+ expect(handler).toContain('{ keepActive: true }')+ // A rejected event still closed tabs: the joiner is reconciled after it settles, resolved or not.+ const settled = handler.indexOf('.catch(() => {})')+ expect(settled).toBeGreaterThan(-1)+ expect(handler.indexOf('.then(() => {', settled)).toBeGreaterThan(settled)+ expect(handler).toContain('const before = teamTabIds()')+ expect(handler).toContain('joiner.tabsAdded(hostId, opened)')+ expect(handler).toContain('joiner.tabRemoved(id, after[0])')+ // The subscription dies with the session.+ expect(handler).toContain('holdSessionTeardown(tab.sessionId, off)')+ })++ it('a hosted tab leaves this desktop through the STORE delete, and never onto a closed project', () => {+ const body = between('const [teamTabs] = useState<TeamTabs>(() => {', ' return tabs\n })')+ expect(body).toContain('const next = store.deleteProject(id)')+ expect(body).toContain('if (!wasActive || isOpenTab(next)) return')+ expect(body).toContain('openSuccessor(useProjects.getState().projects, index, (other) => tabs.teamOf(other) === hostId)')+ expect(body).not.toContain('transport.destroy')+ })++ it('the joiner\'s mount names the team and where to land; the share flow joins through the joiner', () => {+ const joiner = between('const joiner = createHostedJoiner({', '}, [confirmAndMount])')+ expect(joiner).toContain('hostId: req.hostId,')+ expect(joiner).toContain('focusProjectId: req.focusProjectId ?? req.reconnectProjectId')+ const join = between('const joinApprovedTeam = useCallback(', '}, [])')+ expect(join).toContain('hostedJoinerRef.current?.joinApproved(code, focusProjectId ? { focusProjectId } : undefined)')+ })+it('the joiner is created once and reconnects the approved bookmarks at boot', () => {const body = between('const joiner = createHostedJoiner({', '}, [confirmAndMount])')expect(body).toContain('createHostedJoiner({')@@ -88,8 +141,14 @@ describe('hosted team glue in Canvas', () => {})it('R40: closing or deleting a tab stops its team\'s attempt (the one disposal both paths share)', () => {- const body = between('const disposeRelayTabForProject = useCallback(', '}, [])')+ const body = between('const disposeRelayTabForProject = useCallback(', '}, [teamTabs])')expect(body).toContain('hostedJoinerRef.current?.tabClosed(projectId)')+ // …unless the team has other tabs open: then only this one goes, and the connection lives on.+ const multi = body.indexOf('const { remaining } = teamTabs.closeTab(projectId)')+ expect(multi).toBeGreaterThan(-1)+ expect(multi).toBeLessThan(body.indexOf('hostedJoinerRef.current?.tabClosed(projectId)'))+ expect(body).toContain('hostedJoinerRef.current?.tabRemoved(projectId, remaining[0])')+ expect(body.indexOf('return', multi)).toBeLessThan(body.indexOf('disposeSession(s.id)'))expect(src).toContain('disposeRelayTabForProject(id)\n store.closeProject(id)')expect(src).toContain('disposeRelayTabForProject(id)\n store.deleteProject(id)')})@@ -97,6 +156,8 @@ describe('hosted team glue in Canvas', () => {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)) {')+ // A team whose tabs were ALL closed while it reconnected gets none of them back.+ expect(body).toContain('if (reconnectProjectId && !existing.some((id) => isOpenTab(id))) {')expect(body).toContain('return { id: reconnectProjectId } // reconnect: reuse the existing tab')})diff --git a/src/renderer/lib/hostedAttempts.test.ts b/src/renderer/lib/hostedAttempts.test.tsindex 0a4d6945f..6375000aa 100644--- a/src/renderer/lib/hostedAttempts.test.ts+++ b/src/renderer/lib/hostedAttempts.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi } from 'vitest'import type { RelayClosedReason } from '@shared/types'-import { createHostedAttempts, type HostedAttemptDeps, type HostedAttemptRequest } from './hostedAttempts'+import { createHostedAttempts, type HostedAttemptDeps, type HostedAttemptRequest, type HostedMountResult } from './hostedAttempts'import type { JoinFailure } from './hostedTeam'const wrap = (m: string) => new Error(`Error invoking remote method 'relay:client:connect': Error: ${m}`)@@ -9,7 +9,7 @@ const flush = () => new Promise((r) => setTimeout(r, 0))/** Deps whose every answer the test controls, with a manual clock. */function harness() {const connects: Array<{ code: string; resolve: (id: string) => void; reject: (e: Error) => void }> = []- const mounts: Array<{ id: string; req: HostedAttemptRequest; resolve: (r: { projectId: string } | { retry: boolean }) => void }> = []+ const mounts: Array<{ id: string; req: HostedAttemptRequest; resolve: (r: HostedMountResult) => void }> = []const closeCbs = new Map<string, (reason?: RelayClosedReason) => void>()const unsubs: string[] = []const timers: Array<{ fn: () => void; ms: number; cleared: boolean }> = []@@ -564,4 +564,60 @@ describe('hosted attempts: one attempt and one live connection per team (R38/R39expect(h.connects).toHaveLength(1)expect(h.armed()).toEqual([])})++ // ── One connection, several tabs ────────────────────────────────────────────────────────────────+ it('retarget moves a live team onto another of its tabs: a drop then reconnects into that tab', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot())+ h.connects[0].resolve('c1')+ await flush()+ h.mounts[0].resolve({ projectId: 'A', projectIds: ['A', 'B'] })+ await flush()+ expect(a.phase('H1')).toBe('live')+ a.retarget('A', 'B')+ h.closeCbs.get('c1')!(undefined)+ expect(h.ended).toHaveLength(1)+ expect(h.ended[0].projectId).toBe('B')+ })++ it('cancelProject on a retargeted tab no longer touches the team', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot())+ h.connects[0].resolve('c1')+ await flush()+ h.mounts[0].resolve({ projectId: 'A', projectIds: ['A', 'B'] })+ await flush()+ a.retarget('A', 'B')+ a.cancelProject('A')+ expect(a.phase('H1')).toBe('live')+ a.cancelProject('B')+ expect(a.phase('H1')).toBeNull()+ })++ it('retarget also moves a reconnect still waiting for its tab: it comes back into the new one', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ reconnectProjectId: 'A' }))+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] x'))+ await flush()+ a.retarget('A', 'B')+ a.cancelProject('A') // the old tab is no longer this attempt's+ expect(a.phase('H1')).toBe('waiting')+ h.fire()+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[0].req.reconnectProjectId).toBe('B')+ })++ it('retarget leaves other teams and other tabs alone', async () => {+ const h = harness()+ const a = createHostedAttempts(h.deps)+ a.run(boot({ hostId: 'H2', reconnectProjectId: 'C' }))+ a.retarget('A', 'B')+ h.connects[0].resolve('c1')+ await flush()+ expect(h.mounts[0].req.reconnectProjectId).toBe('C')+ })})diff --git a/src/renderer/lib/hostedAttempts.ts b/src/renderer/lib/hostedAttempts.tsindex a6eb47778..7dc81f30f 100644--- a/src/renderer/lib/hostedAttempts.ts+++ b/src/renderer/lib/hostedAttempts.ts@@ -45,14 +45,18 @@ export interface HostedAttemptRequest {afterDrop?: boolean/** A bookmarked reconnect: this side confirms on its own (no SAS prompt is expected). */autoConfirm?: boolean+ /** Activate this tab when the mount places it (the project the user just shared). */+ focusProjectId?: string}export type HostedAttemptPhase = 'connecting' | 'waiting' | 'mounting' | 'live'/** How a mount ended: a live tab, or not — and then whether trying again could help. `retry` is for* a connection that dropped before the host answered (a host restarting, a relay blip): the relay- * client exists before the host is reached, so that failure arrives here rather than as a code. */-export type HostedMountResult = { projectId: string } | { retry: boolean }+ * client exists before the host is reached, so that failure arrives here rather than as a code.+ * `projectIds` = every tab the one connection serves (a hosted team shares several projects);+ * `projectId` is the one the attempt follows. */+export type HostedMountResult = { projectId: string; projectIds?: string[] } | { retry: boolean }export interface HostedAttemptDeps {/** `relayClient.connect(code)` → a connection id; rejects with main's `[E_JOIN_…]` message. */@@ -93,6 +97,9 @@ export interface HostedAttempts {* 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+ /** One of a live team's tabs went away while others remain: its attempt now belongs to `to`, so a+ * later drop reconnects into a tab that is still open, and closing the old one stops nothing. */+ retarget(fromProjectId: string, toProjectId: string): void/** Stop everything (the canvas is going away). */dispose(): void}@@ -300,6 +307,12 @@ export function createHostedAttempts(deps: HostedAttemptDeps): HostedAttempts {release(e)}},+ retarget(from, to) {+ for (const e of entries.values()) {+ if (e.projectId === from) e.projectId = to+ if (e.req.reconnectProjectId === from) e.req = { ...e.req, reconnectProjectId: to }+ }+ },dispose() {disposed = truefor (const e of entries.values()) {diff --git a/src/renderer/lib/hostedJoin.test.ts b/src/renderer/lib/hostedJoin.test.tsindex a73892c55..9434ca1b7 100644--- a/src/renderer/lib/hostedJoin.test.ts+++ b/src/renderer/lib/hostedJoin.test.ts@@ -634,6 +634,142 @@ describe('hosted joiner', () => {expect(h.timers.filter((t) => t.ms === WAITING_NOTICE_DELAY_MS && !t.cleared)).toEqual([])})+ // ── One connection, several tabs ────────────────────────────────────────────────────────────────+ it('a mount with several tabs makes each of them a hosted tab of the team', 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.open.add('A')+ h.open.add('B')+ h.mounts[0].resolve({ projectId: 'A', projectIds: ['A', 'B'] })+ await flush()+ expect(j.isHostedTab('A')).toBe(true)+ expect(j.isHostedTab('B')).toBe(true)+ expect(j.isHostedTab('C')).toBe(false)+ })++ it('tabRemoved keeps the team live on its successor; reconnectTab on the successor works', 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.open.add('A')+ h.open.add('B')+ h.mounts[0].resolve({ projectId: 'A', projectIds: ['A', 'B'] })+ await flush()+ // The tab the connection was opened on goes away; the team lives on in B.+ j.tabRemoved('A', 'B')+ h.open.delete('A')+ expect(j.isHostedTab('A')).toBe(false)+ expect(j.isHostedTab('B')).toBe(true)+ j.joinWithCode(codeFor('H1'))+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: "You're already connected to box." })+ expect(h.connects).toHaveLength(1)+ // A drop reconnects into the successor, not the removed tab (which would end the team).+ h.closeCbs.get('c0')!(undefined)+ await flush()+ fireRetry(h)+ expect(h.connects).toHaveLength(2)+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[1].req).toMatchObject({ hostId: 'H1', reconnectProjectId: 'B' })+ h.mounts[1].resolve({ projectId: 'B', projectIds: ['B'] })+ await flush()+ // …and once it is greyed again, a click on it reconnects in place.+ h.setList([])+ h.closeCbs.get('c1')!(undefined)+ await flush()+ expect(j.reconnectTab('B')).toBe(true)+ expect(h.connects).toHaveLength(3)+ h.connects[2].resolve('c2')+ await flush()+ expect(h.mounts[2].req).toMatchObject({ reconnectProjectId: 'B', manual: true })+ })++ it('tabRemoved for a tab the joiner never tracked changes nothing', 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, 'A')+ j.tabRemoved('Z', 'A')+ expect(j.isHostedTab('Z')).toBe(false)+ expect(j.isHostedTab('A')).toBe(true)+ expect(j.connecting('H1')).toBe(false)+ })++ it('tabsAdded registers tabs opened by a share event', 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, 'A')+ h.open.add('C')+ j.tabsAdded('H1', ['C'])+ expect(j.isHostedTab('C')).toBe(true)+ // A team this joiner holds no tab for is not adopted from a share event.+ j.tabsAdded('H9', ['D'])+ expect(j.isHostedTab('D')).toBe(false)+ // The added tab reconnects like the others: from the team's bookmark, in place.+ h.setList([])+ h.closeCbs.get('c0')!(undefined)+ await flush()+ expect(j.reconnectTab('C')).toBe(true)+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[1].req).toMatchObject({ hostId: 'H1', code: codeFor('H1'), reconnectProjectId: 'C' })+ })++ it('joinApproved retries a network failure (unlike a pasted code) and auto-confirms', async () => {+ const h = harness()+ const j = createHostedJoiner(h.deps)+ expect(j.joinApproved(` ${codeFor('H1', 'box')} `)).toBe('started')+ h.connects[0].reject(wrap('[E_JOIN_NETWORK] Could not reach the nodeterm service.'))+ await flush()+ expect(h.notices).toEqual([]) // a retry in progress says nothing+ expect(h.timers.filter((t) => !t.cleared && t.ms !== WAITING_NOTICE_DELAY_MS).map((t) => t.ms)).toEqual([1000])+ fireRetry(h)+ expect(h.connects).toHaveLength(2)+ expect(h.connects[1].code).toBe(codeFor('H1', 'box'))+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[0].req).toMatchObject({ hostId: 'H1', label: 'box', manual: true, retry: true, autoConfirm: true })+ // Auto-confirmed: no SAS is expected, so the waiting-for-an-owner clock starts with the connection.+ expect(h.timers.filter((t) => t.ms === WAITING_NOTICE_DELAY_MS && !t.cleared)).toHaveLength(1)+ })++ it('joinApproved passes focusProjectId to the mount', async () => {+ const h = harness()+ const j = createHostedJoiner(h.deps)+ j.joinApproved(codeFor('H1'), { focusProjectId: 'P9' })+ h.connects[0].resolve('c0')+ await flush()+ expect(h.mounts[0].req.focusProjectId).toBe('P9')+ // Without one, the request carries none.+ const k = harness()+ createHostedJoiner(k.deps).joinApproved(codeFor('H2'))+ k.connects[0].resolve('c0')+ await flush()+ expect(k.mounts[0].req.focusProjectId).toBeUndefined()+ })++ it('joinApproved for a team that is already live is refused politely; one with a greyed tab reconnects 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, 'A')+ expect(j.joinApproved(codeFor('H1', 'box'))).toBe('busy')+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: "You're already connected to box." })+ h.setList([])+ h.closeCbs.get('c0')!(undefined)+ await flush()+ expect(j.joinApproved(codeFor('H1', 'box'))).toBe('started')+ h.connects[1].resolve('c1')+ await flush()+ expect(h.mounts[1].req.reconnectProjectId).toBe('A')+ })+it('R41: a bookmarked reconnect arms it when its connect resolves; a SAS that shows up after all disarms it', async () => {const h = harness([{ hostId: 'H1', label: 'box', approved: true, code: codeFor('H1') }])const j = createHostedJoiner(h.deps)diff --git a/src/renderer/lib/hostedJoin.ts b/src/renderer/lib/hostedJoin.tsindex a7e655a51..f07b4435e 100644--- a/src/renderer/lib/hostedJoin.ts+++ b/src/renderer/lib/hostedJoin.ts@@ -6,8 +6,12 @@// 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;+// - the share flow (`joinApproved`): a team this desktop just set up itself joins now, retrying+// while its relay comes up, with no SAS (its bookmark is pre-approved);// - 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).+// - closing or deleting a tab: its team's attempt stops, in any phase (R40) — unless the team has+// other tabs open (one connection serves one tab per shared project): then the attempt moves to+// one of those (`tabRemoved`), and tabs a share event opens later join the team (`tabsAdded`).// 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@@ -35,9 +39,10 @@ export const WAITING_NOTICE_DELAY_MS = 2500export const HOSTED_CODE_IN_TEAM_ACCESS_TAB ='That is a hosted team invite code — paste it with New Remote Connection to open the team in its own tab.'-/** 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). */-export type HostedMountOutcome = { projectId: string } | { error: unknown; declined: boolean }+/** How a mount ended, as the canvas reports it: live tabs, or the error it failed with. `declined`+ * = this user declined the SAS themselves (nothing to tell them). `projectIds` = every tab the one+ * connection serves (one per project the team shares); `projectId` is the one it activated. */+export type HostedMountOutcome = { projectId: string; projectIds?: string[] } | { error: unknown; declined: boolean }export interface HostedNotice {kind: 'info' | 'error'@@ -84,6 +89,18 @@ export interface HostedJoiner {isHostedTab(projectId: string): boolean/** The user closed or deleted this tab: its team's attempt stops now, in any phase (R40). */tabClosed(projectId: string): void+ /** One of a team's tabs went away while `successorId`, another of its tabs, stays open (the user+ * closed it, or the host stopped sharing it): the team's attempt follows the successor, so the+ * connection lives on and a drop reconnects into a tab that is still there. */+ tabRemoved(projectId: string, successorId: string): void+ /** A share event opened `projectIds` as more tabs of `hostId`'s live connection: they reconnect+ * like the team's other tabs. A no-op for a team this joiner holds no tab for. */+ tabsAdded(hostId: string, projectIds: string[]): void+ /** Join a team this desktop just set up itself (its bookmark is already approved): retries a+ * network failure like an unattended reconnect, confirms on its own (no SAS prompt), and+ * activates `focusProjectId` when the mount places it. `busy` = that team already has an+ * attempt or a live connection, and the user was told. */+ joinApproved(code: string, opts?: { focusProjectId?: string }): 'started' | 'busy'/** 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. */@@ -197,8 +214,11 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {disarm()}if ('projectId' in outcome) {- tabs.set(outcome.projectId, { hostId: req.hostId, code: req.code, label: req.label })- return { projectId: outcome.projectId }+ // One connection serves every tab the team shares: each one reconnects from this team.+ for (const id of outcome.projectIds ?? [outcome.projectId]) {+ tabs.set(id, { hostId: req.hostId, code: req.code, label: req.label })+ }+ return { projectId: outcome.projectId, projectIds: outcome.projectIds }}// Declined by this user, or its tab was closed meanwhile (closed for it): nothing to say.if (outcome.declined || !tabWanted(req)) return { retry: false }@@ -321,6 +341,38 @@ export function createHostedJoiner(deps: HostedJoinerDeps): HostedJoiner {tabs.delete(projectId)attempts.cancelProject(projectId)},+ tabRemoved(projectId, successorId) {+ const t = tabs.get(projectId)+ tabs.delete(projectId)+ if (t && !tabs.has(successorId)) tabs.set(successorId, t)+ attempts.retarget(projectId, successorId)+ },+ tabsAdded(hostId, projectIds) {+ const t = [...tabs.values()].find((x) => x.hostId === hostId)+ if (t) for (const id of projectIds) tabs.set(id, t)+ },+ joinApproved(raw, opts) {+ const code = raw.trim()+ const peek = peekJoinCode(code)+ const hostId = peek?.hostId ?? `unreadable:${code}`+ const label = peek?.label ?? ''+ const target = tabFor(hostId)+ // A team this desktop just set up itself over ssh (its bookmark is pre-approved): retry a+ // relay that is still coming up, and confirm on our side with no SAS (main confirms a join+ // whose bookmark is approved for the same host key).+ const result = run({+ hostId,+ code,+ label,+ manual: true,+ retry: true,+ autoConfirm: true,+ ...(target ? { reconnectProjectId: target } : {}),+ ...(opts?.focusProjectId ? { focusProjectId: opts.focusProjectId } : {})+ })+ if (result === 'busy') deps.notify({ kind: 'info', text: busyText(hostId, label) })+ return result+ },async bootReconnect() {const list = await deps.bookmarks().catch(() => [])for (const b of list) {diff --git a/src/renderer/lib/hostedTeamTabs.test.ts b/src/renderer/lib/hostedTeamTabs.test.tsindex 3895c56b7..4e65abc75 100644--- a/src/renderer/lib/hostedTeamTabs.test.ts+++ b/src/renderer/lib/hostedTeamTabs.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi } from 'vitest'import type { Project } from '@shared/types'-import { createTeamTabs, type TeamTabOps } from './hostedTeamTabs'+import { createTeamTabs, openSuccessor, type TeamTabOps } from './hostedTeamTabs'/** A host's shared project, as the relay hands it over (`sanitizeRelayProject` marks it remote). */const proj = (id: string, name = id): Project => ({@@ -58,7 +58,7 @@ function fakeOps(initial: Project[] = [], active: string | null = null) {state.projects.push({ ...local(id), name: label })return { id }}),- removeTab: vi.fn((id: string) => {+ removeTab: vi.fn((id: string, _hostId: string) => {calls.push(`remove:${id}`)const index = state.projects.findIndex((p) => p.id === id)if (index < 0) return@@ -473,4 +473,44 @@ describe('createTeamTabs', () => {expect(f.ops.isOpenTab('A')).toBe(true)expect(f.ops.isOpenTab('B')).toBe(true)})++ it('removeTab names the team the tab belonged to, so the caller can keep the user on that team', async () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)+ for (const id of tabs.place(team, [A, B], [], { keepActive: false })) f.ops.bind(id, 'relay-1')+ await tabs.sharedChanged(live, ['A'], async () => [], { keepActive: true })+ expect(f.ops.removeTab).toHaveBeenCalledWith('B', 'host-1')+ // The last unshare leaves a placeholder; the next share removes it, named the same way.+ await tabs.sharedChanged(live, [], async () => [], { keepActive: true })+ expect(f.ops.removeTab).toHaveBeenCalledWith('A', 'host-1')+ await tabs.sharedChanged(live, ['C'], async () => [C], { keepActive: true })+ expect(f.ops.removeTab).toHaveBeenCalledWith('ph-1', 'host-1')+ // A reconnect that finds a project unshared removes it under the team too.+ tabs.place(team, [], ['C'], { keepActive: true })+ expect(f.ops.removeTab).toHaveBeenCalledWith('C', 'host-1')+ })+})++describe('openSuccessor', () => {+ const tab = (id: string, closed = false) => ({ id, closed })++ it('prefers the nearest open tab of the same team', () => {+ // `x` was removed from index 2: the list is what remains.+ const projects = [tab('a'), tab('t1'), tab('mine'), tab('other'), tab('t2')]+ expect(openSuccessor(projects, 2, (id) => id === 't1' || id === 't2')).toBe('t1')+ expect(openSuccessor(projects, 4, (id) => id === 't1' || id === 't2')).toBe('t2')+ })++ it('never lands on a closed project, of the team or not', () => {+ const projects = [tab('mine'), tab('t1', true), tab('closed', true), tab('far')]+ expect(openSuccessor(projects, 2, (id) => id === 't1')).toBe('far')+ expect(openSuccessor(projects, 1, () => false)).toBe('mine')+ })++ it('without a team tab left, the nearest open project; without one at all, the welcome screen', () => {+ expect(openSuccessor([tab('a'), tab('b'), tab('c')], 1, () => false)).toBe('b')+ expect(openSuccessor([tab('a'), tab('b')], 2, () => false)).toBe('b')+ expect(openSuccessor([tab('a', true)], 0, () => false)).toBe('')+ expect(openSuccessor([], 0, () => false)).toBe('')+ })})diff --git a/src/renderer/lib/hostedTeamTabs.ts b/src/renderer/lib/hostedTeamTabs.tsindex 20d3df411..943ad1054 100644--- a/src/renderer/lib/hostedTeamTabs.ts+++ b/src/renderer/lib/hostedTeamTabs.ts@@ -37,8 +37,10 @@ export interface TeamTabOps {adoptProject(p: Project): { id: string }addPlaceholder(label: string): { id: string }/** Drop a hosted tab from THIS desktop only: never the destroying delete (which would kill the- * host's sessions through the relay transport). */- removeTab(id: string): void+ * host's sessions through the relay transport). `hostId` is the team the tab belonged to (or was+ * being opened for), so a caller that has to move the user off it can prefer that team's other+ * tabs (`openSuccessor`). */+ removeTab(id: string, hostId: string): voidactiveProjectId(): string | nullsetActive(id: string): voidbind(projectId: string, sessionId: string): void@@ -71,6 +73,23 @@ export interface TeamTabs {teamOf(projectId: string): string | undefined}+/** Which project takes the screen when the active tab is removed from the store: the nearest open+ * tab of the same team, else the nearest open project, else '' (the welcome screen). Never a closed+ * project — the store's own fallback is whichever project slides into the removed slot, closed or+ * not. `projects` is the list without the removed tab and `index` the slot it held. */+export function openSuccessor(+ projects: readonly { id: string; closed?: boolean }[],+ index: number,+ sameTeam: (id: string) => boolean+): string {+ const nearest = (pick: (p: { id: string; closed?: boolean }) => boolean): string | undefined =>+ projects+ .map((p, i) => ({ p, d: Math.abs(i - index) }))+ .filter(({ p }) => !p.closed && pick(p))+ .sort((a, b) => a.d - b.d)[0]?.p.id+ return nearest((p) => sameTeam(p.id)) ?? nearest(() => true) ?? ''+}+/** The host's projects with the planner's id rules applied: first occurrence of each sane id. */function cleanProjects(projects: readonly Project[]): Project[] {const byId = new Map<string, Project>()@@ -108,22 +127,22 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {if (next && ops.isOpenTab(next)) ops.setActive(next)}- /** Open `p` as a tab under the host's own id; null when that id cannot be had. */- const tabFor = (p: Project): string | null => {+ /** Open `p` as a tab of `hostId` under the host's own id; null when that id cannot be had. */+ const tabFor = (p: Project, hostId: string): string | null => {const held = ops.getProject(p.id)if (held) {if (ops.isOpenTab(p.id)) return null// A closed relay copy is a former hosted tab: replace it. A closed local project is the// user's own, and removing it from the store would delete it.if (held.remote !== true) return null- ops.removeTab(p.id)+ ops.removeTab(p.id, hostId)}const before = ops.activeProjectId()const id = ops.adoptProject(p).idif (id === p.id) return id// The store derived another id; the relay api would not know it. Drop the tab and keep the user// where the adopt found them.- ops.removeTab(id)+ ops.removeTab(id, hostId)if (before && ops.isOpenTab(before)) ops.setActive(before)return null}@@ -134,7 +153,7 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {placeholders.delete(hostId)team.delete(ph)ops.unbind(ph)- ops.removeTab(ph)+ ops.removeTab(ph, hostId)}const applyShared = async (@@ -153,7 +172,7 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {for (const id of plan.close) {team.delete(id)ops.unbind(id)- ops.removeTab(id)+ ops.removeTab(id, host)}// Commit the close half before awaiting: a failed load, or the next event, reads a set// without the closed tabs.@@ -172,14 +191,14 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {if (epochOf(host) !== epoch) return { opened: [], closed: plan.close }for (const p of loaded) {if (!plan.open.includes(p.id) || opened.includes(p.id)) continue- const id = tabFor(p)+ const id = tabFor(p, host)if (!id) continuetry {ops.bind(id, t.sessionId)} catch (error) {// The session was disposed while the workspace loaded; an unbound tab would resolve to the// local session.- ops.removeTab(id)+ ops.removeTab(id, host)failure = { error }sessionGone = truebreak@@ -204,7 +223,7 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {placeholders.set(host, ph)team.set(ph, host)} catch (error) {- ops.removeTab(ph)+ ops.removeTab(ph, host)failure = failure ?? { error }}}@@ -225,7 +244,7 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {const ids: string[] = []for (const p of shared) {if (set.dismissed.includes(p.id)) continue- const id = reuse.has(p.id) && ops.isOpenTab(p.id) ? p.id : tabFor(p)+ const id = reuse.has(p.id) && ops.isOpenTab(p.id) ? p.id : tabFor(p, host)if (id) ids.push(id)}const ph = placeholders.get(host)@@ -233,7 +252,7 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {if (ids.includes(id) || id === ph) continueteam.delete(id)ops.unbind(id)- ops.removeTab(id)+ ops.removeTab(id, host)}// A dismissal is remembered only while the host still shares that project.const dismissed = set.dismissed.filter((d) => shared.some((p) => p.id === d))