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(ssh): warn before reopening a project that was shared to a hosted team
review20bc420f1da2
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex d8e983f0f..55936d2b9 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -380,6 +380,7 @@ import { RemoteAccessDialog } from '../components/RemoteAccessDialog'import { ShareTeamDialog } from '../components/ShareTeamDialog'import { runShare, type ShareConfirmSummary, type ShareOutcome, type SharePhase } from '../lib/shareSshTeam'import { followSharedProject, shareProjectDeps, shareTerminals } from '../lib/shareTeamCanvas'+import { handedOffWarning } from '../lib/handedOff'import { SshProjectDialog } from '../components/SshProjectDialog'import { SshPassphrasePrompt } from '../components/SshPassphrasePrompt'import { transport } from '../terminal/local-transport'@@ -433,7 +434,7 @@ import {shouldShowExplorerPinHint,writeSeenExplorerPinHint} from '../lib/explorerPinHint'-import { setKanbanPublishHook, setStoredCanvasPublishHook, useProjects } from '../state/projects'+import { sameSshEndpoint, setKanbanPublishHook, setStoredCanvasPublishHook, useProjects } from '../state/projects'import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'import { chatPaneRefusal } from '../lib/chatPaneGate'@@ -9187,6 +9188,89 @@ export function Canvas() {[commitActiveToStore, writeDisk])+ // Reopen a previously closed project and make it active — the active-project effect reloads its+ // serialized nodes, whose TerminalNodes reattach to the surviving tmux sessions (or cold-restore).+ // The unchecked form asks nothing first: it is also "Share with team"'s own undo, which must put+ // the project back without a question. Declared here, beside switchProject and for the same TDZ+ // reason: the ⇧⌘T plan executor just below reopens through the guarded form.+ const reopenProjectUnchecked = useCallback(+ (id: string) => {+ commitActiveToStore()+ useProjects.getState().reopenProject(id)+ setWelcomeOpen(false)+ void writeDisk()+ },+ [commitActiveToStore, writeDisk]+ )++ /** Ask before opening a project this desktop handed to a hosted team: the server's core writes+ * that canvas now, and opening it here too makes a second writer that overwrites it. True = go+ * ahead, and going ahead takes the project back — the mark is cleared, so this desktop saves and+ * mirrors it again (the caller saves). A project that was never handed off answers true. */+ const confirmHandedOffReopen = useCallback(+ async (id: string): Promise<boolean> => {+ const marked = useProjects.getState().getProject(id)?.handedOffTo+ if (!marked) return true+ const hostId = marked.hostId+ // The team's name from this device's bookmark of it. Only a label, so every failure (no+ // relay on this surface, an IPC error, no bookmark for that team) falls back to null.+ let label: string | null = null+ if (hostId) {+ try {+ const list = await window.nodeTerminal.relayHosted?.bookmarks()+ label = (Array.isArray(list) ? list : []).find((b) => b.hostId === hostId)?.label ?? null+ } catch {+ label = null+ }+ }+ // Read again after the lookup: the project may have been deleted or taken back meanwhile.+ const project = useProjects.getState().getProject(id)+ if (!project) return false+ const message = handedOffWarning(project, label)+ if (!message) return true+ // One actionable dialog at a time (`confirmFlags`): replacing an open one would drop its+ // answer. Say why nothing opened rather than doing nothing.+ if (confirmBusy()) {+ setNotice({ kind: 'error', text: `Answer the open dialog first, then open ${project.name} again.` })+ return false+ }+ const ok = await new Promise<boolean>((resolve) =>+ setConfirm({+ message,+ confirmLabel: 'Open here anyway',+ danger: true,+ onConfirm: () => {+ setConfirm(null)+ resolve(true)+ },+ // The dialog's cancel path closes it after this runs.+ onCancel: () => resolve(false)+ })+ )+ if (ok) useProjects.getState().setHandedOffTo(id, undefined)+ return ok+ },+ [confirmBusy, setConfirm]+ )++ /** The reopen every human path uses (Welcome's and the sidebar's "Recently closed", ⇧⌘T, ⌘K,+ * travel, "Open recent", Set folder…). A handed-off project asks first; any other reopens at+ * once, synchronously, exactly as before the question existed. Resolves false when the user+ * declined, so a caller that staged follow-up work (a focus, a resume) can drop it. */+ const reopenProject = useCallback(+ (id: string): Promise<boolean> => {+ if (!useProjects.getState().getProject(id)?.handedOffTo) {+ reopenProjectUnchecked(id)+ return Promise.resolve(true)+ }+ return confirmHandedOffReopen(id).then((ok) => {+ if (ok) reopenProjectUnchecked(id)+ return ok+ })+ },+ [confirmHandedOffReopen, reopenProjectUnchecked]+ )+/** Executes a `ReopenPlan` already decided by `planReopen` — the side-effecting half shared by* `Cmd+Shift+T` (`reopenLastClosedCommand`) and reopening a persisted closed-session entry* from the sidebar (`reopenClosedSessionCommand`). Returns whether it did anything ('skip'@@ -9195,13 +9279,10 @@ export function Canvas() {(plan: Exclude<ReopenPlan, { action: 'skip' }>): boolean => {switch (plan.action) {case 'reopenProject':- // A project switch — commit the live canvas back to the store first, or whatever the- // user was looking at is silently lost (the same invariant every other project switch/- // add/delete in this file honors via commitActiveToStore()).- commitActiveToStore()- useProjects.getState().reopenProject(plan.projectId)- setWelcomeOpen(false)- void writeDisk()+ // The guarded reopen: it commits the live canvas back to the store first (or whatever+ // the user was looking at is silently lost) and, for a project handed to a hosted team,+ // asks before this desktop writes it again. Any other project reopens synchronously.+ void reopenProject(plan.projectId)return truecase 'insertActive':setNodes((ns) => [...ns, ...plan.nodes])@@ -9222,18 +9303,14 @@ export function Canvas() {})}void writeDisk()- if (plan.reopenProjectAfter) {- commitActiveToStore()- useProjects.getState().reopenProject(plan.projectId)- setWelcomeOpen(false)- void writeDisk()- } else {- switchProject(plan.projectId)- }+ // A closed project goes through the guarded reopen, which asks first when it was handed+ // to a hosted team. Declining leaves it closed; the restored nodes stay in its store copy.+ if (plan.reopenProjectAfter) void reopenProject(plan.projectId)+ else switchProject(plan.projectId)return true}},- [switchProject, setNodes, markDirty, writeDisk, commitActiveToStore]+ [switchProject, reopenProject, setNodes, markDirty, writeDisk])/** `app.reopenLastClosed` (Cmd+Shift+T): pops the shared close-history stack and reopens a@@ -10984,10 +11061,19 @@ export function Canvas() {.projects.find((p) => p.nodes.some((n) => n.id === nodeId))if (owner && owner.id !== useProjects.getState().activeProjectId) {pendingFocusRef.current = nodeId- switchProject(owner.id)+ if (owner.closed) {+ // A closed project is REOPENED (its tab restored), never activated behind a hidden tab,+ // and through the guarded reopen: a project handed to a hosted team asks first, and a+ // decline drops the staged focus.+ void reopenProject(owner.id).then((ok) => {+ if (!ok && pendingFocusRef.current === nodeId) pendingFocusRef.current = null+ })+ } else {+ switchProject(owner.id)+ }}},- [setNodes, goToNode, switchProject]+ [setNodes, goToNode, switchProject, reopenProject])focusNodeRef.current = focusNodeById@@ -16596,18 +16682,25 @@ export function Canvas() {// project for that server folder (its master is opened by the active-project effect on switch),// persist. openSshProject dedupes by endpoint+remoteCwd — re-adding a folder must reuse its// existing project, never mint a fresh empty one that would clobber the server's project.json.+ // That reuse is a reopen, so a folder whose project was handed to a hosted team asks first+ // (sameSshEndpoint is the store's own matcher, so this asks about the project it will reopen).const createSshProject = useCallback((input: { server: SshServer; remoteCwd: string; label: string }) => {- commitActiveToStore()- useProjects- .getState()- .openSshProject(input.label, { server: input.server, remoteCwd: input.remoteCwd })- // Same contract as onRepoCloned: the welcome screen waits behind the SSH dialog and- // dismisses only once the project is created (cancel returns to the welcome screen).- setWelcomeOpen(false)- void writeDisk()+ const ssh = { server: input.server, remoteCwd: input.remoteCwd }+ void (async () => {+ const existing = useProjects+ .getState()+ .projects.find((p) => !!p.ssh && sameSshEndpoint(p.ssh, ssh))+ if (existing?.handedOffTo && !(await confirmHandedOffReopen(existing.id))) return+ commitActiveToStore()+ useProjects.getState().openSshProject(input.label, ssh)+ // Same contract as onRepoCloned: the welcome screen waits behind the SSH dialog and+ // dismisses only once the project is created (cancel returns to the welcome screen).+ setWelcomeOpen(false)+ void writeDisk()+ })()},- [commitActiveToStore, writeDisk]+ [commitActiveToStore, writeDisk, confirmHandedOffReopen])const addProject = useCallback(() => {@@ -16630,6 +16723,9 @@ export function Canvas() {// folder to another machine's tab (openFolderProject applies the same rule).const existing = useProjects.getState().projects.find((p) => p.cwd === folder && !p.remote)if (existing) {+ // That reuse reopens the project, so one handed to a hosted team (an SSH project can carry+ // a local folder too, via "Set folder…") asks first, like every other reopen.+ if (existing.handedOffTo && !(await confirmHandedOffReopen(existing.id))) returnuseProjects.getState().openFolderProject(folder)// An `unavailable` placeholder never recovers on its own: a save emits a header-only ref// for it (never a file), so a deleted project.json stays deleted and every later load@@ -16654,7 +16750,7 @@ export function Canvas() {}void writeDisk()},- [commitActiveToStore, writeDisk]+ [commitActiveToStore, writeDisk, confirmHandedOffReopen])/** Returns true when a folder was picked (false on cancel), so callers like the welcome@@ -16718,21 +16814,6 @@ export function Canvas() {[persist])- // Reopen a previously closed project and make it active — the active-project effect reloads its- // serialized nodes, whose TerminalNodes reattach to the surviving tmux sessions (or cold-restore).- // The unchecked form asks nothing first: it is also "Share with team"'s own undo, which must put- // the project back without a question.- const reopenProjectUnchecked = useCallback(- (id: string) => {- commitActiveToStore()- useProjects.getState().reopenProject(id)- setWelcomeOpen(false)- void writeDisk()- },- [commitActiveToStore, writeDisk]- )- const reopenProject = useCallback((id: string) => reopenProjectUnchecked(id), [reopenProjectUnchecked])-const setProjectFolder = useCallback(async (id: string) => {const folder = await window.nodeTerminal.dialog.selectFolder()@@ -16750,7 +16831,7 @@ export function Canvas() {return}if (plan.kind === 'switch') {- if (plan.reopen) reopenProject(plan.projectId)+ if (plan.reopen) void reopenProject(plan.projectId)else switchProject(plan.projectId)return}@@ -17021,7 +17102,7 @@ export function Canvas() {(projectId: string) => {const { projects, activeProjectId: active } = useProjects.getState()const travel = projectTravel(projects, active, projectId)- if (travel.kind === 'reopen') reopenProject(travel.projectId)+ if (travel.kind === 'reopen') void reopenProject(travel.projectId)else if (travel.kind === 'switch') switchProject(travel.projectId)},[reopenProject, switchProject]@@ -17042,7 +17123,11 @@ export function Canvas() {if (travel.kind === 'blocked') returnif (travel.kind === 'reopen') {pendingFocusRef.current = nodeId- reopenProject(travel.projectId)+ // Declined (a project handed to a hosted team stays closed): drop the staged focus so a+ // later reopen of that project does not jump to a node nobody asked for this time.+ void reopenProject(travel.projectId).then((ok) => {+ if (!ok && pendingFocusRef.current === nodeId) pendingFocusRef.current = null+ })return}focusNodeById(nodeId)@@ -17173,8 +17258,13 @@ export function Canvas() {returncase 'resume':resumeWhenLanded(plan.projectId, conv)- if (plan.reopen) reopenProject(plan.projectId)- else switchProject(plan.projectId)+ if (plan.reopen) {+ // Declined (a project handed to a hosted team stays closed): drop the staged resume, or+ // a later "Open here anyway" from anywhere would start this conversation unasked.+ void reopenProject(plan.projectId).then((ok) => {+ if (!ok && pendingResumeRef.current?.conv === conv) pendingResumeRef.current = null+ })+ } else switchProject(plan.projectId)returncase 'open-folder':void openOrAdoptFolder(plan.folder)@@ -17777,7 +17867,9 @@ export function Canvas() {label: `Switch to ${p.name}`,hint: 'project',icon: <IconSwitch />,- run: () => switchProject(p.id)+ // A closed project is REOPENED (tab restored), never activated behind a hidden tab — and+ // the reopen is the guarded one, which asks first for a project handed to a hosted team.+ run: () => (p.closed ? void reopenProject(p.id) : switchProject(p.id))}))const cs = useAgentStatus.getState()@@ -17848,6 +17940,7 @@ export function Canvas() {fitView,persist,switchProject,+ reopenProject,goToNode,bufferCache,connectRemote,diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsxindex 13c4de155..f1f799a2b 100644--- a/src/renderer/canvas/canvas-wiring.test.tsx+++ b/src/renderer/canvas/canvas-wiring.test.tsx@@ -365,13 +365,23 @@ describe('reopen-last-closed records and dispatches through the shared history sit('commits the live canvas to the store before every reopenProject call — never a bare switch', () => {// The bug this pins: useProjects.getState().reopenProject(...) is a project SWITCH, and every// switch/add/delete elsewhere in this file calls commitActiveToStore() first so the live- // canvas isn't silently lost. Both reopen-a-project call sites inside reopenLastClosedCommand- // must do the same, rather than referencing the later `reopenProject` wrapper (a TDZ hazard- // from this callback's declaration point).+ // canvas isn't silently lost. Every store reopen lives in `reopenProjectUnchecked`, which+ // commits first; the two reopen-a-project sites of the ⇧⌘T executor reach it through the+ // guarded `reopenProject` (it asks first for a project handed to a hosted team).const calls = CANVAS_SRC.match(/useProjects\.getState\(\)\.reopenProject\(/g) ?? []const guarded = CANVAS_SRC.match(/commitActiveToStore\(\)\n\s+useProjects\.getState\(\)\.reopenProject\(/g) ?? []- expect(calls.length).toBeGreaterThanOrEqual(2)+ expect(calls.length).toBeGreaterThanOrEqual(1)expect(guarded.length).toBe(calls.length)+ const exec = CANVAS_SRC.indexOf('const executeReopenPlan = useCallback(')+ const execBody = CANVAS_SRC.slice(exec, CANVAS_SRC.indexOf('\n )\n', exec))+ expect(execBody.match(/void reopenProject\(plan\.projectId\)/g) ?? []).toHaveLength(2)+ // Both are declared ABOVE the executor: a useCallback dependency named before its declaration+ // throws (TDZ) on the first render.+ for (const decl of ['const reopenProjectUnchecked = useCallback(', 'const reopenProject = useCallback(']) {+ const at = CANVAS_SRC.indexOf(decl)+ expect(at, decl).toBeGreaterThan(-1)+ expect(at, decl).toBeLessThan(exec)+ }})it('resolves permission mode against the TARGET project being restored into, not the caller\'s active one', () => {diff --git a/src/renderer/canvas/handed-off-reopen.source.test.ts b/src/renderer/canvas/handed-off-reopen.source.test.tsnew file mode 100644index 000000000..bebef9115--- /dev/null+++ b/src/renderer/canvas/handed-off-reopen.source.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for "reopening a project handed to a hosted team warns first, on every path".+ * The copy is proven against the pure `lib/handedOff.ts`; what only a source read can pin is that+ * every path in Canvas that reopens (or activates) a CLOSED project reaches the guarded+ * `reopenProject`, and that only "Share with team"'s own undo skips the question.+ */+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++function between(start: string, end: string): string {+ const a = src.indexOf(start)+ expect(a, start).toBeGreaterThan(-1)+ const b = src.indexOf(end, a + start.length)+ expect(b, end).toBeGreaterThan(a)+ return src.slice(a, b)+}++const CALLBACK_END = '\n )\n'++describe('handed-off reopen guard in Canvas', () => {+ it('asks with the fixed copy, and only a confirm takes the project back', () => {+ const ask = between('const confirmHandedOffReopen = useCallback(', CALLBACK_END)+ expect(ask).toContain('handedOffWarning(project, label)')+ expect(ask).toContain("confirmLabel: 'Open here anyway'")+ expect(ask).toContain('danger: true')+ expect(ask).toContain('if (ok) useProjects.getState().setHandedOffTo(id, undefined)')+ // The team label is display only: its lookup fails open to null.+ expect(ask).toMatch(/try \{\n\s+const list = await window\.nodeTerminal\.relayHosted\?\.bookmarks\(\)/)+ })++ it('the unchecked reopen is reached only through the guard, or by the share flow undoing itself', () => {+ const human = between('const reopenProject = useCallback(', CALLBACK_END)+ const unchecked = src.match(/reopenProjectUnchecked\(/g) ?? []+ const inGuard = human.match(/reopenProjectUnchecked\(/g) ?? []+ expect(inGuard.length).toBeGreaterThan(0)+ expect(src).toContain('reopen: () => reopenProjectUnchecked(projectId)')+ expect(unchecked.length).toBe(inGuard.length + 1)+ })++ it('the store reopen is called in exactly one place, the unchecked reopen', () => {+ const calls = src.match(/useProjects\.getState\(\)\.reopenProject\(/g) ?? []+ expect(calls).toHaveLength(1)+ expect(between('const reopenProjectUnchecked = useCallback(', CALLBACK_END)).toContain(+ 'useProjects.getState().reopenProject(id)'+ )+ })++ it('Welcome "Recently closed" and the sidebar closed history reopen through the guard', () => {+ expect(src).toContain('onReopen={reopenProject}')+ expect(src).toContain('onReopenProject={reopenProject}')+ })++ it('re-adding the same SSH folder asks before the store reuses its handed-off project', () => {+ const create = between('const createSshProject = useCallback(', CALLBACK_END)+ expect(create).toContain('sameSshEndpoint(p.ssh, ssh)')+ const ask = create.indexOf('await confirmHandedOffReopen(existing.id)')+ expect(ask).toBeGreaterThan(-1)+ expect(create.indexOf('.openSshProject(', ask)).toBeGreaterThan(ask)+ })++ it('"Open folder…" asks before the store reuses a handed-off project carrying that folder', () => {+ const open = between('const openOrAdoptFolder = useCallback(', CALLBACK_END)+ const ask = open.indexOf('await confirmHandedOffReopen(existing.id)')+ expect(ask).toBeGreaterThan(-1)+ expect(open.indexOf('.openFolderProject(folder)', ask)).toBeGreaterThan(ask)+ })++ it('a node in a closed project is focused through the guarded reopen, never a hidden switch', () => {+ const focus = between('const focusNodeById = useCallback(', CALLBACK_END)+ expect(focus).toMatch(/if \(owner\.closed\) \{[\s\S]*?void reopenProject\(owner\.id\)/)+ })++ it('the command palette reopens a closed project instead of switching to it', () => {+ expect(src).toContain('run: () => (p.closed ? void reopenProject(p.id) : switchProject(p.id))')+ })+})diff --git a/src/renderer/canvas/share-team.source.test.ts b/src/renderer/canvas/share-team.source.test.tsindex b6b6a9336..ebaa13fbc 100644--- a/src/renderer/canvas/share-team.source.test.ts+++ b/src/renderer/canvas/share-team.source.test.ts@@ -28,7 +28,10 @@ describe('Share with team glue in Canvas', () => {it('reopens through the unchecked reopen (the share undoes its own close without a question)', () => {expect(body).toContain('reopen: () => reopenProjectUnchecked(projectId)')- expect(between('const reopenProject = useCallback(', '\n')).toContain('reopenProjectUnchecked(id)')+ // The human reopen asks first for a handed-off project, then goes through the same unchecked one.+ const human = between('const reopenProject = useCallback(', '\n )\n')+ expect(human).toContain('confirmHandedOffReopen(id)')+ expect(human).toContain('reopenProjectUnchecked(id)')})it('never undoes anything itself: the orchestrator owns every undo', () => {diff --git a/src/renderer/lib/handedOff.test.ts b/src/renderer/lib/handedOff.test.tsnew file mode 100644index 000000000..45096d874--- /dev/null+++ b/src/renderer/lib/handedOff.test.ts@@ -0,0 +1,28 @@+import { describe, it, expect } from 'vitest'+import { handedOffWarning } from './handedOff'++const P = { name: 'proj', ssh: { server: { host: 'box', user: 'alice' }, remoteCwd: '~/proj' } } as never+describe('handedOffWarning', () => {+ it('null for a project that was never handed off', () => expect(handedOffWarning(P, null)).toBeNull())+ it('names the team, the host and the unshare command', () => {+ const w = handedOffWarning({ ...(P as object), handedOffTo: { hostId: 'H', projectId: 'project-9', at: 1 } } as never, 'Box team')+ expect(w).toBe('proj is now managed by team Box team on box. Open it from the team tab, or run "team unshare project-9" on the server first.\n\nOpen it here anyway? Two copies editing one canvas can overwrite each other.')+ })+ it('an unfinished handover says so', () => {+ expect(handedOffWarning({ ...(P as object), handedOffTo: { at: 1 } } as never, null)).toMatch(/^Sharing proj with a team did not finish\./)+ })+ it('the unfinished copy is the whole sentence pair, and ignores any team label', () => {+ expect(handedOffWarning({ ...(P as object), handedOffTo: { at: 1 } } as never, 'Box team')).toBe(+ 'Sharing proj with a team did not finish. If the server already took it over, opening it here gives one canvas two editors that can overwrite each other.\n\nOpen it here anyway?'+ )+ })+ it('an unknown or blank team label falls back to the generic name', () => {+ const p = { ...(P as object), handedOffTo: { hostId: 'H', projectId: 'project-9', at: 1 } } as never+ expect(handedOffWarning(p, null)).toMatch(/^proj is now managed by team the hosted team on box\./)+ expect(handedOffWarning(p, ' ')).toMatch(/^proj is now managed by team the hosted team on box\./)+ })+ it('a finished handover with no server project id still names the command, with its placeholder', () => {+ const w = handedOffWarning({ ...(P as object), handedOffTo: { hostId: 'H', at: 1 } } as never, 'Box team')+ expect(w).toContain('run "team unshare <projectId>" on the server first.')+ })+})diff --git a/src/renderer/lib/handedOff.ts b/src/renderer/lib/handedOff.tsnew file mode 100644index 000000000..779a8b35e--- /dev/null+++ b/src/renderer/lib/handedOff.ts@@ -0,0 +1,39 @@+import type { Project } from '@shared/types'++/**+ * The question asked before this desktop opens an SSH project it handed to a hosted team.+ *+ * After "Share with team" the server's own core writes that project's canvas. Opening it here as+ * well makes this desktop a second writer of the same canvas, and the two overwrite each other —+ * so every path that would open it asks first, with this text. `null` = never handed off, nothing+ * to ask.+ *+ * A mark with no `hostId` is a handover that never finished: the server may or may not hold the+ * project, so the copy says exactly that rather than naming a team that may not exist.+ *+ * `teamLabel` is the team's name from this device's bookmark of it, when one is known; anything+ * else (no bookmark, a blank label) reads as "the hosted team". A finished mark always carries the+ * server's project id in practice; a hand-edited one without it still names the command, with the+ * same `<projectId>` placeholder the server's own usage text prints.+ */+export function handedOffWarning(+ p: Pick<Project, 'name' | 'handedOffTo' | 'ssh'>,+ teamLabel: string | null+): string | null {+ const to = p.handedOffTo+ if (!to) return null+ if (!to.hostId) {+ return (+ `Sharing ${p.name} with a team did not finish. If the server already took it over, opening it ` ++ 'here gives one canvas two editors that can overwrite each other.\n\nOpen it here anyway?'+ )+ }+ const team = teamLabel?.trim() || 'the hosted team'+ const host = p.ssh?.server.host || 'its host'+ const projectId = to.projectId ?? '<projectId>'+ return (+ `${p.name} is now managed by team ${team} on ${host}. Open it from the team tab, or run ` ++ `"team unshare ${projectId}" on the server first.\n\n` ++ 'Open it here anyway? Two copies editing one canvas can overwrite each other.'+ )+}diff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.tsindex 3c04720d0..a22b0cf60 100644--- a/src/renderer/state/projects.test.ts+++ b/src/renderer/state/projects.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach } from 'vitest'-import { useProjects } from './projects'+import { sameSshEndpoint, useProjects } from './projects'import { PROJECT_NAME_MAX } from '@shared/project-name'beforeEach(() => {@@ -222,6 +222,26 @@ describe('openSshProject', () => {})})+// The one "same server folder" rule: openSshProject's dedupe and Canvas's handed-off check before+// it must agree, or the check would look at one project and the store would reopen another.+describe('sameSshEndpoint', () => {+ const at = (server: object, remoteCwd = '~/app') => ({ server, remoteCwd }) as never+ const base = { id: 's1', label: 'niova', host: 'h', user: 'root' }++ it('ignores the server entry id and label', () => {+ expect(sameSshEndpoint(at(base), at({ ...base, id: 's2', label: 'renamed' }))).toBe(true)+ })+ it('an unset port is port 22', () => {+ expect(sameSshEndpoint(at(base), at({ ...base, port: 22 }))).toBe(true)+ expect(sameSshEndpoint(at(base), at({ ...base, port: 2222 }))).toBe(false)+ })+ it('host, user and remoteCwd must all match', () => {+ expect(sameSshEndpoint(at(base), at({ ...base, host: 'other' }))).toBe(false)+ expect(sameSshEndpoint(at(base), at({ ...base, user: 'alice' }))).toBe(false)+ expect(sameSshEndpoint(at(base), at(base, '~/web'))).toBe(false)+ })+})+describe('setProjectColor', () => {it('updates the project color', () => {const p = useProjects.getState().addProject('demo', '/tmp/demo')diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 92eea35dd..71637e819 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -476,6 +476,19 @@ function ownWrite(get: () => ProjectsState, projectId: string, write: () => voidhook(projectId, () => diffToMutations(sceneOf(before), sceneOf(after)))}+/** One server folder is one project: the same endpoint (host, user, and port — 22 when unset) and+ * the same remoteCwd. The server entry's own id and label do not count, so a re-added server entry+ * still finds its folder's project. `openSshProject` dedupes by this, and so does anything that+ * must know in advance which project that call will reopen. */+export function sameSshEndpoint(a: NonNullable<Project['ssh']>, b: NonNullable<Project['ssh']>): boolean {+ return (+ a.remoteCwd === b.remoteCwd &&+ a.server.host === b.server.host &&+ a.server.user === b.server.user &&+ (a.server.port ?? 22) === (b.server.port ?? 22)+ )+}+export const useProjects = create<ProjectsState>((set, get) => ({projects: [],activeProjectId: '',@@ -522,14 +535,7 @@ export const useProjects = create<ProjectsState>((set, get) => ({},openSshProject(label, ssh) {- const existing = get().projects.find(- (p) =>- p.ssh &&- p.ssh.remoteCwd === ssh.remoteCwd &&- p.ssh.server.host === ssh.server.host &&- p.ssh.server.user === ssh.server.user &&- (p.ssh.server.port ?? 22) === (ssh.server.port ?? 22)- )+ const existing = get().projects.find((p) => !!p.ssh && sameSshEndpoint(p.ssh, ssh))if (existing) {get().reopenProject(existing.id)return existing