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 tabs keep the host id, order share events and grey every bound tab

reviewfa3f8372835e
diff --git a/src/renderer/lib/hostedTabs.ts b/src/renderer/lib/hostedTabs.ts
index 67c976572..eb92c32f1 100644
--- a/src/renderer/lib/hostedTabs.ts
+++ b/src/renderer/lib/hostedTabs.ts
@@ -18,7 +18,9 @@ export const EMPTY_TAB_SET: HostedTabSet = Object.freeze({ shown: [], dismissed:
const MAX = 256
-const clean = (ids: readonly unknown[]): string[] =>
+/** The host's project ids, made safe to act on: non-empty strings of at most 128 characters,
+ * first occurrence kept, at most 256. */
+export const cleanSharedIds = (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
@@ -27,7 +29,7 @@ export function planSharedChange(
set: HostedTabSet,
shared: readonly string[]
): { open: string[]; close: string[]; next: HostedTabSet } {
- const ids = clean(shared)
+ const ids = cleanSharedIds(shared)
const open = ids.filter((id) => !set.shown.includes(id) && !set.dismissed.includes(id))
const close = set.shown.filter((id) => !ids.includes(id))
return {
diff --git a/src/renderer/lib/hostedTeamTabs.test.ts b/src/renderer/lib/hostedTeamTabs.test.ts
index 1989ee467..3895c56b7 100644
--- a/src/renderer/lib/hostedTeamTabs.test.ts
+++ b/src/renderer/lib/hostedTeamTabs.test.ts
@@ -2,7 +2,17 @@ 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: [] })
+/** A host's shared project, as the relay hands it over (`sanitizeRelayProject` marks it remote). */
+const proj = (id: string, name = id): Project => ({
+ id,
+ name,
+ color: '#fff',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [],
+ remote: true
+})
+/** One of the user's own local projects. */
+const local = (id: string): Project => ({ id, name: id, color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] })
const A = proj('A', 'Alpha')
const B = proj('B', 'Beta')
@@ -11,61 +21,104 @@ 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 deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (err: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
+/** An in-memory stand-in for the projects store + the session registry's bindings, shaped like the
+ * real ones: `adoptProject` activates what it adopts and derives a fresh id when the id is taken,
+ * `addPlaceholder` (the store's `addProject`) does not activate, `removeTab` hands the active slot
+ * to the project that moves into it (the store's delete), `close` keeps the project marked closed
+ * (the store's closeProject), and `bind` throws for a disposed session. */
function fakeOps(initial: Project[] = [], active: string | null = null) {
- const projects = new Map<string, Project>(initial.map((p) => [p.id, p]))
+ const state = { projects: [...initial], active, placeholders: 0, disposed: new Set<string>() }
const bindings = new Map<string, string>()
- const state = { active, placeholders: 0 }
+ const calls: string[] = []
+ const find = (id: string): Project | undefined => state.projects.find((p) => p.id === id)
const ops: TeamTabOps = {
- getProject: (id) => projects.get(id),
+ getProject: find,
isOpenTab: (id) => {
- const p = projects.get(id)
+ const p = find(id)
return !!p && !p.closed
},
adoptProject: vi.fn((p: Project) => {
- projects.set(p.id, p)
- state.active = p.id
- return { id: p.id }
+ const adopted = find(p.id) ? { ...p, id: `${p.id}~derived` } : p
+ state.projects.push(adopted)
+ state.active = adopted.id
+ return { id: adopted.id }
}),
addPlaceholder: vi.fn((label: string) => {
const id = `ph-${++state.placeholders}`
- projects.set(id, { ...proj(id), name: label })
+ state.projects.push({ ...local(id), name: label })
return { id }
}),
removeTab: vi.fn((id: string) => {
- projects.delete(id)
+ calls.push(`remove:${id}`)
+ const index = state.projects.findIndex((p) => p.id === id)
+ if (index < 0) return
+ state.projects.splice(index, 1)
+ if (state.active === id) {
+ state.active = state.projects.length ? state.projects[Math.min(index, state.projects.length - 1)].id : null
+ }
}),
activeProjectId: () => state.active,
setActive: (id) => {
state.active = id
},
- bind: (projectId, sessionId) => {
+ bind: vi.fn((projectId: string, sessionId: string) => {
+ if (state.disposed.has(sessionId)) throw new Error(`[session] no session ${sessionId}`)
bindings.set(projectId, sessionId)
- },
- unbind: (projectId) => {
+ }),
+ unbind: vi.fn((projectId: string) => {
+ calls.push(`unbind:${projectId}`)
bindings.delete(projectId)
+ })
+ }
+ return {
+ ops,
+ state,
+ bindings,
+ calls,
+ has: (id: string) => !!find(id),
+ ids: () => state.projects.map((p) => p.id),
+ close: (id: string) => {
+ const index = state.projects.findIndex((p) => p.id === id)
+ state.projects = state.projects.map((p) => (p.id === id ? { ...p, closed: true } : p))
+ if (state.active === id) {
+ const open = state.projects
+ .map((p, i) => ({ p, d: Math.abs(i - index) }))
+ .filter(({ p }) => !p.closed)
+ .sort((a, b) => a.d - b.d)
+ state.active = open.length ? open[0].p.id : null
+ }
+ },
+ dispose: (sessionId: string) => {
+ state.disposed.add(sessionId)
}
}
- 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 f = fakeOps([local('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.ids()).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')
+ const g = fakeOps([local('mine')], 'mine')
createTeamTabs(g.ops).place(team, [A, B], [], { keepActive: false })
expect(g.state.active).toBe('B')
})
@@ -75,7 +128,7 @@ describe('createTeamTabs', () => {
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(f.state.projects.find((p) => p.id === '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.
@@ -83,17 +136,19 @@ describe('createTeamTabs', () => {
expect(f.ops.addPlaceholder).toHaveBeenCalledTimes(1)
})
- it('place on reconnect: reuses the existing tabs by id, removes a tab that is no longer shared', () => {
+ it('place on reconnect: reuses the existing tabs by id, unbinds then 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'])
+ for (const id of tabs.place(team, [A, B], [], { keepActive: false })) f.ops.bind(id, 'relay-1')
// 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(f.has('A')).toBe(true)
+ expect(f.has('B')).toBe(false)
+ expect(f.bindings.has('B')).toBe(false)
+ expect(f.calls.indexOf('unbind:B')).toBeGreaterThanOrEqual(0)
+ expect(f.calls.indexOf('unbind:B')).toBeLessThan(f.calls.indexOf('remove:B'))
expect(tabs.teamOf('B')).toBeUndefined()
})
@@ -103,11 +158,45 @@ describe('createTeamTabs', () => {
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
+ f.close('B') // the store keeps the closed tab, marked 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)
+ expect(f.ops.isOpenTab('B')).toBe(false)
+ })
+
+ it('place: the host list is cleaned (duplicates, empty and overlong ids) before anything is adopted', () => {
+ const f = fakeOps()
+ const tabs = createTeamTabs(f.ops)
+
+ expect(tabs.place(team, [A, A, proj(''), proj('x'.repeat(129)), B], [], { keepActive: false })).toEqual(['A', 'B'])
+ expect(f.ops.adoptProject).toHaveBeenCalledTimes(2)
+ expect(f.ids()).toEqual(['A', 'B'])
+ })
+
+ it('place on reconnect: a closed copy whose dismissal was forgotten reopens under the host id, never a derived one', 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')
+ tabs.closeTab('B')
+ f.close('B')
+ // The host stops sharing B, which forgets the dismissal; the store still holds the closed copy.
+ await tabs.sharedChanged(live, ['A'], async () => [A], { keepActive: false })
+
+ expect(tabs.place(team, [A, B], ['A'], { keepActive: false })).toEqual(['A', 'B'])
+ expect(f.ops.isOpenTab('B')).toBe(true)
+ expect(f.ids().some((id) => id.includes('~derived'))).toBe(false)
+ })
+
+ it('a closed LOCAL project holding the host id is never removed, and no tab opens under another id', () => {
+ const f = fakeOps([{ ...local('B'), closed: true }])
+ const tabs = createTeamTabs(f.ops)
+
+ expect(tabs.place(team, [A, B], [], { keepActive: false })).toEqual(['A'])
+ expect(f.state.projects.find((p) => p.id === 'B')).toMatchObject({ closed: true })
+ expect(f.ops.removeTab).not.toHaveBeenCalled()
+ expect(f.ids().some((id) => id.includes('~derived'))).toBe(false)
+ expect(tabs.teamOf('B')).toBeUndefined()
})
it('sharedChanged: opens and binds a newly shared project, loading the workspace only when something opens', async () => {
@@ -123,7 +212,7 @@ describe('createTeamTabs', () => {
})
expect(load).toHaveBeenCalledTimes(1)
expect(f.bindings.get('C')).toBe('relay-1')
- expect(f.projects.has('C')).toBe(true)
+ expect(f.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
@@ -146,7 +235,7 @@ describe('createTeamTabs', () => {
opened: [],
closed: ['B']
})
- expect(f.projects.has('B')).toBe(false)
+ expect(f.has('B')).toBe(false)
expect(f.bindings.has('B')).toBe(false)
expect(f.bindings.get('A')).toBe('relay-1')
expect(tabs.teamOf('B')).toBeUndefined()
@@ -155,9 +244,9 @@ describe('createTeamTabs', () => {
opened: [],
closed: ['A']
})
- expect(f.projects.has('A')).toBe(false)
+ expect(f.has('A')).toBe(false)
expect(f.bindings.has('A')).toBe(false)
- expect(f.projects.get('ph-1')?.name).toBe('Team X')
+ expect(f.state.projects.find((p) => p.id === '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()
@@ -173,20 +262,187 @@ describe('createTeamTabs', () => {
opened: ['A'],
closed: []
})
- expect(f.projects.has('A')).toBe(true)
+ expect(f.has('A')).toBe(true)
expect(f.bindings.get('A')).toBe('relay-1')
- expect(f.projects.has('ph-1')).toBe(false)
+ expect(f.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('sharedChanged: a closed copy of a former tab is replaced, so a re-share reopens it under its own id', 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')
+ expect(tabs.closeTab('B')).toEqual({ remaining: ['A'] })
+ f.close('B')
+
+ await tabs.sharedChanged(live, ['A'], async () => [A], { keepActive: false }) // unshare
+ await expect(tabs.sharedChanged(live, ['A', 'B'], async () => [A, B], { keepActive: false })).resolves.toEqual({
+ opened: ['B'],
+ closed: []
+ })
+ expect(f.ops.isOpenTab('B')).toBe(true)
+ expect(f.bindings.get('B')).toBe('relay-1')
+ expect(tabs.teamOf('B')).toBe('host-1')
+ expect(f.ids().some((id) => id.includes('~derived'))).toBe(false)
+ })
+
+ it('sharedChanged: a store that derives an id anyway gets no tab under it, and the user stays put', async () => {
+ const f = fakeOps([local('mine')], 'mine')
+ const tabs = createTeamTabs(f.ops)
+ tabs.place(team, [A], [], { keepActive: true })
+ // A store that minted the id against state this renderer has not seen yet.
+ f.ops.adoptProject = vi.fn((p: Project) => {
+ const adopted = { ...p, id: `${p.id}~derived` }
+ f.state.projects.push(adopted)
+ f.state.active = adopted.id
+ return { id: adopted.id }
+ })
+
+ await expect(tabs.sharedChanged(live, ['A', 'C'], async () => [A, C], { keepActive: false })).resolves.toEqual({
+ opened: [],
+ closed: []
+ })
+ expect(f.ids()).toEqual(['mine', 'A'])
+ expect(f.state.active).toBe('mine')
+ expect(f.bindings.size).toBe(0)
+ })
+
+ it('sharedChanged: shown counts only open tabs, so a team whose tabs were all closed gets its placeholder', async () => {
+ const f = fakeOps()
+ const tabs = createTeamTabs(f.ops)
+ for (const id of tabs.place(team, [A], [], { keepActive: false })) f.ops.bind(id, 'relay-1')
+ f.close('A') // closed in the store, behind the controller's back
+
+ await tabs.sharedChanged(live, ['A'], async () => [A], { keepActive: false })
+ expect(f.bindings.get('ph-1')).toBe('relay-1')
+ expect(tabs.teamOf('ph-1')).toBe('host-1')
+ })
+
+ it('sharedChanged: a user on the placeholder lands on the newly opened tab, never on the store fallback', async () => {
+ const f = fakeOps([local('mine')], 'mine')
+ const tabs = createTeamTabs(f.ops)
+ const [ph] = tabs.place(team, [], [], { keepActive: false })
+ f.ops.bind(ph, 'relay-1')
+ f.state.projects.push({ ...local('later'), closed: true }) // a project the user made and closed meanwhile
+ f.ops.setActive(ph) // the user is looking at the team's placeholder
+
+ await tabs.sharedChanged(live, ['A'], async () => [A], { keepActive: true })
+ expect(f.state.active).toBe('A')
+ expect(f.ops.isOpenTab(f.state.active as string)).toBe(true)
+ })
+
+ it('sharedChanged: a user on a tab the host unshares lands on another of the team tabs', async () => {
+ const f = fakeOps([local('mine')], 'mine')
+ const tabs = createTeamTabs(f.ops)
+ for (const id of tabs.place(team, [A, B], [], { keepActive: false })) f.ops.bind(id, 'relay-1')
+ f.state.projects.push({ ...local('later'), closed: true })
+ f.ops.setActive('B')
+
+ await tabs.sharedChanged(live, ['A'], async () => [A], { keepActive: true })
+ expect(f.state.active).toBe('A')
+ })
+
+ it('sharedChanged: a rejected load applies the closes, opens nothing, and a later re-share opens the project', 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 expect(
+ tabs.sharedChanged(live, ['A', 'C'], async () => {
+ throw new Error('relay hiccup')
+ }, { keepActive: false })
+ ).rejects.toThrow('relay hiccup')
+ expect(f.has('B')).toBe(false)
+ expect(tabs.teamOf('B')).toBeUndefined()
+ expect(f.has('C')).toBe(false)
+ expect(f.ops.addPlaceholder).not.toHaveBeenCalled() // A is still shown
+
+ await expect(tabs.sharedChanged(live, ['A', 'B'], async () => [A, B], { keepActive: false })).resolves.toEqual({
+ opened: ['B'],
+ closed: []
+ })
+ expect(f.ops.isOpenTab('B')).toBe(true)
+ })
+
+ it('sharedChanged: overlapping events apply in order, each against the set the previous one left', async () => {
+ const f = fakeOps()
+ const tabs = createTeamTabs(f.ops)
+ tabs.place(team, [A], [], { keepActive: false })
+ const first = deferred<Project[]>()
+ const secondLoad = vi.fn(async () => [A])
+
+ const e1 = tabs.sharedChanged(live, ['A', 'B'], () => first.promise, { keepActive: false })
+ const e2 = tabs.sharedChanged(live, ['A'], secondLoad, { keepActive: false })
+ first.resolve([A, B])
+
+ await expect(e1).resolves.toEqual({ opened: ['B'], closed: [] })
+ await expect(e2).resolves.toEqual({ opened: [], closed: ['B'] })
+ expect(f.has('B')).toBe(false)
+ expect(f.bindings.has('B')).toBe(false)
+ expect(tabs.teamOf('B')).toBeUndefined()
+ expect(secondLoad).not.toHaveBeenCalled()
+ })
+
+ it('sharedChanged: a session disposed during the load gets no tab; the adopted one is removed', async () => {
+ const f = fakeOps()
+ const tabs = createTeamTabs(f.ops)
+ for (const id of tabs.place(team, [A], [], { keepActive: false })) f.ops.bind(id, 'relay-1')
+
+ await expect(
+ tabs.sharedChanged(live, ['A', 'C'], async () => {
+ f.dispose('relay-1')
+ return [A, C]
+ }, { keepActive: false })
+ ).rejects.toThrow(/no session/)
+ expect(f.has('C')).toBe(false)
+ expect(tabs.teamOf('C')).toBeUndefined()
+ expect(f.has('A')).toBe(true)
+ })
+
+ it('sharedChanged: an event in flight when the team remounts changes nothing', async () => {
+ const f = fakeOps()
+ const tabs = createTeamTabs(f.ops)
+ for (const id of tabs.place(team, [A], [], { keepActive: false })) f.ops.bind(id, 'relay-1')
+ const load = deferred<Project[]>()
+
+ const stale = tabs.sharedChanged(live, ['A', 'B'], () => load.promise, { keepActive: false })
+ // The connection drops and remounts; the new workspace shares only A.
+ expect(tabs.place(team, [A], ['A'], { keepActive: false })).toEqual(['A'])
+ load.resolve([A, B])
+
+ await expect(stale).resolves.toEqual({ opened: [], closed: [] })
+ expect(f.has('B')).toBe(false)
+ expect(f.bindings.has('B')).toBe(false)
+ })
+
+ it('sharedChanged: a remount while the workspace loads makes the event open nothing', async () => {
+ const f = fakeOps()
+ const tabs = createTeamTabs(f.ops)
+ for (const id of tabs.place(team, [A], [], { keepActive: false })) f.ops.bind(id, 'relay-1')
+ const load = deferred<Project[]>()
+ const loading = deferred<void>()
+
+ const stale = tabs.sharedChanged(live, ['A', 'B'], () => {
+ loading.resolve()
+ return load.promise
+ }, { keepActive: false })
+ await loading.promise // the event is now waiting on the host's workspace
+ expect(tabs.place(team, [A], ['A'], { keepActive: false })).toEqual(['A'])
+ load.resolve([A, B])
+
+ await expect(stale).resolves.toEqual({ opened: [], closed: [] })
+ expect(f.has('B')).toBe(false)
+ expect(f.bindings.has('B')).toBe(false)
+ })
+
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 })
+ f.close('C')
expect(tabs.closeTab('A')).toEqual({ remaining: ['B'] })
expect(f.bindings.has('A')).toBe(false)
@@ -202,4 +458,19 @@ describe('createTeamTabs', () => {
// A tab that belongs to no team reports nothing and touches nothing.
expect(tabs.closeTab('mine')).toEqual({ remaining: [] })
})
+
+ it('closeTab: closing the last tab forgets the team, so a later join is not shadowed by an old dismissal', () => {
+ 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')
+ expect(tabs.closeTab('A')).toEqual({ remaining: ['B'] })
+ f.close('A')
+ expect(tabs.closeTab('B')).toEqual({ remaining: [] })
+ f.close('B')
+
+ // The user joins the team again in the same run.
+ expect(tabs.place(team, [A, B], [], { keepActive: false })).toEqual(['A', 'B'])
+ expect(f.ops.isOpenTab('A')).toBe(true)
+ expect(f.ops.isOpenTab('B')).toBe(true)
+ })
})
diff --git a/src/renderer/lib/hostedTeamTabs.ts b/src/renderer/lib/hostedTeamTabs.ts
index df5d898e0..20d3df411 100644
--- a/src/renderer/lib/hostedTeamTabs.ts
+++ b/src/renderer/lib/hostedTeamTabs.ts
@@ -3,25 +3,33 @@
// 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.)
+// id would ask the host about a project it does not know. A tab is therefore never opened under a
+// derived id: when the store holds a CLOSED relay copy under that id (a former tab of a hosted
+// team), the copy is replaced; when it holds anything else (an open tab, or one of the user's own
+// local projects, closed or not), that project is skipped rather than renamed.
// - `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.
+// greyed tabs by id, so their nodes and their place in the tab bar survive, and it unbinds and
+// 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 closes the
+// tabs of unshared projects and opens a tab for each newly shared one. Events for one team run
+// one at a time, each against the set the previous one left; the close half is committed before
+// the workspace load is awaited, so a failed load leaves no half-applied event behind. An event
+// that began before the team remounted (or was closed) changes nothing: the newer mount decided.
// - `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.
+// reopened while it stays shared) and the connection lives on for the team's other tabs. The last
+// tab's close leaves its binding alone, for the caller that ends the connection, and forgets the
+// team, so a later join in the same run starts clean.
// - 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.
+// - When a tab the user was looking at goes away, they land on another of the team's open tabs,
+// never on whatever the store falls back to (which can be a closed project).
//
// 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'
+import { EMPTY_TAB_SET, cleanSharedIds, dismissTab, planSharedChange, type HostedTabSet } from './hostedTabs'
export interface TeamTabOps {
getProject(id: string): Project | undefined
@@ -44,11 +52,12 @@ export interface TeamRef {
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. */
+ * id and unbinding 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. */
+ * the newly shared ones, calling `load` for the host's workspace only when something opens.
+ * Rejects when the load fails or the session is gone; the closes it made still stand. */
sharedChanged(
team: TeamRef & { sessionId: string },
projectIds: string[],
@@ -62,16 +71,63 @@ export interface TeamTabs {
teamOf(projectId: string): string | undefined
}
+/** 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>()
+ for (const p of projects) if (p && typeof p.id === 'string' && !byId.has(p.id)) byId.set(p.id, p)
+ return cleanSharedIds([...byId.keys()]).map((id) => byId.get(id) as Project)
+}
+
export function createTeamTabs(ops: TeamTabOps): TeamTabs {
const sets = new Map<string, HostedTabSet>()
const placeholders = new Map<string, string>()
const team = new Map<string, string>()
+ // Bumped by every (re)mount and by the team's last tab closing: a share event that began before
+ // describes a connection that has been replaced or ended.
+ const epochs = new Map<string, number>()
+ // One share event at a time per team.
+ const chains = new Map<string, Promise<void>>()
- // 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 epochOf = (hostId: string): number => epochs.get(hostId) ?? 0
+ const bumpEpoch = (hostId: string): void => {
+ epochs.set(hostId, epochOf(hostId) + 1)
}
+ const isTeamTab = (id: string, hostId: string): boolean => team.get(id) === hostId && ops.isOpenTab(id)
+
+ /** Keep the user on their tab when asked. When the tab they were on was this team's and is gone,
+ * move them to the team's first open tab (or its placeholder) unless they already sit on one. */
+ const settleActive = (prev: string | null, prevWasTeam: boolean, keep: boolean, hostId: string): void => {
+ if (prev && ops.isOpenTab(prev)) {
+ if (keep) ops.setActive(prev)
+ return
+ }
+ if (!prevWasTeam) return
+ const current = ops.activeProjectId()
+ if (current && isTeamTab(current, hostId)) return
+ const next = (sets.get(hostId)?.shown ?? []).find((id) => isTeamTab(id, hostId)) ?? placeholders.get(hostId)
+ 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 => {
+ 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)
+ }
+ const before = ops.activeProjectId()
+ const id = ops.adoptProject(p).id
+ if (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)
+ if (before && ops.isOpenTab(before)) ops.setActive(before)
+ return null
+ }
+
const dropPlaceholder = (hostId: string): void => {
const ph = placeholders.get(hostId)
if (!ph) return
@@ -81,71 +137,138 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {
ops.removeTab(ph)
}
+ const applyShared = async (
+ t: TeamRef & { sessionId: string },
+ projectIds: string[],
+ load: () => Promise<Project[]>,
+ opts: { keepActive: boolean },
+ epoch: number
+ ): Promise<{ opened: string[]; closed: string[] }> => {
+ const host = t.hostId
+ if (epochOf(host) !== epoch) return { opened: [], closed: [] }
+ const prev = ops.activeProjectId()
+ const prevWasTeam = !!prev && team.get(prev) === host
+ const set = sets.get(host) ?? EMPTY_TAB_SET
+ const plan = planSharedChange(set, projectIds)
+ for (const id of plan.close) {
+ team.delete(id)
+ ops.unbind(id)
+ ops.removeTab(id)
+ }
+ // Commit the close half before awaiting: a failed load, or the next event, reads a set
+ // without the closed tabs.
+ sets.set(host, { shown: set.shown.filter((id) => !plan.close.includes(id)), dismissed: plan.next.dismissed })
+
+ const opened: string[] = []
+ let failure: { error: unknown } | null = null
+ let sessionGone = false
+ if (plan.open.length) {
+ let loaded: Project[] = []
+ try {
+ loaded = await load()
+ } catch (error) {
+ failure = { error }
+ }
+ 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)
+ if (!id) continue
+ try {
+ 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)
+ failure = { error }
+ sessionGone = true
+ break
+ }
+ team.set(id, host)
+ opened.push(id)
+ }
+ }
+
+ // Shown = the host's order, limited to what is still this team's open tab (a tab the user
+ // closed during the load is dismissed, not shown).
+ const fresh = sets.get(host) ?? EMPTY_TAB_SET
+ const shown = plan.next.shown.filter(
+ (id) => (fresh.shown.includes(id) || opened.includes(id)) && isTeamTab(id, host)
+ )
+ sets.set(host, { shown, dismissed: fresh.dismissed })
+ if (shown.length > 0) dropPlaceholder(host)
+ else if (!sessionGone && !placeholders.has(host)) {
+ const ph = ops.addPlaceholder(t.label).id
+ try {
+ ops.bind(ph, t.sessionId)
+ placeholders.set(host, ph)
+ team.set(ph, host)
+ } catch (error) {
+ ops.removeTab(ph)
+ failure = failure ?? { error }
+ }
+ }
+ settleActive(prev, prevWasTeam, opts.keepActive, host)
+ if (failure) throw failure.error
+ return { opened, closed: plan.close }
+ }
+
return {
place(t, projects, existing, opts) {
+ const host = t.hostId
+ bumpEpoch(host)
const prev = ops.activeProjectId()
- const set = sets.get(t.hostId) ?? EMPTY_TAB_SET
+ const prevWasTeam = !!prev && (team.get(prev) === host || existing.includes(prev))
+ const set = sets.get(host) ?? EMPTY_TAB_SET
+ const shared = cleanProjects(projects)
const reuse = new Set(existing)
const ids: string[] = []
- for (const p of projects) {
+ for (const p of shared) {
if (set.dismissed.includes(p.id)) continue
- ids.push(reuse.has(p.id) && ops.getProject(p.id) ? p.id : ops.adoptProject(p).id)
+ const id = reuse.has(p.id) && ops.isOpenTab(p.id) ? p.id : tabFor(p)
+ if (id) ids.push(id)
}
- const ph = placeholders.get(t.hostId)
+ const ph = placeholders.get(host)
for (const id of existing) {
- if (!ids.includes(id) && id !== ph) {
- team.delete(id)
- ops.removeTab(id)
- }
+ if (ids.includes(id) || id === ph) continue
+ team.delete(id)
+ ops.unbind(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))
+ const dismissed = set.dismissed.filter((d) => shared.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 })
+ if (ph && !ops.isOpenTab(ph)) team.delete(ph)
+ const keep = ph && ops.isOpenTab(ph) ? ph : ops.addPlaceholder(t.label).id
+ placeholders.set(host, keep)
+ team.set(keep, host)
+ sets.set(host, { shown: [], dismissed })
+ settleActive(prev, prevWasTeam, opts.keepActive, host)
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)
+ if (ph) dropPlaceholder(host)
+ for (const id of ids) team.set(id, host)
+ sets.set(host, { shown: ids, dismissed })
+ settleActive(prev, prevWasTeam, opts.keepActive, host)
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 }
+ sharedChanged(t, projectIds, load, opts) {
+ const host = t.hostId
+ // The epoch is read when the event arrives: one queued behind an older event is still stale
+ // if the team remounts before it runs.
+ const epoch = epochOf(host)
+ const prior = chains.get(host) ?? Promise.resolve()
+ const result = prior.then(() => applyShared(t, projectIds, load, opts, epoch))
+ const settled = result.then(
+ () => undefined,
+ () => undefined
+ )
+ chains.set(host, settled)
+ void settled.then(() => {
+ if (chains.get(host) === settled) chains.delete(host)
+ })
+ return result
},
closeTab(projectId) {
@@ -158,7 +281,16 @@ export function createTeamTabs(ops: TeamTabOps): TeamTabs {
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)
+ if (remaining.length) {
+ ops.unbind(projectId)
+ return { remaining }
+ }
+ // The team's last tab: forget the team, so a later join in this run is not shadowed by its
+ // dismissals, and a share event still in flight changes nothing.
+ sets.delete(hostId)
+ placeholders.delete(hostId)
+ for (const [id, h] of [...team]) if (h === hostId) team.delete(id)
+ bumpEpoch(hostId)
return { remaining }
},
diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.ts
index 52a1b4d7e..2dcd26cc2 100644
--- a/src/renderer/session/relay-tab.test.ts
+++ b/src/renderer/session/relay-tab.test.ts
@@ -14,6 +14,7 @@ import {
sessionCount,
resetSessionsForTest,
projectIdsBoundToSession,
+ bindProjectToSession,
} from './session'
import { LocalTransport } from '../terminal/local-transport'
import { planActiveProjectDials } from '../lib/sshAttachments'
@@ -615,4 +616,19 @@ describe('openRelayTab — placing several shared projects (hosted team)', () =>
expect(projectIdsBoundToSession(tab.sessionId)).toEqual(['A', 'B'])
expect(sessionForProject('B').status).toBe('offline')
})
+
+ it('handleRelayDrop also greys a tab a share event bound to the session after mount', 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'] })
+ bindProjectToSession('C', tab.sessionId) // the host shared C while the connection was live
+
+ const setProjectUnavailable = vi.fn()
+ handleRelayDrop(tab, { setProjectUnavailable })
+ expect(setProjectUnavailable.mock.calls).toEqual([
+ ['A', true],
+ ['C', true],
+ ])
+ })
})
diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.ts
index 6d48f93bc..155e3f3ae 100644
--- a/src/renderer/session/relay-tab.ts
+++ b/src/renderer/session/relay-tab.ts
@@ -31,6 +31,7 @@ import {
disposeSession,
getSessionStores,
takeSessionOffline,
+ projectIdsBoundToSession,
type SessionSource,
} from './session'
@@ -210,8 +211,10 @@ 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)
- // 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)
+ // Every tab the connection served greys, so each one can reconnect in place: the ones placed at
+ // mount and any a share event bound to the session since (bindings survive going offline).
+ const ids = new Set([...tab.projectIds, ...projectIdsBoundToSession(tab.sessionId)])
+ for (const id of ids) deps.setProjectUnavailable(id, true)
}
export interface RelayReconnectDeps {