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): hosted tab model — one tab per shared project, following share changes
reviewf1f031646deb
diff --git a/src/renderer/lib/hostedTabs.test.ts b/src/renderer/lib/hostedTabs.test.tsnew file mode 100644index 000000000..4e56670cf--- /dev/null+++ b/src/renderer/lib/hostedTabs.test.ts@@ -0,0 +1,21 @@+import { describe, it, expect } from 'vitest'+import { planSharedChange, dismissTab, EMPTY_TAB_SET } from './hostedTabs'++describe('planSharedChange', () => {+ it('opens new shared projects and closes unshared ones, in the host order', () => {+ expect(planSharedChange({ shown: ['a', 'b'], dismissed: [] }, ['c', 'a'])).toEqual({+ open: ['c'], close: ['b'], next: { shown: ['c', 'a'], dismissed: [] }+ })+ })+ it('a tab the user closed is not reopened while it stays shared; unsharing forgets that', () => {+ const set = dismissTab({ shown: ['a', 'b'], dismissed: [] }, 'b')+ expect(set).toEqual({ shown: ['a'], dismissed: ['b'] })+ expect(planSharedChange(set, ['a', 'b']).open).toEqual([])+ const afterUnshare = planSharedChange(set, ['a']).next+ expect(afterUnshare.dismissed).toEqual([])+ expect(planSharedChange(afterUnshare, ['a', 'b']).open).toEqual(['b'])+ })+ it('ignores junk and duplicates in the list', () => {+ expect(planSharedChange(EMPTY_TAB_SET, ['a', 'a', 7 as never, '' ]).next.shown).toEqual(['a'])+ })+})diff --git a/src/renderer/lib/hostedTabs.ts b/src/renderer/lib/hostedTabs.tsnew file mode 100644index 000000000..67c976572--- /dev/null+++ b/src/renderer/lib/hostedTabs.ts@@ -0,0 +1,49 @@+// Which of a hosted team's shared projects this desktop shows as tabs, and how a share change moves+// them. Pure.+//+// `shown` is the team's open tabs in the host's order; `dismissed` is what the user closed by hand+// while it stayed shared. A dismissed project is never reopened by a later share event (the user+// said no to that tab), but the moment the host stops sharing it the dismissal is forgotten, so a+// re-share opens it again like any newly shared project.+//+// The host's list arrives off the wire, so it is cleaned before it is trusted: only non-empty+// strings of a sane length, de-duplicated, capped.++export interface HostedTabSet {+ shown: string[]+ dismissed: string[]+}++export const EMPTY_TAB_SET: HostedTabSet = Object.freeze({ shown: [], dismissed: [] }) as HostedTabSet++const MAX = 256++const clean = (ids: readonly unknown[]): string[] =>+ [...new Set(ids.filter((x): x is string => typeof x === 'string' && x.length > 0 && x.length <= 128))].slice(0, MAX)++/** The host now shares `shared`: which tabs to open (new and not dismissed), which to close (shown+ * but no longer shared), and the set after both. */+export function planSharedChange(+ set: HostedTabSet,+ shared: readonly string[]+): { open: string[]; close: string[]; next: HostedTabSet } {+ const ids = clean(shared)+ const open = ids.filter((id) => !set.shown.includes(id) && !set.dismissed.includes(id))+ const close = set.shown.filter((id) => !ids.includes(id))+ return {+ open,+ close,+ next: {+ shown: ids.filter((id) => set.shown.includes(id) || open.includes(id)),+ dismissed: set.dismissed.filter((id) => ids.includes(id))+ }+ }+}++/** The user closed one of the team's tabs: stop showing it and remember not to reopen it. */+export function dismissTab(set: HostedTabSet, projectId: string): HostedTabSet {+ return {+ shown: set.shown.filter((id) => id !== projectId),+ dismissed: set.dismissed.includes(projectId) ? set.dismissed : [...set.dismissed, projectId]+ }+}diff --git a/src/renderer/lib/hostedTeamTabs.test.ts b/src/renderer/lib/hostedTeamTabs.test.tsnew file mode 100644index 000000000..1989ee467--- /dev/null+++ b/src/renderer/lib/hostedTeamTabs.test.ts@@ -0,0 +1,205 @@+import { describe, it, expect, vi } from 'vitest'+import type { Project } from '@shared/types'+import { createTeamTabs, type TeamTabOps } from './hostedTeamTabs'++const proj = (id: string, name = id): Project => ({ id, name, color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] })++const A = proj('A', 'Alpha')+const B = proj('B', 'Beta')+const C = proj('C', 'Gamma')++const team = { hostId: 'host-1', label: 'Team X' }+const live = { ...team, sessionId: 'relay-1' }++/** An in-memory stand-in for the projects store + the session registry's bindings. `adoptProject`+ * activates what it adopts, exactly as the real store does; `addPlaceholder` (the store's+ * `addProject`) does not. */+function fakeOps(initial: Project[] = [], active: string | null = null) {+ const projects = new Map<string, Project>(initial.map((p) => [p.id, p]))+ const bindings = new Map<string, string>()+ const state = { active, placeholders: 0 }+ const ops: TeamTabOps = {+ getProject: (id) => projects.get(id),+ isOpenTab: (id) => {+ const p = projects.get(id)+ return !!p && !p.closed+ },+ adoptProject: vi.fn((p: Project) => {+ projects.set(p.id, p)+ state.active = p.id+ return { id: p.id }+ }),+ addPlaceholder: vi.fn((label: string) => {+ const id = `ph-${++state.placeholders}`+ projects.set(id, { ...proj(id), name: label })+ return { id }+ }),+ removeTab: vi.fn((id: string) => {+ projects.delete(id)+ }),+ activeProjectId: () => state.active,+ setActive: (id) => {+ state.active = id+ },+ bind: (projectId, sessionId) => {+ bindings.set(projectId, sessionId)+ },+ unbind: (projectId) => {+ bindings.delete(projectId)+ }+ }+ return { ops, projects, bindings, state }+}++describe('createTeamTabs', () => {+ it('place: adopts each shared project as a tab in host order, and keeps the user on their tab when asked', () => {+ const f = fakeOps([proj('mine')], 'mine')+ const tabs = createTeamTabs(f.ops)++ expect(tabs.place(team, [A, B], [], { keepActive: true })).toEqual(['A', 'B'])+ expect(f.ops.adoptProject).toHaveBeenCalledTimes(2)+ expect([...f.projects.keys()]).toEqual(['mine', 'A', 'B'])+ expect(f.state.active).toBe('mine')+ expect(tabs.teamOf('A')).toBe('host-1')+ expect(tabs.teamOf('B')).toBe('host-1')+ expect(tabs.teamOf('mine')).toBeUndefined()++ // Not asked to keep it: the user lands where the store's adopt put them.+ const g = fakeOps([proj('mine')], 'mine')+ createTeamTabs(g.ops).place(team, [A, B], [], { keepActive: false })+ expect(g.state.active).toBe('B')+ })++ it('place: with nothing shared, a placeholder tab named after the team', () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)++ expect(tabs.place(team, [], [], { keepActive: false })).toEqual(['ph-1'])+ expect(f.projects.get('ph-1')?.name).toBe('Team X')+ expect(tabs.teamOf('ph-1')).toBe('host-1')++ // Placing nothing again (a reconnect) keeps that one placeholder instead of minting another.+ expect(tabs.place(team, [], ['ph-1'], { keepActive: false })).toEqual(['ph-1'])+ expect(f.ops.addPlaceholder).toHaveBeenCalledTimes(1)+ })++ it('place on reconnect: reuses the existing tabs by id, removes a tab that is no longer shared', () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)+ expect(tabs.place(team, [A, B], [], { keepActive: false })).toEqual(['A', 'B'])++ // The host now shares only A; the greyed tabs A and B are this team's existing tabs.+ expect(tabs.place(team, [A], ['A', 'B'], { keepActive: false })).toEqual(['A'])+ expect(f.ops.adoptProject).toHaveBeenCalledTimes(2) // A was reused, not adopted a second time+ expect(f.projects.has('A')).toBe(true)+ expect(f.projects.has('B')).toBe(false)+ expect(f.ops.removeTab).toHaveBeenCalledWith('B')+ expect(tabs.teamOf('B')).toBeUndefined()+ })++ it('place: a project the user dismissed is not reopened on reconnect', () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)+ tabs.place(team, [A, B], [], { keepActive: false })++ expect(tabs.closeTab('B')).toEqual({ remaining: ['A'] })+ f.projects.delete('B') // the store drops the tab the user closed++ expect(tabs.place(team, [A, B], ['A'], { keepActive: false })).toEqual(['A'])+ expect(f.ops.adoptProject).toHaveBeenCalledTimes(2)+ expect(f.projects.has('B')).toBe(false)+ })++ it('sharedChanged: opens and binds a newly shared project, loading the workspace only when something opens', async () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)+ tabs.place(team, [A], [], { keepActive: false })+ expect(f.state.active).toBe('A')+ const load = vi.fn(async () => [A, C])++ await expect(tabs.sharedChanged(live, ['A', 'C'], load, { keepActive: true })).resolves.toEqual({+ opened: ['C'],+ closed: []+ })+ expect(load).toHaveBeenCalledTimes(1)+ expect(f.bindings.get('C')).toBe('relay-1')+ expect(f.projects.has('C')).toBe(true)+ expect(f.ops.adoptProject).toHaveBeenCalledTimes(2) // A was already open: only C was adopted+ expect(tabs.teamOf('C')).toBe('host-1')+ expect(f.state.active).toBe('A') // kept, although the store's adopt activated C++ // The same list again opens nothing, so the host's workspace is not loaded again.+ await expect(tabs.sharedChanged(live, ['A', 'C'], load, { keepActive: true })).resolves.toEqual({+ opened: [],+ closed: []+ })+ expect(load).toHaveBeenCalledTimes(1)+ })++ it('sharedChanged: closes and unbinds an unshared tab; the last unshare leaves a bound placeholder', 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')+ const load = vi.fn(async () => [A, B])++ await expect(tabs.sharedChanged(live, ['A'], load, { keepActive: false })).resolves.toEqual({+ opened: [],+ closed: ['B']+ })+ expect(f.projects.has('B')).toBe(false)+ expect(f.bindings.has('B')).toBe(false)+ expect(f.bindings.get('A')).toBe('relay-1')+ expect(tabs.teamOf('B')).toBeUndefined()++ await expect(tabs.sharedChanged(live, [], load, { keepActive: false })).resolves.toEqual({+ opened: [],+ closed: ['A']+ })+ expect(f.projects.has('A')).toBe(false)+ expect(f.bindings.has('A')).toBe(false)+ expect(f.projects.get('ph-1')?.name).toBe('Team X')+ expect(f.bindings.get('ph-1')).toBe('relay-1')+ expect(tabs.teamOf('ph-1')).toBe('host-1')+ expect(load).not.toHaveBeenCalled()+ })++ it('sharedChanged: the first real project replaces the placeholder', async () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)+ expect(tabs.place(team, [], [], { keepActive: false })).toEqual(['ph-1'])+ f.ops.bind('ph-1', 'relay-1')++ await expect(tabs.sharedChanged(live, ['A'], async () => [A], { keepActive: false })).resolves.toEqual({+ opened: ['A'],+ closed: []+ })+ expect(f.projects.has('A')).toBe(true)+ expect(f.bindings.get('A')).toBe('relay-1')+ expect(f.projects.has('ph-1')).toBe(false)+ expect(f.bindings.has('ph-1')).toBe(false)+ expect(tabs.teamOf('ph-1')).toBeUndefined()+ expect(tabs.teamOf('A')).toBe('host-1')+ })++ it('closeTab: with other tabs open only unbinds this one and reports them; the last tab reports none', () => {+ const f = fakeOps()+ const tabs = createTeamTabs(f.ops)+ for (const id of tabs.place(team, [A, B, C], [], { keepActive: false })) f.ops.bind(id, 'relay-1')+ // C was closed in the store behind this controller's back: it is no longer an open tab.+ f.projects.set('C', { ...C, closed: true })++ expect(tabs.closeTab('A')).toEqual({ remaining: ['B'] })+ expect(f.bindings.has('A')).toBe(false)+ expect(f.bindings.get('B')).toBe('relay-1')+ expect(tabs.teamOf('A')).toBeUndefined()+ expect(f.ops.removeTab).not.toHaveBeenCalled() // closing is the caller's; this only bookkeeps++ // The last open tab of the team: its binding stays for the caller that ends the connection.+ expect(tabs.closeTab('B')).toEqual({ remaining: [] })+ expect(f.bindings.get('B')).toBe('relay-1')+ expect(tabs.teamOf('B')).toBeUndefined()++ // A tab that belongs to no team reports nothing and touches nothing.+ expect(tabs.closeTab('mine')).toEqual({ remaining: [] })+ })+})diff --git a/src/renderer/lib/hostedTeamTabs.ts b/src/renderer/lib/hostedTeamTabs.tsnew file mode 100644index 000000000..df5d898e0--- /dev/null+++ b/src/renderer/lib/hostedTeamTabs.ts@@ -0,0 +1,167 @@+// The tabs a hosted team occupies on this desktop: one tab per project the host shares, all served+// by ONE relay connection. The store and the session registry are injected (`TeamTabOps`), so+// everything here is plain bookkeeping that runs under a test without either.+//+// - The tab id IS the host's project id. The relay api translates no ids, so a tab under any other+// id would ask the host about a project it does not know. (An id an unrelated local project+// already holds is the store's to resolve, exactly as the single-tab adopt always did.)+// - `place` runs on every (re)mount of the team's connection: on a reconnect it reuses the team's+// greyed tabs by id, so their nodes and their place in the tab bar survive, and it removes the+// tabs whose project the host stopped sharing while this desktop was away.+// - `sharedChanged` follows the host's share events while the connection is live: it opens a tab+// for each newly shared project and closes the tabs of unshared ones.+// - `closeTab` is the user closing ONE of the team's tabs: it is remembered as dismissed (not+// reopened while it stays shared) and the connection lives on for the team's other tabs. Only the+// last tab's close leaves the binding alone, for the caller that ends the connection.+// - A team with nothing shared keeps one placeholder tab named after the team, so the team stays+// visible and reconnectable instead of vanishing from the tab bar; the first shared project+// replaces it.+//+// Removing a tab here is always a removal from THIS desktop only (`removeTab`), never the+// destroying delete: that would end the host's sessions through the relay transport.++import type { Project } from '@shared/types'+import { EMPTY_TAB_SET, dismissTab, planSharedChange, type HostedTabSet } from './hostedTabs'++export interface TeamTabOps {+ getProject(id: string): Project | undefined+ isOpenTab(id: string): boolean+ 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+ activeProjectId(): string | null+ setActive(id: string): void+ bind(projectId: string, sessionId: string): void+ unbind(projectId: string): void+}++export interface TeamRef {+ hostId: string+ label: string+}++export interface TeamTabs {+ /** Place the host's shared projects as this team's tabs (host order), reusing `existing` tabs by+ * id and removing the existing ones no longer shared. Never empty: nothing shared yields the+ * team's placeholder. Binding the returned ids to the session is the caller's. */+ place(team: TeamRef, projects: Project[], existing: string[], opts: { keepActive: boolean }): string[]+ /** The host's shared set is now `projectIds`: close the tabs no longer shared, and open (and bind)+ * the newly shared ones, calling `load` for the host's workspace only when something opens. */+ sharedChanged(+ team: TeamRef & { sessionId: string },+ projectIds: string[],+ load: () => Promise<Project[]>,+ opts: { keepActive: boolean }+ ): Promise<{ opened: string[]; closed: string[] }>+ /** The user closed one of a team's tabs. `remaining` names the team's other open tabs; empty means+ * this was its last, and the caller owns ending the connection. */+ closeTab(projectId: string): { remaining: string[] }+ /** The team (host id) a tab belongs to, if any. */+ teamOf(projectId: string): string | undefined+}++export function createTeamTabs(ops: TeamTabOps): TeamTabs {+ const sets = new Map<string, HostedTabSet>()+ const placeholders = new Map<string, string>()+ const team = new Map<string, string>()++ // The store's adopt activates what it adopts; a share the user did not ask for must not take the+ // screen from the tab they are on.+ const restoreActive = (prev: string | null, keep: boolean): void => {+ if (keep && prev && ops.getProject(prev)) ops.setActive(prev)+ }+ const dropPlaceholder = (hostId: string): void => {+ const ph = placeholders.get(hostId)+ if (!ph) return+ placeholders.delete(hostId)+ team.delete(ph)+ ops.unbind(ph)+ ops.removeTab(ph)+ }++ return {+ place(t, projects, existing, opts) {+ const prev = ops.activeProjectId()+ const set = sets.get(t.hostId) ?? EMPTY_TAB_SET+ const reuse = new Set(existing)+ const ids: string[] = []+ for (const p of projects) {+ if (set.dismissed.includes(p.id)) continue+ ids.push(reuse.has(p.id) && ops.getProject(p.id) ? p.id : ops.adoptProject(p).id)+ }+ const ph = placeholders.get(t.hostId)+ for (const id of existing) {+ if (!ids.includes(id) && id !== ph) {+ team.delete(id)+ ops.removeTab(id)+ }+ }+ // A dismissal is remembered only while the host still shares that project.+ const dismissed = set.dismissed.filter((d) => projects.some((p) => p.id === d))+ if (ids.length === 0) {+ const keep = ph && ops.getProject(ph) ? ph : ops.addPlaceholder(t.label).id+ placeholders.set(t.hostId, keep)+ team.set(keep, t.hostId)+ restoreActive(prev, opts.keepActive)+ sets.set(t.hostId, { shown: [], dismissed })+ return [keep]+ }+ if (ph) dropPlaceholder(t.hostId)+ for (const id of ids) team.set(id, t.hostId)+ sets.set(t.hostId, { shown: ids, dismissed })+ restoreActive(prev, opts.keepActive)+ return ids+ },++ async sharedChanged(t, projectIds, load, opts) {+ const set = sets.get(t.hostId) ?? EMPTY_TAB_SET+ const plan = planSharedChange(set, projectIds)+ for (const id of plan.close) {+ team.delete(id)+ ops.unbind(id)+ ops.removeTab(id)+ }+ const opened: string[] = []+ if (plan.open.length) {+ const prev = ops.activeProjectId()+ for (const p of await load()) {+ if (!plan.open.includes(p.id) || ops.getProject(p.id)) continue+ const id = ops.adoptProject(p).id+ ops.bind(id, t.sessionId)+ team.set(id, t.hostId)+ opened.push(id)+ }+ restoreActive(prev, opts.keepActive)+ }+ // A newly shared project the load did not return opened no tab: it is not shown.+ const shown = plan.next.shown.filter((id) => ops.getProject(id))+ sets.set(t.hostId, { shown, dismissed: plan.next.dismissed })+ if (shown.length > 0) dropPlaceholder(t.hostId)+ else if (!placeholders.has(t.hostId)) {+ const ph = ops.addPlaceholder(t.label).id+ placeholders.set(t.hostId, ph)+ team.set(ph, t.hostId)+ ops.bind(ph, t.sessionId)+ }+ return { opened, closed: plan.close }+ },++ closeTab(projectId) {+ const hostId = team.get(projectId)+ if (!hostId) return { remaining: [] }+ const remaining = [...team]+ .filter(([id, h]) => h === hostId && id !== projectId && ops.isOpenTab(id))+ .map(([id]) => id)+ const set = sets.get(hostId)+ if (set?.shown.includes(projectId)) sets.set(hostId, dismissTab(set, projectId))+ if (placeholders.get(hostId) === projectId) placeholders.delete(hostId)+ team.delete(projectId)+ if (remaining.length) ops.unbind(projectId)+ return { remaining }+ },++ teamOf: (projectId) => team.get(projectId)+ }+}diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.tsindex 16f794f92..52a1b4d7e 100644--- a/src/renderer/session/relay-tab.test.ts+++ b/src/renderer/session/relay-tab.test.ts@@ -13,6 +13,7 @@ import {sessionForProject,sessionCount,resetSessionsForTest,+ projectIdsBoundToSession,} from './session'import { LocalTransport } from '../terminal/local-transport'import { planActiveProjectDials } from '../lib/sshAttachments'@@ -530,3 +531,88 @@ describe('openRelayTab — hosted team tabs', () => {expect(sessionForProject(tab.projectId).id).toBe(tab.sessionId) // still bound})})++// ── Hosted team: one tab per shared project ───────────────────────────────────────────────────────++describe('openRelayTab — placing several shared projects (hosted team)', () => {+ const hostProjects = ['A', 'B'].map(+ (id) => ({ id, name: `Project ${id}`, color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] }) as Project+ )++ it('binds every placed tab to the one session and activates the first, or the focused one', async () => {+ const { api } = fakeBridgedApi({ version: 2, activeProjectId: 'A', projects: hostProjects })+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }+ const { deps, addProject, adoptProject, setActiveProject } = makeDeps({ handle })+ const placeProjects = vi.fn((_projects: Project[]) => ['A', 'B'])++ const tab = await openRelayTab('conn-1', 'Team', { ...deps, placeProjects })++ // The placer got every shared project, sanitized like the single adopt always was.+ expect(placeProjects).toHaveBeenCalledTimes(1)+ const placed = placeProjects.mock.calls[0][0]+ expect(placed.map((p) => p.id)).toEqual(['A', 'B'])+ expect(placed.every((p) => p.remote === true)).toBe(true)+ expect(adoptProject).not.toHaveBeenCalled()+ expect(addProject).not.toHaveBeenCalled()++ expect(tab.projectIds).toEqual(['A', 'B'])+ expect(tab.projectId).toBe('A')+ expect(projectIdsBoundToSession(tab.sessionId)).toEqual(['A', 'B'])+ expect(sessionForProject('B').id).toBe(tab.sessionId)+ expect(setActiveProject).toHaveBeenCalledWith('A')+ })++ it('activates focusProjectId when it is among the placed tabs, the first one otherwise', async () => {+ const { api } = fakeBridgedApi({ version: 2, activeProjectId: 'A', projects: hostProjects })+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }+ const { deps, setActiveProject } = makeDeps({ handle })++ const tab = await openRelayTab('conn-1', 'Team', { ...deps, placeProjects: () => ['A', 'B'], focusProjectId: 'B' })+ expect(tab.projectId).toBe('B')+ expect(setActiveProject).toHaveBeenCalledWith('B')++ const other = await openRelayTab('conn-2', 'Team', { ...deps, placeProjects: () => ['A', 'B'], focusProjectId: 'Z' })+ expect(other.projectId).toBe('A')+ })++ it('a placer that returns nothing still opens one labelled tab', async () => {+ const { api } = fakeBridgedApi({ version: 2, activeProjectId: '', projects: [] })+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }+ const { deps, addProject } = makeDeps({ handle })++ const tab = await openRelayTab('conn-1', 'Team', { ...deps, placeProjects: () => [] })+ expect(addProject).toHaveBeenCalledWith('Team')+ expect(tab.projectIds).toEqual(['proj-1'])+ expect(sessionForProject('proj-1').id).toBe(tab.sessionId)+ })++ it('without a placer (a Team Access tab) it adopts projects[0] alone, exactly as before', async () => {+ const { api } = fakeBridgedApi({ version: 2, activeProjectId: 'A', projects: hostProjects })+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }+ const { deps, adoptProject } = makeDeps({ handle })++ const tab = await openRelayTab('conn-1', 'Mac', deps)+ expect(adoptProject).toHaveBeenCalledTimes(1)+ expect((adoptProject.mock.calls[0][0] as Project).id).toBe('A')+ expect(tab.projectIds).toEqual(['A-adopted'])+ expect(tab.projectId).toBe('A-adopted')+ expect(projectIdsBoundToSession(tab.sessionId)).toEqual(['A-adopted'])+ })++ it('handleRelayDrop greys every tab the connection served', async () => {+ const { api } = fakeBridgedApi({ version: 2, activeProjectId: 'A', projects: hostProjects })+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }+ const { deps } = makeDeps({ handle })+ const tab = await openRelayTab('conn-1', 'Team', { ...deps, placeProjects: () => ['A', 'B'] })++ const setProjectUnavailable = vi.fn()+ handleRelayDrop(tab, { setProjectUnavailable })+ expect(setProjectUnavailable.mock.calls).toEqual([+ ['A', true],+ ['B', true],+ ])+ // Both stay bound to the (now offline) relay session, so each reconnects in place.+ expect(projectIdsBoundToSession(tab.sessionId)).toEqual(['A', 'B'])+ expect(sessionForProject('B').status).toBe('offline')+ })+})diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.tsindex 9d30d1850..6d48f93bc 100644--- a/src/renderer/session/relay-tab.ts+++ b/src/renderer/session/relay-tab.ts@@ -61,11 +61,21 @@ export interface RelayTabDeps {/** Switch to the tab once it is live (default true). A reconnect nobody clicked (boot, a dropped* tab coming back) binds its tab without taking the screen from whatever the user is on. */activate?: boolean+ /** HOSTED only: place the host's shared projects as tabs (one per project, reusing a reconnecting+ * team's greyed tabs) and return their ids in host order — never empty (a team with nothing+ * shared gets one placeholder). Absent = a Team Access tab: `projects[0]` exactly as before. */+ placeProjects?: (projects: Project[]) => string[]+ /** Activate this tab when it is among the placed ones (the one the user just shared). */+ focusProjectId?: string}export interface RelayTab {sessionId: string+ /** The tab activated on open: the focused one, else the first placed. */projectId: string+ /** Every tab this connection serves (one for a Team Access tab, one per shared project for a+ * hosted team), in the host's order. */+ projectIds: string[]/** A hosted team's tab: this device's role there and the team's name. Absent otherwise. */hosted?: HostedTeamInfo/** Tear the tab's session down (runs the held presence teardown + relay socket close, once). */@@ -130,18 +140,30 @@ export async function openRelayTab(// transport to the relay api; Stage-3 sync then keeps it live. If the host shared nothing (or the// project was deleted), OR we're reconnecting (no `adoptProject` dep — the existing tab is reused),// fall back to the labelled tab so it still opens rather than throwing.+ // A hosted team shares several projects through one connection: `placeProjects` turns each into+ // its own tab (id = the host's project id, since the relay api translates no ids), and every one+ // of them is bound to this session.// The load runs AFTER createSession + the held teardowns, so a host that vanishes between approval// and load would leave the SESSIONS entry, its presence subscription (the peer lingers in host// facepiles) and the relay socket all leaking. Dispose the just-created session before rethrowing// — `disposeSession` runs the held teardowns exactly once (idempotent).try {const ws = await handle.api.workspace.load()- const hostProject = ws.projects[0]+ let projectIds: string[]+ if (deps.placeProjects) {+ projectIds = deps.placeProjects(ws.projects.map(sanitizeRelayProject))+ } else {+ const hostProject = ws.projects[0]+ projectIds = [+ hostProject && deps.adoptProject+ ? deps.adoptProject(sanitizeRelayProject(hostProject)).id+ : deps.addProject(label).id+ ]+ }+ if (projectIds.length === 0) projectIds = [deps.addProject(label).id]+ for (const id of projectIds) bindProjectToSession(id, session.id)const projectId =- hostProject && deps.adoptProject- ? deps.adoptProject(sanitizeRelayProject(hostProject)).id- : deps.addProject(label).id- bindProjectToSession(projectId, session.id)+ deps.focusProjectId && projectIds.includes(deps.focusProjectId) ? deps.focusProjectId : projectIds[0]if (deps.activate !== false) {setActiveSession(session.id)deps.setActiveProject(projectId)@@ -158,6 +180,7 @@ export async function openRelayTab(return {sessionId: session.id,projectId,+ projectIds,...(hostedInfo ? { hosted: hostedInfo } : {}),dispose: () => disposeSession(session.id),}@@ -187,7 +210,8 @@ export interface RelayDropDeps {* reconnect in place. NEVER removes the project (that is only a user close). Idempotent. */export function handleRelayDrop(tab: RelayTab, deps: RelayDropDeps): void {takeSessionOffline(tab.sessionId)- deps.setProjectUnavailable(tab.projectId, true)+ // Every tab the connection served greys, so each one can reconnect in place.+ for (const id of tab.projectIds ?? [tab.projectId]) deps.setProjectUnavailable(id, true)}export interface RelayReconnectDeps {diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.tsindex 75bf54bfb..a8029139d 100644--- a/src/renderer/session/session.test.ts+++ b/src/renderer/session/session.test.ts@@ -17,6 +17,8 @@ import {activeSessionPresence,presenceForProject,projectIdsBoundToApi,+ unbindProject,+ projectIdsBoundToSession,} from './session'import { defaultPresence } from '../state/presence'import type { NodeTerminalApi } from '@shared/types'@@ -345,3 +347,24 @@ describe('projectIdsBoundToApi (a relay connection -> the tabs it serves)', () =expect(projectIdsBoundToApi(apiA)).toEqual([])})})++describe('unbindProject / projectIdsBoundToSession (one session serving several tabs)', () => {+ it('unbinds ONE project and leaves the session serving its other tabs', () => {+ const local = createSession('local', fakeApi, 'This Mac')+ setActiveSession(local.id)+ const relay = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, 'Team')+ bindProjectToSession('pa', relay.id)+ bindProjectToSession('pb', relay.id)+ expect(projectIdsBoundToSession(relay.id)).toEqual(['pa', 'pb'])++ unbindProject('pa')+ expect(projectIdsBoundToSession(relay.id)).toEqual(['pb'])+ expect(sessionForProject('pa')).toBe(local) // unbound → falls back to local+ expect(sessionForProject('pb')).toBe(relay)+ expect(sessionCount()).toBe(2) // the session itself lives on++ unbindProject('never-bound') // no-op+ expect(projectIdsBoundToSession(relay.id)).toEqual(['pb'])+ expect(projectIdsBoundToSession('relay-999')).toEqual([])+ })+})diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.tsindex 0bbf1f412..a1e658c43 100644--- a/src/renderer/session/session.ts+++ b/src/renderer/session/session.ts@@ -170,6 +170,17 @@ export function bindProjectToSession(projectId: string, sessionId: string): voidPROJECT_BINDINGS.set(projectId, sessionId)}+/** Unbind ONE project (a hosted team stopped sharing it, or the user closed that one of the team's+ * tabs). The session lives on for its other tabs. No-op when unbound. */+export function unbindProject(projectId: string): void {+ PROJECT_BINDINGS.delete(projectId)+}++/** Every project bound to `sessionId` (a hosted team's tabs, live or greyed). */+export function projectIdsBoundToSession(sessionId: string): string[] {+ return [...PROJECT_BINDINGS].filter(([, sid]) => sid === sessionId).map(([projectId]) => projectId)+}+/** The local session (the fallback every unbound tab resolves to), or the active one if — in a* node-environment test — no 'local' session was created. */function localOrActiveSession(): WorkspaceSession {