Skip to content

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.

fix(relay): hosted team tabs follow share events per connection and never save a placeholder

review5bbc6b118adc
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9e713ffa3..896be9bf8 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -565,8 +565,6 @@ import {
disposeSession,
holdSessionTeardown,
projectIdsBoundToSession,
- unbindProject,
- bindProjectToSession,
} from '../session/session'
import {
openRelayTab,
@@ -578,7 +576,8 @@ 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 { createTeamTabs, reconcileTeamTabs, type TeamTabs } from '../lib/hostedTeamTabs'
+import { isOpenTab, teamTabStoreOps } from '../lib/hostedTeamTabStore'
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'
@@ -910,12 +909,6 @@ interface HostedMountOpts {
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)
- return !!p && !p.closed
-}
-
/** What the agent-control handler's `reply` accepts, for helpers that build one outside it. */
type ControlReply = { ok: boolean; message?: string; result?: unknown; error?: string }
@@ -1546,33 +1539,11 @@ 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).
+ // One tab per shared project of a hosted team (lib/hostedTeamTabs.ts), over the store ops in
+ // lib/hostedTeamTabStore.ts; 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)
- })
+ const tabs: TeamTabs = createTeamTabs(teamTabStoreOps((id) => tabs.teamOf(id)))
return tabs
})
// A relay tab is a live client of a remote core — closing/deleting its project must tear the
@@ -1598,10 +1569,11 @@ export function Canvas() {
hostedJoinerRef.current?.tabClosed(projectId)
const s = sessionForProject(projectId)
for (const [connectionId, tab] of relayTabsRef.current) {
- // 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)
- }
+ // By session too: a team's last tab may be one a share event opened after the mount. Never
+ // while the connection still serves other tabs (one closed earlier lingers in `projectIds`).
+ const ours = tab.projectIds.includes(projectId) || (s.source === 'relay' && tab.sessionId === s.id)
+ const othersBound = projectIdsBoundToSession(tab.sessionId).some((id) => id !== projectId)
+ if (ours && !othersBound) relayTabsRef.current.delete(connectionId)
}
if (s.source === 'relay') {
disposeSession(s.id)
@@ -5255,12 +5227,16 @@ export function Canvas() {
.getState()
.projects.filter((x) => !x.closed && teamTabs.teamOf(x.id) === hostId)
.map((x) => x.id)
+ // The tabs the joiner was last told this connection serves. Events overlap (each commits
+ // its close half before awaiting its load), so an earlier event can settle after a later
+ // one closed tabs: each reconcile diffs the store against this set, never against a
+ // snapshot from when its own event began.
+ let known = [...tab.projectIds]
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 },
@@ -5270,18 +5246,14 @@ export function Canvas() {
)
.catch(() => {}) // never the user's error: the tabs that stand are in the store
.then(() => {
+ const r = reconcileTeamTabs(known, teamTabIds())
+ known = r.known
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)
- }
+ if (r.added.length) joiner.tabsAdded(hostId, r.added)
+ // Never tabClosed: a share event does not end the team. Closing its last tab does
+ // (disposeRelayTabForProject).
+ for (const id of r.removed) joiner.tabRemoved(id, r.known[0])
})
})
try {
diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.ts
index 416b23925..8b53ebba0 100644
--- a/src/renderer/canvas/hosted-team.source.test.ts
+++ b/src/renderer/canvas/hosted-team.source.test.ts
@@ -85,19 +85,27 @@ describe('hosted team glue in Canvas', () => {
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 joiner follows a per-connection set (lib/hostedTeamTabs.test.ts `reconcileTeamTabs`), seeded
+ // with the mount's tabs, never a per-event snapshot, and a share event never ends the team.
+ expect(body.indexOf('let known = [...tab.projectIds]')).toBeGreaterThan(capture)
+ expect(body.indexOf('let known = [...tab.projectIds]')).toBeLessThan(listen)
+ expect(handler).toContain('const r = reconcileTeamTabs(known, teamTabIds())')
+ expect(handler).toContain('known = r.known')
+ expect(handler).toContain('joiner.tabsAdded(hostId, r.added)')
+ expect(handler).toContain('for (const id of r.removed) joiner.tabRemoved(id, r.known[0])')
+ expect(handler.slice(0, handler.indexOf('holdSessionTeardown('))).not.toContain('tabClosed(')
+ expect(handler).not.toContain('const before =')
// 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', () => {
+ it('the team tab model runs on the store ops module (placeholder and removal: lib/hostedTeamTabStore.test.ts)', () => {
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')
+ expect(body).toContain('createTeamTabs(teamTabStoreOps((id) => tabs.teamOf(id)))')
+ expect(src).not.toContain('function isOpenTab(')
+ const store = readFileSync(new URL('../lib/hostedTeamTabStore.ts', import.meta.url), 'utf8')
+ expect(store).toContain('const next = store.deleteProject(id)')
+ expect(store).not.toContain('transport.destroy')
})
it('the joiner\'s mount names the team and where to land; the share flow joins through the joiner', () => {
@@ -148,6 +156,9 @@ describe('hosted team glue in Canvas', () => {
expect(multi).toBeGreaterThan(-1)
expect(multi).toBeLessThan(body.indexOf('hostedJoinerRef.current?.tabClosed(projectId)'))
expect(body).toContain('hostedJoinerRef.current?.tabRemoved(projectId, remaining[0])')
+ // A connection that still serves other tabs keeps its entry, even for a tab it once served.
+ expect(body).toContain('const othersBound = projectIdsBoundToSession(tab.sessionId).some((id) => id !== projectId)')
+ expect(body).toContain('if (ours && !othersBound) relayTabsRef.current.delete(connectionId)')
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)')
diff --git a/src/renderer/lib/hostedJoin.test.ts b/src/renderer/lib/hostedJoin.test.ts
index 9434ca1b7..d8495f720 100644
--- a/src/renderer/lib/hostedJoin.test.ts
+++ b/src/renderer/lib/hostedJoin.test.ts
@@ -721,6 +721,28 @@ describe('hosted joiner', () => {
expect(h.mounts[1].req).toMatchObject({ hostId: 'H1', code: codeFor('H1'), reconnectProjectId: 'C' })
})
+ it('a share event that replaces the placeholder (added, then removed onto it) keeps the team live in the new tab', 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, 'ph-1') // the team shared nothing: its placeholder is the tab
+ h.open.add('C')
+ j.tabsAdded('H1', ['C'])
+ j.tabRemoved('ph-1', 'C')
+ h.open.delete('ph-1')
+ expect(j.isHostedTab('C')).toBe(true)
+ expect(j.isHostedTab('ph-1')).toBe(false)
+ j.joinWithCode(codeFor('H1'))
+ expect(h.notices.at(-1)).toMatchObject({ kind: 'info', text: "You're already connected to box." })
+ expect(h.connects).toHaveLength(1)
+ h.closeCbs.get('c0')!(undefined)
+ await flush()
+ fireRetry(h)
+ h.connects[1].resolve('c1')
+ await flush()
+ expect(h.mounts[1].req).toMatchObject({ hostId: '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)
diff --git a/src/renderer/lib/hostedTeamTabStore.test.ts b/src/renderer/lib/hostedTeamTabStore.test.ts
new file mode 100644
index 000000000..d80e6e9c8
--- /dev/null
+++ b/src/renderer/lib/hostedTeamTabStore.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useProjects } from '../state/projects'
+import { codexApprovalCaps } from '../state/codexCli'
+import {
+ createSession,
+ resetSessionsForTest,
+ bindProjectToSession,
+ projectIdsBoundToSession,
+ sessionForProject
+} from '../session/session'
+import { handleRelayDrop } from '../session/relay-tab'
+import { createTeamTabs, type TeamTabs } from './hostedTeamTabs'
+import { teamTabStoreOps } from './hostedTeamTabStore'
+import type { NodeTerminalApi, Project } from '@shared/types'
+
+// The model's store side against the REAL projects store and session registry: what a hosted team's
+// placeholder and its tab removals do to the user's tabs and saved workspace.
+
+const team = { hostId: 'H1', label: 'Acme' }
+
+function hostProject(id: string): Project {
+ return { id, name: id, color: '#888', nodes: [], remote: true } as unknown as Project
+}
+
+function model(): TeamTabs {
+ const tabs: TeamTabs = createTeamTabs(teamTabStoreOps((id) => tabs.teamOf(id)))
+ return tabs
+}
+
+function relaySession(): string {
+ return createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, 'Acme').id
+}
+
+const store = () => useProjects.getState()
+const ids = () => store().projects.map((p) => p.id)
+const savedIds = () => store().toWorkspace().projects.map((p) => p.id)
+
+function freshApp(): void {
+ resetSessionsForTest()
+ createSession('local', { marker: 'local' } as unknown as NodeTerminalApi, 'This Mac')
+}
+
+beforeEach(() => {
+ freshApp()
+ store().hydrate({ version: 2, activeProjectId: '', projects: [] })
+})
+
+describe('the placeholder of a team with nothing shared', () => {
+ it('is a relay tab: never saved, not active on its own, and the codex probe calls it remote', () => {
+ const local = store().addProject('Mine')
+ store().setActive(local.id)
+ const [ph] = model().place(team, [], [], { keepActive: true })
+
+ expect(store().getProject(ph)).toMatchObject({ name: 'Acme', remote: true })
+ expect(store().activeProjectId).toBe(local.id)
+ expect(savedIds()).toEqual([local.id])
+ expect(codexApprovalCaps(undefined, ph).codexApprovalValues).toBeNull()
+ })
+
+ it('a restart and a boot reconnect leave no extra saved project behind', () => {
+ const [first] = model().place(team, [], [], { keepActive: false })
+ const saved = store().toWorkspace()
+
+ // Restart: the store comes back from disk, the model and the sessions start fresh.
+ freshApp()
+ store().hydrate(saved)
+ expect(ids()).toEqual([])
+ const [second] = model().place(team, [], [], { keepActive: false })
+
+ expect(second).not.toBe(first)
+ expect(ids()).toEqual([second])
+ expect(savedIds()).toEqual([])
+ })
+
+ it('a share event binds it, a drop greys it, and the first shared project replaces it', async () => {
+ const tabs = model()
+ const s = relaySession()
+ const [a] = tabs.place(team, [hostProject('A')], [], { keepActive: false })
+ bindProjectToSession(a, s) // openRelayTab binds what `place` returns
+
+ // The host stops sharing A: the model opens the placeholder and binds it itself.
+ await tabs.sharedChanged({ ...team, sessionId: s }, [], async () => [], { keepActive: false })
+ const [ph] = ids()
+ expect(store().getProject(ph)).toMatchObject({ name: 'Acme', remote: true })
+ expect(projectIdsBoundToSession(s)).toEqual([ph])
+ expect(sessionForProject(ph).id).toBe(s)
+ expect(savedIds()).toEqual([])
+
+ handleRelayDrop(
+ { sessionId: s, projectId: a, projectIds: [a], dispose: () => {} },
+ { setProjectUnavailable: (id, v) => store().setProjectUnavailable(id, v) }
+ )
+ expect(store().getProject(ph)?.unavailable).toBe(true)
+
+ await tabs.sharedChanged({ ...team, sessionId: s }, ['B'], async () => [hostProject('B')], { keepActive: false })
+ expect(ids()).toEqual(['B'])
+ expect(projectIdsBoundToSession(s)).toEqual(['B'])
+ expect(savedIds()).toEqual([])
+ })
+})
+
+describe('removeTab', () => {
+ const teamOf = (id: string) => (id === 'A' || id === 'B' ? 'H1' : undefined)
+
+ function seed(order: Array<{ id: string; closed?: boolean; team?: boolean }>, active: string): void {
+ store().hydrate({
+ version: 2,
+ activeProjectId: active,
+ projects: order.map(({ id, closed, team: t }) => ({
+ ...hostProject(id),
+ remote: !!t,
+ ...(closed ? { closed: true } : {})
+ }))
+ })
+ }
+
+ it('when the store hands the slot to a closed project, lands on the team\'s nearest open tab', () => {
+ seed([{ id: 'Mine' }, { id: 'A', team: true }, { id: 'Old', closed: true }, { id: 'B', team: true }], 'A')
+ teamTabStoreOps(teamOf).removeTab('A', 'H1')
+ expect(ids()).toEqual(['Mine', 'Old', 'B'])
+ expect(store().activeProjectId).toBe('B')
+ })
+
+ it('with no team tab left, lands on the nearest open project', () => {
+ seed([{ id: 'Mine' }, { id: 'A', team: true }, { id: 'Old', closed: true }], 'A')
+ teamTabStoreOps(teamOf).removeTab('A', 'H1')
+ expect(store().activeProjectId).toBe('Mine')
+ })
+
+ it('keeps the store\'s pick when it is open, and the active tab when it was not the removed one', () => {
+ seed([{ id: 'A', team: true }, { id: 'Other' }, { id: 'B', team: true }], 'A')
+ teamTabStoreOps(teamOf).removeTab('A', 'H1')
+ expect(store().activeProjectId).toBe('Other')
+
+ seed([{ id: 'Mine' }, { id: 'A', team: true }, { id: 'B', team: true }], 'Mine')
+ teamTabStoreOps(teamOf).removeTab('A', 'H1')
+ expect(store().activeProjectId).toBe('Mine')
+ })
+
+ it('removes from the store only (no unknown id error), and the last tab leaves the welcome screen', () => {
+ seed([{ id: 'A', team: true }], 'A')
+ teamTabStoreOps(teamOf).removeTab('missing', 'H1')
+ expect(ids()).toEqual(['A'])
+ teamTabStoreOps(teamOf).removeTab('A', 'H1')
+ expect(ids()).toEqual([])
+ expect(store().activeProjectId).toBe('')
+ })
+})
diff --git a/src/renderer/lib/hostedTeamTabStore.ts b/src/renderer/lib/hostedTeamTabStore.ts
new file mode 100644
index 000000000..10caca513
--- /dev/null
+++ b/src/renderer/lib/hostedTeamTabStore.ts
@@ -0,0 +1,50 @@
+// The team tab model's store side (`TeamTabOps`), against the projects store and the session
+// registry. Kept out of Canvas so the placeholder and the removal run under a test against the
+// real store.
+
+import { useProjects } from '../state/projects'
+import { bindProjectToSession, unbindProject } from '../session/session'
+import { openSuccessor, type TeamTabOps } from './hostedTeamTabs'
+
+/** Is this project an open tab (not closed, not deleted)? What a hosted reconnect is for (R40). */
+export function isOpenTab(projectId: string): boolean {
+ const p = useProjects.getState().getProject(projectId)
+ return !!p && !p.closed
+}
+
+/** `teamOf` is the model's own answer (the model is built from these ops, so it comes later). */
+export function teamTabStoreOps(teamOf: (projectId: string) => string | undefined): TeamTabOps {
+ return {
+ getProject: (id) => useProjects.getState().getProject(id),
+ isOpenTab,
+ adoptProject: (p) => useProjects.getState().adoptProject(p),
+ // A relay tab like the team's others (`remote`): the save filter drops it, so a restart never
+ // finds one on disk (a boot reconnect would otherwise add a second beside it), and whatever asks
+ // whether a project is a relay tab (the codex probe) says yes. Added like any project first, so
+ // it takes the store's name cap and does not take the screen.
+ addPlaceholder: (label) => {
+ const store = useProjects.getState()
+ const relay = { ...store.addProject(label), remote: true }
+ store.replaceProject(relay)
+ return relay
+ },
+ // The STORE delete, never Canvas's `deleteProject` (which ends the host's sessions through the
+ // relay transport): a hosted tab leaves this desktop only. When the removed tab was active, the
+ // store hands the active slot to whatever slid into it; only when that is a closed project (or
+ // none) does this pick an open neighbour, the same team's when it has one. The model's
+ // settleActive decides the rest.
+ 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) => teamOf(other) === hostId))
+ },
+ activeProjectId: () => useProjects.getState().activeProjectId ?? null,
+ setActive: (id) => useProjects.getState().setActive(id),
+ bind: (projectId, sessionId) => bindProjectToSession(projectId, sessionId),
+ unbind: (projectId) => unbindProject(projectId)
+ }
+}
diff --git a/src/renderer/lib/hostedTeamTabs.test.ts b/src/renderer/lib/hostedTeamTabs.test.ts
index 4e65abc75..f3ee3d83a 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, openSuccessor, type TeamTabOps } from './hostedTeamTabs'
+import { createTeamTabs, openSuccessor, reconcileTeamTabs, 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 => ({
@@ -491,6 +491,59 @@ describe('createTeamTabs', () => {
})
})
+describe('reconcileTeamTabs', () => {
+ it('reports the tabs gone and the tabs new since the joiner was last told', () => {
+ expect(reconcileTeamTabs(['A', 'B'], ['B', 'C'])).toEqual({ removed: ['A'], added: ['C'], known: ['B', 'C'] })
+ expect(reconcileTeamTabs(['ph-1'], ['C'])).toEqual({ removed: ['ph-1'], added: ['C'], known: ['C'] })
+ expect(reconcileTeamTabs(['A'], ['A'])).toEqual({ removed: [], added: [], known: ['A'] })
+ })
+
+ it('with no open team tab, removes nothing and keeps what it knew for the next reconcile', () => {
+ expect(reconcileTeamTabs(['A', 'B'], [])).toEqual({ removed: [], added: [], known: ['A', 'B'] })
+ })
+
+ it('an earlier event reconciled after a later one closed every tab ends nothing; the later one moves the team on', async () => {
+ // The joiner as Canvas drives it: what it was told, in order.
+ const joiner: string[] = []
+ const f = fakeOps([local('mine')], 'mine')
+ const tabs = createTeamTabs(f.ops)
+ const placed = tabs.place(team, [], [], { keepActive: true })
+ for (const id of placed) f.ops.bind(id, 'relay-1')
+ let known = [...placed]
+ const seen: string[][] = []
+ const teamTabIds = () => f.state.projects.filter((p) => !p.closed && tabs.teamOf(p.id) === 'host-1').map((p) => p.id)
+ // Canvas's handler: run the event, then reconcile from the store whether it resolved or not.
+ const follow = (ids: string[], load: () => Promise<Project[]>) =>
+ tabs
+ .sharedChanged(live, ids, load, { keepActive: true })
+ .catch(() => {})
+ .then(() => {
+ const after = teamTabIds()
+ seen.push(after)
+ const r = reconcileTeamTabs(known, after)
+ known = r.known
+ if (r.added.length) joiner.push(`added:${r.added.join(',')}`)
+ for (const id of r.removed) joiner.push(`removed:${id}->${r.known[0]}`)
+ })
+
+ const l1 = deferred<Project[]>()
+ const l2 = deferred<Project[]>()
+ const e1 = follow(['A', 'B'], () => l1.promise)
+ const e2 = follow(['C'], () => l2.promise) // a full replace, queued behind e1
+ l1.resolve([A, B])
+ await e1
+ // e2's close half ran before e1's reconcile: the team had no open tab at that moment…
+ expect(seen).toEqual([[]])
+ // …and the joiner was told nothing (a "tab closed" here would release the live connection).
+ expect(joiner).toEqual([])
+ l2.resolve([C])
+ await e2
+ expect(seen.at(-1)).toEqual(['C'])
+ expect(joiner).toEqual(['added:C', 'removed:ph-1->C'])
+ expect(known).toEqual(['C'])
+ })
+})
+
describe('openSuccessor', () => {
const tab = (id: string, closed = false) => ({ id, closed })
diff --git a/src/renderer/lib/hostedTeamTabs.ts b/src/renderer/lib/hostedTeamTabs.ts
index 943ad1054..2732470aa 100644
--- a/src/renderer/lib/hostedTeamTabs.ts
+++ b/src/renderer/lib/hostedTeamTabs.ts
@@ -90,6 +90,25 @@ export function openSuccessor(
return nearest((p) => sameTeam(p.id)) ?? nearest(() => true) ?? ''
}
+/** What the joiner must follow after a share event settled, read back from the store (the event can
+ * reject and still have closed tabs, so its own result says too little). `known` is what the joiner
+ * was last told this connection serves, `after` the team's open tabs now, in store order.
+ * `removed` = tabs gone since, each to move onto the first of the returned `known`; `added` = tabs
+ * new since. While the team has no open tab at all, nothing is removed and `known` is kept: another
+ * event for the team may sit between closing its tabs and opening the new ones, and a removal needs
+ * a tab to move onto. A share event never ends the team in the joiner; closing its last tab does. */
+export function reconcileTeamTabs(
+ known: readonly string[],
+ after: readonly string[]
+): { removed: string[]; added: string[]; known: string[] } {
+ if (after.length === 0) return { removed: [], added: [], known: [...known] }
+ return {
+ removed: known.filter((id) => !after.includes(id)),
+ added: after.filter((id) => !known.includes(id)),
+ known: [...after]
+ }
+}
+
/** 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>()