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.

feat(ssh): Share with team dialog, tab menu and ⌘K entries

review78e963d3b2ee
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 896be9bf8..d8e983f0f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -377,6 +377,9 @@ import {
import { planSessionKill } from '../lib/sessionKill'
import { sessionPauseOffer, type SessionPauseOffer } from '../lib/sessionPause'
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 { SshProjectDialog } from '../components/SshProjectDialog'
import { SshPassphrasePrompt } from '../components/SshPassphrasePrompt'
import { transport } from '../terminal/local-transport'
@@ -492,6 +495,7 @@ import {
vanillaEnvStripPattern,
AGENT_CONFIG,
BUILTIN_AGENT_IDS,
+ resolvePermissionMode,
type AgentId,
type AgentPermissionMode
} from '@shared/agents/config'
@@ -1583,6 +1587,8 @@ export function Canvas() {
const [remoteDialogOpen, setRemoteDialogOpen] = useState(false)
// "Connect over SSH…" project-creation dialog (from the Welcome screen).
const [sshDialogOpen, setSshDialogOpen] = useState(false)
+ // The SSH project "Share with team" is running for (its dialog is open while set).
+ const [shareProjectId, setShareProjectId] = useState<string | null>(null)
// "Clone repository…" dialog (from the Welcome screen + command palette).
const [cloneDialogOpen, setCloneDialogOpen] = useState(false)
// Live SSH ControlMaster status per project id (drives the thin connection banner).
@@ -5376,9 +5382,10 @@ export function Canvas() {
// The share flow's join: a team this desktop just set up over ssh, whose bookmark it seeded
// pre-approved. Through the team's one attempt owner (retrying while the relay comes up, with no
- // SAS), landing on the project that was shared.
- const joinApprovedTeam = useCallback((code: string, focusProjectId?: string) => {
- hostedJoinerRef.current?.joinApproved(code, focusProjectId ? { focusProjectId } : undefined)
+ // SAS), landing on the project that was shared. `busy` = this desktop is already connected to that
+ // team (nothing mounts; the caller lands on the project itself); null = no joiner yet.
+ const joinApprovedTeam = useCallback((code: string, focusProjectId?: string): 'started' | 'busy' | null => {
+ return hostedJoinerRef.current?.joinApproved(code, focusProjectId ? { focusProjectId } : undefined) ?? null
}, [])
// Connect to a host from an already-collected pairing offer: open the relay socket, then run the
@@ -16713,7 +16720,9 @@ export function Canvas() {
// 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).
- const reopenProject = useCallback(
+ // 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)
@@ -16722,6 +16731,7 @@ export function Canvas() {
},
[commitActiveToStore, writeDisk]
)
+ const reopenProject = useCallback((id: string) => reopenProjectUnchecked(id), [reopenProjectUnchecked])
const setProjectFolder = useCallback(
async (id: string) => {
@@ -16843,6 +16853,86 @@ export function Canvas() {
[commitActiveToStore, performCloseProject, setCloseTarget]
)
+ // ---- Share with team: an SSH project handed to a hosted team on its own host ----
+ // Every step runs over the project's ControlMaster, so the share waits for the same connection
+ // status the connection banner shows.
+ const shareBlockedReason = useCallback(
+ (id: string): string | null =>
+ sshStatus[id] === 'connected' ? null : 'Connect this project first (its SSH connection is down).',
+ [sshStatus]
+ )
+
+ // A share whose join found the team already live here follows the shared project's tab (see
+ // `followSharedProject`). One follower at a time, stopped on unmount.
+ const shareFollowStopRef = useRef<(() => void) | null>(null)
+ useEffect(() => () => shareFollowStopRef.current?.(), [])
+ const followSharedTab = useCallback(
+ (projectId: string) => {
+ shareFollowStopRef.current?.()
+ shareFollowStopRef.current = followSharedProject({
+ targetId: projectId,
+ read: () => ({ activeId: useProjects.getState().activeProjectId, targetOpen: isOpenTab(projectId) }),
+ subscribe: (listener) => useProjects.subscribe(listener),
+ switchTo: (id) => switchProject(id),
+ setTimer: (fn, ms) => setTimeout(fn, ms),
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>)
+ })
+ },
+ [switchProject]
+ )
+
+ // The dialog's `start`: runs the share for one project. The orchestrator owns the order and every
+ // undo, so nothing here catches a failure or puts the project back.
+ const startShare = useCallback(
+ (projectId: string) =>
+ async (ui: { phase(p: SharePhase): void; confirm(s: ShareConfirmSummary): Promise<boolean> }): Promise<ShareOutcome> => {
+ commitActiveToStore()
+ const project = useProjects.getState().getProject(projectId)
+ if (!project?.ssh || project.remote) return { kind: 'refused', reason: 'This is not an SSH project.' }
+ const steps = shareProjectDeps({
+ commit: commitActiveToStore,
+ save: writeDisk,
+ setHandedOffTo: (value) => useProjects.getState().setHandedOffTo(projectId, value),
+ isClosed: () => useProjects.getState().getProject(projectId)?.closed === true,
+ // Never `closeProject`: it may ask whether to end the sessions, and the handover ends them
+ // itself, once the server holds the project.
+ close: () => performCloseProject(projectId),
+ reopen: () => reopenProjectUnchecked(projectId),
+ join: joinApprovedTeam,
+ followTab: followSharedTab,
+ now: () => Date.now()
+ })
+ return runShare(
+ { api: window.nodeTerminal.shareTeam, confirm: ui.confirm, phase: ui.phase, ...steps },
+ {
+ projectId,
+ projectName: project.name,
+ host: project.ssh.server.host,
+ user: project.ssh.server.user,
+ terminals: shareTerminals(project.nodes, useAgentStatus.getState().byId),
+ permissionMode: resolvePermissionMode(project, useSettings.getState().settings)
+ }
+ )
+ },
+ [commitActiveToStore, writeDisk, performCloseProject, reopenProjectUnchecked, joinApprovedTeam, followSharedTab]
+ )
+
+ // Every entry (tab menu, sidebar menu, ⌘K) opens the dialog through here, so a blocked share is
+ // refused the same way everywhere.
+ const openShareWithTeam = useCallback(
+ (projectId: string) => {
+ const blocked = shareBlockedReason(projectId)
+ if (blocked) {
+ setNotice({ kind: 'error', text: blocked })
+ return
+ }
+ // One share at a time: a second one would unmount the running dialog and leave its run
+ // going with nothing on screen.
+ setShareProjectId((current) => current ?? projectId)
+ },
+ [shareBlockedReason]
+ )
+
// Right-click on a sidebar project header: mostly the same project actions as the tab caret
// menu (plus a color swatch the tab caret menu doesn't have), in the shared ContextMenu shell.
const onProjectContextMenu = useCallback(
@@ -16883,6 +16973,20 @@ export function Canvas() {
icon: <IconGear />,
onClick: () => openProjectSettings(projectId)
},
+ ...(project.ssh && !project.remote
+ ? ((): MenuItem[] => {
+ const blocked = shareBlockedReason(projectId)
+ return [
+ {
+ label: 'Share with team…',
+ icon: <IconRemote />,
+ disabled: !!blocked,
+ ...(blocked ? { hint: blocked } : {}),
+ onClick: () => openShareWithTeam(projectId)
+ }
+ ]
+ })()
+ : []),
{ type: 'separator' },
{ type: 'colors', onPick: (color) => setProjectColor(projectId, color) },
{ type: 'separator' },
@@ -16902,7 +17006,9 @@ export function Canvas() {
setProjectFolder,
setProjectColor,
closeProject,
- openProjectSettings
+ openProjectSettings,
+ shareBlockedReason,
+ openShareWithTeam
]
)
@@ -17559,6 +17665,23 @@ export function Canvas() {
]
: []
})(),
+ // Share the active SSH project with a team. The palette has no disabled row, so a blocked
+ // share keeps its reason in `note` and running it says so (`openShareWithTeam`).
+ ...(activeProject?.ssh && !activeProject.remote
+ ? ((): Command[] => {
+ const blocked = shareBlockedReason(activeProject.id)
+ return [
+ {
+ id: 'share-with-team',
+ label: `Share ${activeProject.name} with team`,
+ hint: 'hosted team invite ssh server share',
+ icon: <IconRemote />,
+ ...(blocked ? { note: blocked } : {}),
+ run: () => openShareWithTeam(activeProject.id)
+ }
+ ]
+ })()
+ : []),
...hostedBookmarks.map(
(b): Command => ({
id: `hosted-forget-${b.hostId}`,
@@ -17740,7 +17863,9 @@ export function Canvas() {
hostedBookmarks,
copyHostedInviteCode,
forgetHostedTeam,
- confirmStopAllLiveLinks
+ confirmStopAllLiveLinks,
+ shareBlockedReason,
+ openShareWithTeam
])
// Build the palette's command list only when its inputs change — the inline `buildCommands()`
@@ -17794,6 +17919,8 @@ export function Canvas() {
onSetDefaultAccount={setProjectDefaultAccount}
onSetDefaultPermissionMode={setProjectDefaultPermissionMode}
onOpenProjectSettings={openProjectSettings}
+ onShareWithTeam={openShareWithTeam}
+ shareBlockedReason={shareBlockedReason}
/>
<div className="top-banners">
@@ -18385,6 +18512,15 @@ export function Canvas() {
{remoteDialogOpen && <RemoteAccessDialog onClose={() => setRemoteDialogOpen(false)} />}
+ {shareProjectId && (
+ <ShareTeamDialog
+ projectId={shareProjectId}
+ projectName={useProjects.getState().getProject(shareProjectId)?.name ?? 'project'}
+ start={startShare(shareProjectId)}
+ onClose={() => setShareProjectId(null)}
+ />
+ )}
+
{sshDialogOpen && (
<SshProjectDialog
onCreate={createSshProject}
diff --git a/src/renderer/canvas/share-team.source.test.ts b/src/renderer/canvas/share-team.source.test.ts
new file mode 100644
index 000000000..b6b6a9336
--- /dev/null
+++ b/src/renderer/canvas/share-team.source.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the "Share with team" glue in Canvas.tsx, the same class of test as
+ * `hosted-team.source.test.ts`: the behaviour is proven against the real modules
+ * (`lib/shareSshTeam.test.ts` for the order and every undo, `lib/shareTeamCanvas.test.ts` for the
+ * store steps and the tab follow, `components/ShareTeamDialog.test.tsx` for the dialog). What only a
+ * source read can pin is which Canvas actions those steps are bound to.
+ */
+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)
+}
+
+describe('Share with team glue in Canvas', () => {
+ const body = between('const startShare = useCallback(', '\n )\n')
+
+ it('closes through the non-destructive close, never the confirm-raising wrapper', () => {
+ expect(body).toContain('close: () => performCloseProject(projectId)')
+ expect(body).not.toMatch(/\bcloseProject\(/)
+ })
+
+ 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)')
+ })
+
+ it('never undoes anything itself: the orchestrator owns every undo', () => {
+ expect(body).not.toMatch(/\bcatch\b/)
+ expect(body).toContain('return runShare(')
+ })
+
+ it('a busy join follows the shared tab; the joiner answer is returned, not dropped', () => {
+ expect(body).toContain('join: joinApprovedTeam')
+ expect(body).toContain('followTab: followSharedTab')
+ const join = between('const joinApprovedTeam = useCallback(', '}, [])')
+ expect(join).toContain('return hostedJoinerRef.current?.joinApproved(')
+ })
+
+ it('every entry opens through one gate', () => {
+ expect(src).toContain('onShareWithTeam={openShareWithTeam}')
+ expect(src).toContain('shareBlockedReason={shareBlockedReason}')
+ expect(src).toContain("onClick: () => openShareWithTeam(projectId)")
+ expect(src).toContain('run: () => openShareWithTeam(activeProject.id)')
+ })
+})
diff --git a/src/renderer/components/ShareTeamDialog.test.tsx b/src/renderer/components/ShareTeamDialog.test.tsx
new file mode 100644
index 000000000..b4db93ce7
--- /dev/null
+++ b/src/renderer/components/ShareTeamDialog.test.tsx
@@ -0,0 +1,415 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ShareTeamDialog, ShareTeamDialogBody, type ShareDialogState } from './ShareTeamDialog'
+import { resetDialogStack } from './dialog-stack'
+import type { ShareConfirmSummary, ShareOutcome, SharePhase } from '../lib/shareSshTeam'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const noop = (): void => {}
+const body = (state: ShareDialogState, extra: Partial<Parameters<typeof ShareTeamDialogBody>[0]> = {}) =>
+ renderToStaticMarkup(
+ <ShareTeamDialogBody
+ projectName="proj"
+ state={state}
+ onConfirm={noop}
+ onCancel={noop}
+ onClose={noop}
+ onCopy={noop}
+ onCancelInstall={noop}
+ {...extra}
+ />
+ )
+const SECURITY = 'Editors get a shell as alice on box and can make themselves owners; Viewers cannot.'
+const SUMMARY: ShareConfirmSummary = {
+ host: 'box',
+ user: 'alice',
+ install: 'missing',
+ restartsService: false,
+ resumable: [{ nodeId: 'a', title: 'Claude' }],
+ manual: [{ node: { nodeId: 'x', title: 'Work' }, reason: 'runs under a managed account' }],
+ stopping: [{ node: { nodeId: 'p', title: 'dev server' }, command: 'npm' }],
+ security: SECURITY
+}
+const SHARED: Extract<ShareOutcome, { kind: 'shared' }> = {
+ kind: 'shared',
+ joinCode: 'ntj1.CODE',
+ teamLabel: 'Box team',
+ projectName: 'proj',
+ hosting: 'up',
+ resumed: [{ nodeId: 'a', title: 'Claude' }],
+ notResumed: [{ node: { nodeId: 'x', title: 'Work' }, reason: 'runs under a managed account' }],
+ stillOnSsh: [{ nodeId: 'q', title: 'logs' }]
+}
+const RESTORED_SENTENCE = 'The SSH project was reopened; nothing was changed.'
+const RESTORE_FAILED_SENTENCE = 'The SSH project could not be restored automatically. Reopen it from Recently closed.'
+
+describe('ShareTeamDialogBody', () => {
+ it('confirm shows host, install, the security sentence and all three lists', () => {
+ const html = body({ phase: 'confirm', summary: SUMMARY })
+ for (const s of [
+ 'Share proj with a team',
+ 'alice@box',
+ 'about 600 MB',
+ 'Editors get a shell as alice on box',
+ 'These agents continue on the server:',
+ 'Claude',
+ 'These terminals are running something that will stop:',
+ 'dev server',
+ 'npm',
+ 'These agents will not be resumed — resume them by hand:',
+ 'Work',
+ 'runs under a managed account',
+ '>Share<',
+ '>Cancel<'
+ ]) {
+ expect(html).toContain(s)
+ }
+ })
+
+ it('confirm words each install reason exactly, and the restart only when one happens', () => {
+ expect(body({ phase: 'confirm', summary: SUMMARY })).toContain(
+ 'nodeterm-server will be installed on the host: about 600 MB, built from source, as a systemd --user service that updates itself daily.'
+ )
+ expect(body({ phase: 'confirm', summary: { ...SUMMARY, install: 'outdated' } })).toContain(
+ 'nodeterm-server on the host is too old for this and will be updated (the same installer).'
+ )
+ expect(body({ phase: 'confirm', summary: { ...SUMMARY, install: 'not-running' } })).toContain(
+ 'nodeterm-server on the host is not answering and will be reinstalled and restarted.'
+ )
+ const restart = 'Updating restarts the server; teammates connected to it are briefly disconnected.'
+ expect(body({ phase: 'confirm', summary: SUMMARY })).not.toContain(restart)
+ expect(body({ phase: 'confirm', summary: { ...SUMMARY, install: 'outdated', restartsService: true } })).toContain(restart)
+ // A ready server: no install line at all.
+ expect(body({ phase: 'confirm', summary: { ...SUMMARY, install: null } })).not.toContain('nodeterm-server')
+ })
+
+ it('confirm leaves out an empty list', () => {
+ const html = body({ phase: 'confirm', summary: { ...SUMMARY, manual: [], stopping: [] } })
+ expect(html).toContain('These agents continue on the server:')
+ expect(html).not.toContain('These terminals are running something that will stop:')
+ expect(html).not.toContain('These agents will not be resumed')
+ })
+
+ it('running shows the step line and, while installing, the log and a Cancel', () => {
+ const html = body({ phase: 'running', step: 'installing', log: 'cloning…' })
+ expect(html).toContain('Installing nodeterm-server on the host.')
+ expect(html).toContain('cloning…')
+ expect(html).toContain('Cancel')
+ expect(body({ phase: 'running', step: 'bootstrapping', log: '' })).not.toContain('Cancel')
+ expect(body({ phase: 'running', step: 'bootstrapping', log: 'cloning…' })).not.toContain('cloning…')
+ })
+
+ it('words every step exactly', () => {
+ const lines: Record<SharePhase, string> = {
+ probing: 'Checking the host…',
+ installing: 'Installing nodeterm-server on the host. This can take several minutes…',
+ 'checking-install': 'Checking the install…',
+ releasing: 'Saving the canvas to the host…',
+ bootstrapping: 'Setting up the team…',
+ 'handing-over': 'Moving the terminals to the server…',
+ joining: 'Joining the team…'
+ }
+ for (const [step, line] of Object.entries(lines)) {
+ expect(body({ phase: 'running', step: step as SharePhase, log: '' })).toContain(line)
+ }
+ })
+
+ it('the install log shows only its last 4000 characters', () => {
+ const html = body({ phase: 'running', step: 'installing', log: 'HEAD' + 'x'.repeat(4000) })
+ expect(html).not.toContain('HEAD')
+ expect(html).toContain('x'.repeat(4000))
+ expect(html).toContain('role="log"')
+ })
+
+ it('shared shows the code with Copy, the security note, and the result lists', () => {
+ const html = body({ phase: 'done', outcome: SHARED, security: SECURITY })
+ for (const s of [
+ 'Shared with Box team',
+ 'Invite code',
+ 'ntj1.CODE',
+ '>Copy<',
+ 'Give this code to teammates. An owner approves each new device.',
+ SECURITY,
+ 'This computer is joining the team; its tab opens when it connects.',
+ 'Resumed on the server:',
+ 'Claude',
+ 'Not resumed:',
+ 'Work — runs under a managed account',
+ 'Still running on SSH (not moved):',
+ 'logs',
+ '>Close<'
+ ]) {
+ expect(html).toContain(s)
+ }
+ expect(html).not.toContain('Hosting is starting')
+ expect(body({ phase: 'done', outcome: SHARED, copied: true })).toContain('>Copied<')
+ })
+
+ it('shared says hosting is still starting only when it is', () => {
+ expect(body({ phase: 'done', outcome: { ...SHARED, hosting: 'starting' } })).toContain(
+ 'Hosting is starting — the code works in a moment.'
+ )
+ })
+
+ it('shared leaves out an empty result list', () => {
+ const html = body({ phase: 'done', outcome: { ...SHARED, notResumed: [], stillOnSsh: [] } })
+ expect(html).toContain('Resumed on the server:')
+ expect(html).not.toContain('Not resumed:')
+ expect(html).not.toContain('Still running on SSH')
+ })
+
+ it('refused shows the reason and the busy agents', () => {
+ const html = body({
+ phase: 'done',
+ outcome: {
+ kind: 'refused',
+ reason: 'Wait for these agents to finish (or stop them), then share again.',
+ busy: [{ nodeId: 'a', title: 'Busy Claude' }]
+ }
+ })
+ expect(html).toContain('Wait for these agents to finish (or stop them), then share again.')
+ expect(html).toContain('Busy Claude')
+ expect(html).toContain('>Close<')
+ })
+
+ it('failed says whether the SSH project was reopened', () => {
+ const failed = { kind: 'failed', step: 'bootstrapping', error: 'boom' } as const
+ const reopened = body({ phase: 'done', outcome: { ...failed, reopened: true } })
+ expect(reopened).toContain('Could not share: boom')
+ expect(reopened).toContain(RESTORED_SENTENCE)
+ expect(reopened).toContain('>Close<')
+ expect(body({ phase: 'done', outcome: { ...failed, reopened: false } })).not.toContain(RESTORED_SENTENCE)
+ })
+
+ it('failed never claims nothing changed when the undo itself failed', () => {
+ for (const reopened of [false, true]) {
+ const html = body({ phase: 'done', outcome: { kind: 'failed', step: 'bootstrapping', error: 'boom', reopened, restoreFailed: true } })
+ expect(html).toContain('Could not share: boom')
+ expect(html).toContain(RESTORE_FAILED_SENTENCE)
+ expect(html).not.toContain(RESTORED_SENTENCE)
+ }
+ expect(body({ phase: 'done', outcome: { kind: 'failed', step: 'probing', error: 'x', reopened: false } })).not.toContain(
+ RESTORE_FAILED_SENTENCE
+ )
+ })
+
+ it('failed shows the install log it carries', () => {
+ const html = body({ phase: 'done', outcome: { kind: 'failed', step: 'checking-install', error: 'x', reopened: false, log: 'npm ERR! boom' } })
+ expect(html).toContain('npm ERR! boom')
+ expect(html).toContain('role="log"')
+ })
+})
+
+// ---- the mounted dialog ----------------------------------------------------------------------
+
+type Ui = Parameters<Parameters<typeof ShareTeamDialog>[0]['start']>[0]
+
+let api: {
+ onInstallOutput: ReturnType<typeof vi.fn<(projectId: string, listener: (text: string) => void) => () => void>>
+ cancelInstall: ReturnType<typeof vi.fn<(projectId: string) => Promise<void>>>
+}
+let output: ((text: string) => void) | null
+let unsubscribed: number
+let writeText: ReturnType<typeof vi.fn<(text: string) => void>>
+let host: HTMLDivElement
+let root: Root
+
+beforeEach(() => {
+ resetDialogStack()
+ output = null
+ unsubscribed = 0
+ api = {
+ onInstallOutput: vi.fn((_id: string, listener: (text: string) => void) => {
+ output = listener
+ return () => {
+ unsubscribed++
+ output = null
+ }
+ }),
+ cancelInstall: vi.fn(async () => {})
+ }
+ writeText = vi.fn()
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ shareTeam: api,
+ clipboard: { writeText }
+ }
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ document.body.innerHTML = ''
+ resetDialogStack()
+})
+
+const flush = (): Promise<void> => act(async () => {})
+const btn = (label: string): HTMLButtonElement | undefined =>
+ [...document.querySelectorAll<HTMLButtonElement>('.share-team button')].find((b) => b.textContent === label)
+const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+const escape = (): void => act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))
+const text = (): string => document.querySelector('.share-team')?.textContent ?? ''
+
+function mount(start: (ui: Ui) => Promise<ShareOutcome>): { onClose: ReturnType<typeof vi.fn>; start: ReturnType<typeof vi.fn> } {
+ const onClose = vi.fn()
+ const startFn = vi.fn(start)
+ act(() => root.render(<ShareTeamDialog projectId="p1" projectName="proj" start={startFn} onClose={onClose} />))
+ return { onClose, start: startFn }
+}
+
+describe('ShareTeamDialog', () => {
+ it('the wrapper drives start(): confirm resolves from the Share button, the outcome renders', async () => {
+ let finish!: (o: ShareOutcome) => void
+ let agreed: boolean | undefined
+ const { onClose, start } = mount(async (ui) => {
+ ui.phase('probing')
+ agreed = await ui.confirm(SUMMARY)
+ ui.phase('bootstrapping')
+ return new Promise<ShareOutcome>((r) => (finish = r))
+ })
+ await flush()
+ expect(start).toHaveBeenCalledTimes(1)
+ expect(text()).toContain('Share proj with a team')
+ click(btn('Share')!)
+ await flush()
+ expect(agreed).toBe(true)
+ expect(text()).toContain('Setting up the team…')
+ await act(async () => finish(SHARED))
+ expect(text()).toContain('Shared with Box team')
+ // The confirm's security sentence is carried into the result.
+ expect(text()).toContain(SECURITY)
+ expect(onClose).not.toHaveBeenCalled()
+ click(btn('Close')!)
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('Cancel at the confirm cancels the run and closes the dialog', async () => {
+ let agreed: boolean | undefined
+ const { onClose } = mount(async (ui) => {
+ agreed = await ui.confirm(SUMMARY)
+ return agreed ? SHARED : { kind: 'cancelled' }
+ })
+ await flush()
+ click(btn('Cancel')!)
+ await flush()
+ expect(agreed).toBe(false)
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('shows the step while probing, before anything is asked', async () => {
+ mount(async (ui) => {
+ ui.phase('probing')
+ return new Promise<ShareOutcome>(() => {})
+ })
+ await flush()
+ expect(text()).toContain('Checking the host…')
+ })
+
+ it('Escape cancels at the confirm, is ignored while running, and closes once done', async () => {
+ let finish!: (o: ShareOutcome) => void
+ let agreed: boolean | undefined
+ const run = mount(async (ui) => {
+ agreed = await ui.confirm(SUMMARY)
+ return agreed ? SHARED : { kind: 'cancelled' }
+ })
+ await flush()
+ escape()
+ await flush()
+ expect(agreed).toBe(false)
+ expect(run.onClose).toHaveBeenCalledTimes(1)
+
+ act(() => root.unmount())
+ root = createRoot(host)
+ const second = mount(async (ui) => {
+ ui.phase('bootstrapping')
+ return new Promise<ShareOutcome>((r) => (finish = r))
+ })
+ await flush()
+ escape()
+ click(document.querySelector('.confirm-overlay')!)
+ expect(second.onClose).not.toHaveBeenCalled()
+ await act(async () => finish({ kind: 'failed', step: 'bootstrapping', error: 'boom', reopened: true }))
+ expect(text()).toContain('Could not share: boom')
+ escape()
+ expect(second.onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('streams the install output into the log, and Cancel stops the install', async () => {
+ mount(async (ui) => {
+ ui.phase('installing')
+ return new Promise<ShareOutcome>(() => {})
+ })
+ await flush()
+ expect(api.onInstallOutput).toHaveBeenCalledWith('p1', expect.any(Function))
+ act(() => output!('cloning…\n'))
+ act(() => output!('building…\n'))
+ expect(document.querySelector('[role="log"]')!.textContent).toBe('cloning…\nbuilding…\n')
+ click(btn('Cancel')!)
+ expect(api.cancelInstall).toHaveBeenCalledWith('p1')
+ })
+
+ it('keeps the log across a step change and unsubscribes on close', async () => {
+ let ui!: Ui
+ mount(async (u) => {
+ ui = u
+ u.phase('installing')
+ return new Promise<ShareOutcome>(() => {})
+ })
+ await flush()
+ act(() => output!('built\n'))
+ act(() => ui.phase('checking-install'))
+ act(() => ui.phase('installing'))
+ expect(document.querySelector('[role="log"]')!.textContent).toBe('built\n')
+ act(() => root.unmount())
+ expect(unsubscribed).toBe(1)
+ root = createRoot(host)
+ })
+
+ it('a failed install shows the output it streamed', async () => {
+ let finish!: (o: ShareOutcome) => void
+ mount(async (ui) => {
+ ui.phase('installing')
+ return new Promise<ShareOutcome>((r) => (finish = r))
+ })
+ await flush()
+ act(() => output!('npm ERR! gyp\n'))
+ await act(async () => finish({ kind: 'failed', step: 'checking-install', error: 'not ready', reopened: false }))
+ expect(text()).toContain('Could not share: not ready')
+ expect(document.querySelector('[role="log"]')!.textContent).toBe('npm ERR! gyp\n')
+ })
+
+ it('Copy puts the invite code on the clipboard and says so', async () => {
+ mount(async () => SHARED)
+ await flush()
+ click(btn('Copy')!)
+ expect(writeText).toHaveBeenCalledWith('ntj1.CODE')
+ expect(btn('Copied')).toBeDefined()
+ })
+
+ it('a start that rejects shows the failure (the project is not touched here)', async () => {
+ mount(async (ui) => {
+ ui.phase('probing')
+ throw new Error('bridge gone')
+ })
+ await flush()
+ expect(text()).toContain('Could not share: bridge gone')
+ expect(text()).not.toContain(RESTORED_SENTENCE)
+ })
+
+ it('a pending confirm answers no when the dialog goes away', async () => {
+ let agreed: boolean | undefined
+ mount(async (ui) => {
+ agreed = await ui.confirm(SUMMARY)
+ return { kind: 'cancelled' }
+ })
+ await flush()
+ act(() => root.unmount())
+ await flush()
+ expect(agreed).toBe(false)
+ root = createRoot(host)
+ })
+})
diff --git a/src/renderer/components/ShareTeamDialog.tsx b/src/renderer/components/ShareTeamDialog.tsx
new file mode 100644
index 000000000..338f844aa
--- /dev/null
+++ b/src/renderer/components/ShareTeamDialog.tsx
@@ -0,0 +1,347 @@
+// "Share with team" for an SSH project: the dialog around `runShare` (lib/shareSshTeam). The
+// orchestrator owns the order and every undo; this component only shows where it is, asks the one
+// question (the confirm), streams the installer's output, and shows the result.
+//
+// It cannot be dismissed while a step runs: the steps change the host and the project, and a closed
+// dialog would hide a failure (or an invite code) the user has to see. The confirm and the result
+// close on Escape or the scrim; at the confirm that is a Cancel, which changes nothing.
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
+import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
+import type { ShareConfirmSummary, ShareNode, ShareOutcome, SharePhase } from '../lib/shareSshTeam'
+
+export type ShareDialogState =
+ | { phase: 'running'; step: SharePhase; log: string }
+ | { phase: 'confirm'; summary: ShareConfirmSummary }
+ | {
+ phase: 'done'
+ outcome: Exclude<ShareOutcome, { kind: 'cancelled' }>
+ copied?: boolean
+ /** The confirm's security sentence, repeated beside the invite code: whoever hands the code
+ * out decides who gets a shell, so it is said again where that decision is made. */
+ security?: string
+ }
+
+export const SHARE_STEP_TEXT: Readonly<Record<SharePhase, string>> = Object.freeze({
+ probing: 'Checking the host…',
+ installing: 'Installing nodeterm-server on the host. This can take several minutes…',
+ 'checking-install': 'Checking the install…',
+ releasing: 'Saving the canvas to the host…',
+ bootstrapping: 'Setting up the team…',
+ 'handing-over': 'Moving the terminals to the server…',
+ joining: 'Joining the team…'
+})
+
+const INSTALL_TEXT: Readonly<Record<NonNullable<ShareConfirmSummary['install']>, string>> = Object.freeze({
+ missing:
+ 'nodeterm-server will be installed on the host: about 600 MB, built from source, as a systemd --user service that updates itself daily.',
+ outdated: 'nodeterm-server on the host is too old for this and will be updated (the same installer).',
+ 'not-running': 'nodeterm-server on the host is not answering and will be reinstalled and restarted.'
+})
+const RESTART_TEXT = 'Updating restarts the server; teammates connected to it are briefly disconnected.'
+const RESTORED_TEXT = 'The SSH project was reopened; nothing was changed.'
+const RESTORE_FAILED_TEXT = 'The SSH project could not be restored automatically. Reopen it from Recently closed.'
+
+/** The installer's output is shown (and kept) only this far back: a build prints far more than
+ * anyone reads, and the tail is where a failure is. */
+export const SHARE_LOG_TAIL = 4000
+
+const errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))
+
+function TitleList({ heading, items }: { heading?: string; items: string[] }): React.JSX.Element | null {
+ if (!items.length) return null
+ return (
+ <>
+ {heading && <p className="share-team__heading">{heading}</p>}
+ <ul className="share-team__list">
+ {items.map((t, i) => (
+ <li key={i}>{t}</li>
+ ))}
+ </ul>
+ </>
+ )
+}
+
+const titles = (nodes: ShareNode[]): string[] => nodes.map((n) => n.title)
+const withReasons = (rows: Array<{ node: ShareNode; reason: string }>): string[] =>
+ rows.map((r) => `${r.node.title} — ${r.reason}`)
+
+const Log = ({ text }: { text: string }): React.JSX.Element => (
+ <pre role="log" className="share-team__log">
+ {text.slice(-SHARE_LOG_TAIL)}
+ </pre>
+)
+
+export function ShareTeamDialogBody(p: {
+ projectName: string
+ state: ShareDialogState
+ onConfirm(): void
+ onCancel(): void
+ onClose(): void
+ onCopy(): void
+ onCancelInstall(): void
+}): React.JSX.Element {
+ const s = p.state
+ let title = `Share ${p.projectName} with a team`
+ let content: ReactNode
+ let actions: ReactNode = (
+ <button className="confirm__btn" data-autofocus="" onClick={p.onClose}>
+ Close
+ </button>
+ )
+
+ if (s.phase === 'running') {
+ content = (
+ <>
+ <p>{SHARE_STEP_TEXT[s.step]}</p>
+ {s.step === 'installing' && <Log text={s.log} />}
+ </>
+ )
+ // Only the install can be stopped: every later step is short, and stopping one half-way would
+ // leave the very state the orchestrator's own undo exists to avoid.
+ actions =
+ s.step === 'installing' ? (
+ <button className="confirm__btn" data-autofocus="" onClick={p.onCancelInstall}>
+ Cancel
+ </button>
+ ) : null
+ } else if (s.phase === 'confirm') {
+ const m = s.summary
+ content = (
+ <>
+ <p>{`Host: ${m.user}@${m.host}`}</p>
+ {m.install && <p>{INSTALL_TEXT[m.install]}</p>}
+ {m.restartsService && <p>{RESTART_TEXT}</p>}
+ <p className="share-team__warning">{m.security}</p>
+ <TitleList heading="These agents continue on the server:" items={titles(m.resumable)} />
+ <TitleList
+ heading="These terminals are running something that will stop:"
+ items={m.stopping.map((x) => `${x.node.title} — ${x.command}`)}
+ />
+ <TitleList heading="These agents will not be resumed — resume them by hand:" items={withReasons(m.manual)} />
+ </>
+ )
+ // Focus lands on Cancel: an Enter pressed out of habit must never start an install on a host.
+ actions = (
+ <>
+ <button className="confirm__btn" data-autofocus="" onClick={p.onCancel}>
+ Cancel
+ </button>
+ <button className="confirm__btn primary" onClick={p.onConfirm}>
+ Share
+ </button>
+ </>
+ )
+ } else {
+ const o = s.outcome
+ if (o.kind === 'shared') {
+ title = `Shared with ${o.teamLabel}`
+ content = (
+ <>
+ <p className="share-team__heading">Invite code</p>
+ <div className="share-team__code">
+ <input
+ className="confirm__input"
+ readOnly
+ aria-label="Invite code"
+ value={o.joinCode}
+ onFocus={(e) => e.currentTarget.select()}
+ />
+ <button className="confirm__btn primary" data-autofocus="" onClick={p.onCopy}>
+ {s.copied ? 'Copied' : 'Copy'}
+ </button>
+ </div>
+ <p>Give this code to teammates. An owner approves each new device.</p>
+ {s.security && <p className="share-team__warning">{s.security}</p>}
+ {o.hosting === 'starting' && <p>Hosting is starting — the code works in a moment.</p>}
+ <p>This computer is joining the team; its tab opens when it connects.</p>
+ <TitleList heading="Resumed on the server:" items={titles(o.resumed)} />
+ <TitleList heading="Not resumed:" items={withReasons(o.notResumed)} />
+ <TitleList heading="Still running on SSH (not moved):" items={titles(o.stillOnSsh)} />
+ </>
+ )
+ actions = (
+ <button className="confirm__btn" onClick={p.onClose}>
+ Close
+ </button>
+ )
+ } else if (o.kind === 'refused') {
+ content = (
+ <>
+ <p>{o.reason}</p>
+ <TitleList items={titles(o.busy ?? [])} />
+ </>
+ )
+ } else {
+ content = (
+ <>
+ <p className="share-team__error" role="alert">{`Could not share: ${o.error}`}</p>
+ {/* "Nothing was changed" only when the undo is known to have worked. */}
+ {o.restoreFailed ? <p>{RESTORE_FAILED_TEXT}</p> : o.reopened && <p>{RESTORED_TEXT}</p>}
+ {o.log && <Log text={o.log} />}
+ </>
+ )
+ }
+ }
+
+ return (
+ <div className="confirm share-team" tabIndex={-1} onClick={(e) => e.stopPropagation()}>
+ <p className="share-team__title">{title}</p>
+ <div className="share-team__body">{content}</div>
+ {actions && <div className="confirm__actions">{actions}</div>}
+ </div>
+ )
+}
+
+export function ShareTeamDialog({
+ projectId,
+ projectName,
+ start,
+ onClose
+}: {
+ projectId: string
+ projectName: string
+ /** Runs the share (once, on mount) and reports its steps and its one question through `ui`. */
+ start(ui: { phase(p: SharePhase): void; confirm(s: ShareConfirmSummary): Promise<boolean> }): Promise<ShareOutcome>
+ onClose(): void
+}): React.JSX.Element | null {
+ const [state, setState] = useState<ShareDialogState>({ phase: 'running', step: 'probing', log: '' })
+ // The latest state for the key and click handlers (a closure would see the render that made it).
+ const stateRef = useRef(state)
+ stateRef.current = state
+ const isTop = useDialogStack()
+ // The caller passes a fresh `start` on every render; the share runs once, with the first.
+ const startRef = useRef(start)
+ const onCloseRef = useRef(onClose)
+ onCloseRef.current = onClose
+ const logRef = useRef('')
+ const stepRef = useRef<SharePhase>('probing')
+ const securityRef = useRef<string | undefined>(undefined)
+ const answerRef = useRef<((ok: boolean) => void) | null>(null)
+ const liveRef = useRef(true)
+
+ const answer = useCallback((ok: boolean) => {
+ const resolve = answerRef.current
+ answerRef.current = null
+ resolve?.(ok)
+ }, [])
+
+ useEffect(() => {
+ liveRef.current = true
+ const ui = {
+ phase(p: SharePhase): void {
+ stepRef.current = p
+ if (liveRef.current) setState({ phase: 'running', step: p, log: logRef.current })
+ },
+ confirm(summary: ShareConfirmSummary): Promise<boolean> {
+ return new Promise<boolean>((resolve) => {
+ answerRef.current?.(false)
+ if (!liveRef.current) return resolve(false)
+ securityRef.current = summary.security
+ answerRef.current = resolve
+ setState({ phase: 'confirm', summary })
+ })
+ }
+ }
+ let run: Promise<ShareOutcome>
+ try {
+ run = Promise.resolve(startRef.current(ui))
+ } catch (e) {
+ run = Promise.reject(e)
+ }
+ run.then(
+ (outcome) => {
+ if (!liveRef.current) return
+ if (outcome.kind === 'cancelled') {
+ onCloseRef.current()
+ return
+ }
+ // An install that failed keeps the output it streamed: the tail is usually the reason.
+ const keepLog =
+ outcome.kind === 'failed' &&
+ !outcome.log &&
+ logRef.current &&
+ (outcome.step === 'installing' || outcome.step === 'checking-install')
+ setState({
+ phase: 'done',
+ outcome: keepLog ? { ...outcome, log: logRef.current } : outcome,
+ ...(securityRef.current ? { security: securityRef.current } : {})
+ })
+ },
+ // The orchestrator answers instead of rejecting and owns every undo, so a rejection is shown
+ // as it is: nothing here may try to put the project back.
+ (e) => {
+ if (!liveRef.current) return
+ setState({ phase: 'done', outcome: { kind: 'failed', step: stepRef.current, error: errorText(e), reopened: false } })
+ }
+ )
+ return () => {
+ liveRef.current = false
+ // A question nobody can answer any more is a no: the run ends as cancelled.
+ answer(false)
+ }
+ }, [answer])
+
+ useEffect(
+ () =>
+ window.nodeTerminal.shareTeam.onInstallOutput(projectId, (text) => {
+ logRef.current = (logRef.current + text).slice(-SHARE_LOG_TAIL)
+ setState((s) => (s.phase === 'running' ? { ...s, log: logRef.current } : s))
+ }),
+ [projectId]
+ )
+
+ // Focus lands in the dialog, so keys stay inside it instead of reaching the canvas behind.
+ const panelRef = useRef<HTMLDivElement>(null)
+ const focusKey = state.phase === 'running' ? `running:${state.step}` : state.phase
+ useEffect(() => {
+ const panel = panelRef.current
+ const target = panel?.querySelector<HTMLElement>('[data-autofocus]') ?? panel?.querySelector<HTMLElement>('.share-team')
+ target?.focus({ preventScroll: true })
+ }, [focusKey])
+
+ const dismiss = useCallback(() => {
+ const s = stateRef.current
+ if (s.phase === 'confirm') answer(false)
+ else if (s.phase === 'done') onCloseRef.current()
+ }, [answer])
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape' && isTop()) dismiss()
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [isTop, dismiss])
+
+ const copy = (): void => {
+ const s = stateRef.current
+ if (s.phase !== 'done' || s.outcome.kind !== 'shared') return
+ window.nodeTerminal.clipboard.writeText(s.outcome.joinCode)
+ setState({ ...s, copied: true })
+ }
+
+ // The orchestrator's install then answers with a non-zero exit, and that failure is what renders.
+ const cancelInstall = (): void => {
+ try {
+ window.nodeTerminal.shareTeam.cancelInstall(projectId).catch(() => {})
+ } catch {
+ // No bridge to ask: the install runs to its end, and its result renders as usual.
+ }
+ }
+
+ return createPortal(
+ <div className="confirm-overlay" ref={panelRef} onClick={dismiss}>
+ <ShareTeamDialogBody
+ projectName={projectName}
+ state={state}
+ onConfirm={() => answer(true)}
+ onCancel={() => answer(false)}
+ onClose={dismiss}
+ onCopy={copy}
+ onCancelInstall={cancelInstall}
+ />
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/TabBar.test.tsx b/src/renderer/components/TabBar.test.tsx
index ebfb83b34..944f26d95 100644
--- a/src/renderer/components/TabBar.test.tsx
+++ b/src/renderer/components/TabBar.test.tsx
@@ -337,3 +337,88 @@ describe('TabBar options button', () => {
})
})
+
+describe('TabBar Share with team', () => {
+ let root: Root
+ let host: HTMLElement
+ let onShareWithTeam: ReturnType<typeof vi.fn<(id: string) => void>>
+
+ const SSH = { server: { host: 'box', user: 'alice' }, remoteCwd: '~/proj' }
+ const shareRow = (): HTMLButtonElement | undefined =>
+ Array.from(document.querySelectorAll<HTMLButtonElement>('.tab-menu button')).find(
+ (b) => b.textContent?.trim() === 'Share with team…'
+ )
+
+ async function open(
+ over: Partial<Project>,
+ props: { share?: boolean; blocked?: (id: string) => string | null } = {}
+ ): Promise<void> {
+ const { TabBar, useProjects } = await load()
+ useProjects.setState({ projects: [project(over)], activeProjectId: 'p1' })
+ await act(async () => {
+ root.render(
+ <TabBar
+ onSwitch={vi.fn()}
+ onReconnect={vi.fn()}
+ onReorder={vi.fn()}
+ onOpenWelcome={vi.fn()}
+ onRename={vi.fn()}
+ onSetFolder={vi.fn()}
+ onCloseProject={vi.fn()}
+ onRemoteAccess={vi.fn()}
+ onSetDefaultAccount={vi.fn()}
+ onSetDefaultPermissionMode={vi.fn()}
+ onOpenProjectSettings={vi.fn()}
+ {...(props.share === false ? {} : { onShareWithTeam })}
+ shareBlockedReason={props.blocked}
+ />
+ )
+ })
+ await click(host.querySelector<HTMLButtonElement>('.tab__caret')!)
+ }
+
+ beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ onShareWithTeam = vi.fn<(id: string) => void>()
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ })
+
+ it('shows for an SSH project, and opens the share for it', async () => {
+ await open({ ssh: SSH })
+ const row = shareRow()
+ expect(row).toBeDefined()
+ expect(row!.disabled).toBe(false)
+ await click(row!)
+ expect(onShareWithTeam).toHaveBeenCalledWith('p1')
+ expect(document.querySelector('.tab-menu')).toBeNull()
+ })
+
+ it('is absent for a local project, a relay tab and when the canvas offers no share', async () => {
+ await open({})
+ expect(shareRow()).toBeUndefined()
+ act(() => root.unmount())
+ root = createRoot(host)
+ await open({ ssh: SSH, remote: true })
+ expect(shareRow()).toBeUndefined()
+ act(() => root.unmount())
+ root = createRoot(host)
+ await open({ ssh: SSH }, { share: false })
+ expect(shareRow()).toBeUndefined()
+ })
+
+ it('is disabled with the reason while the share is blocked', async () => {
+ const reason = 'Connect this project first (its SSH connection is down).'
+ await open({ ssh: SSH }, { blocked: () => reason })
+ const row = shareRow()!
+ expect(row.disabled).toBe(true)
+ expect(row.title).toBe(reason)
+ await click(row)
+ expect(onShareWithTeam).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsx
index 8a226c948..e74c1244a 100644
--- a/src/renderer/components/TabBar.tsx
+++ b/src/renderer/components/TabBar.tsx
@@ -47,6 +47,11 @@ interface TabBarProps {
/** Deep-link to this project's own pane in Settings — everything this menu can change plus the
* shared/machine-local settings families, which have no other entry point. */
onOpenProjectSettings: (id: string) => void
+ /** Open "Share with team" for an SSH project. Absent = the row is not offered. */
+ onShareWithTeam?: (projectId: string) => void
+ /** Why the share cannot start for this project right now (the row is then disabled with it as
+ * its tooltip), or null when it can. */
+ shareBlockedReason?: (projectId: string) => string | null
}
/**
@@ -82,7 +87,9 @@ export function TabBar({
onRemoteAccess,
onSetDefaultAccount,
onSetDefaultPermissionMode,
- onOpenProjectSettings
+ onOpenProjectSettings,
+ onShareWithTeam,
+ shareBlockedReason
}: TabBarProps) {
// Select the raw array and filter in a memo, a `.filter()` inside the selector returns a
// fresh array every store snapshot, which re-rendered the TabBar on EVERY projects change.
@@ -521,6 +528,24 @@ export function TabBar({
>
Remote access…
</button>
+ {menuProject.ssh &&
+ !menuProject.remote &&
+ onShareWithTeam &&
+ (() => {
+ const blocked = shareBlockedReason?.(menuProject.id) ?? null
+ return (
+ <button
+ disabled={!!blocked}
+ title={blocked ?? undefined}
+ onClick={() => {
+ onShareWithTeam(menuProject.id)
+ closeMenu()
+ }}
+ >
+ Share with team…
+ </button>
+ )
+ })()}
{menuAccounts.length > 0 && (
<>
<button
diff --git a/src/renderer/lib/shareTeamCanvas.test.ts b/src/renderer/lib/shareTeamCanvas.test.ts
new file mode 100644
index 000000000..23bac305b
--- /dev/null
+++ b/src/renderer/lib/shareTeamCanvas.test.ts
@@ -0,0 +1,240 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { CanvasNodeState, HandedOffTo } from '@shared/types'
+import {
+ SHARE_FOCUS_WAIT_MS,
+ SHARE_SAVE_FAILED,
+ followSharedProject,
+ shareFocusStep,
+ shareProjectDeps,
+ shareTerminals,
+ type ShareCanvasOps
+} from './shareTeamCanvas'
+
+const node = (over: Partial<CanvasNodeState> & { id: string }): CanvasNodeState => ({
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 1, height: 1 },
+ title: over.id,
+ color: '#fff',
+ group: null,
+ ...over
+})
+
+describe('shareTerminals', () => {
+ it('takes terminal nodes only (a legacy node without a kind is one), with what is known of each agent', () => {
+ const nodes = [
+ node({ id: 'a', title: 'Claude', agentId: 'claude', agentSessionId: 'minted', accountId: 'acc' }),
+ node({ id: 'b', title: '' }),
+ { ...node({ id: 'legacy' }), kind: undefined as unknown as CanvasNodeState['kind'] },
+ node({ id: 's', kind: 'sticky' }),
+ node({ id: 'g', kind: 'group' })
+ ]
+ const out = shareTerminals(nodes, { a: { sessionId: 'hooked', state: 'done' } })
+ expect(out).toEqual([
+ // The hook-fed id wins over the minted one: /clear and --fork-session mint a new one in-CLI.
+ { nodeId: 'a', title: 'Claude', agentId: 'claude', sessionId: 'hooked', accountId: 'acc', state: 'done' },
+ // An untitled node is listed by its id.
+ { nodeId: 'b', title: 'b' },
+ { nodeId: 'legacy', title: 'legacy' }
+ ])
+ })
+
+ it('falls back to the persisted session id when no hook reported one', () => {
+ const out = shareTerminals([node({ id: 'a', agentId: 'claude', agentSessionId: 'minted' })], {})
+ expect(out[0].sessionId).toBe('minted')
+ expect('state' in out[0]).toBe(false)
+ })
+})
+
+type FakeOps = ShareCanvasOps & { calls: string[]; mark: HandedOffTo | undefined; closed: boolean }
+
+function ops(over: Partial<ShareCanvasOps> = {}): FakeOps {
+ const calls: string[] = []
+ const o: FakeOps = {
+ calls,
+ mark: undefined,
+ closed: false,
+ commit: () => void calls.push('commit'),
+ save: async () => {
+ calls.push('save')
+ return true
+ },
+ setHandedOffTo: (v: HandedOffTo | undefined) => {
+ calls.push(v ? `mark:${v.hostId ?? '-'}` : 'unmark')
+ o.mark = v
+ },
+ isClosed: () => o.closed,
+ close: () => {
+ calls.push('close')
+ o.closed = true
+ },
+ reopen: () => {
+ calls.push('reopen')
+ o.closed = false
+ },
+ join: (code: string, focus: string): 'started' | 'busy' | null => {
+ calls.push(`join:${code}:${focus}`)
+ return 'started'
+ },
+ followTab: (id: string) => void calls.push(`follow:${id}`),
+ now: () => 42,
+ ...over
+ }
+ return o
+}
+
+describe('shareProjectDeps', () => {
+ it('prepare commits the live canvas, then awaits the save', async () => {
+ const o = ops()
+ await shareProjectDeps(o).prepare()
+ expect(o.calls).toEqual(['commit', 'save'])
+ })
+
+ it('every step that saves fails when the save did not land', async () => {
+ const o = ops({ save: async () => false })
+ const d = shareProjectDeps(o)
+ await expect(d.prepare()).rejects.toThrow(SHARE_SAVE_FAILED)
+ await expect(d.markPending()).rejects.toThrow(SHARE_SAVE_FAILED)
+ await expect(d.release()).rejects.toThrow(SHARE_SAVE_FAILED)
+ await expect(d.restore()).rejects.toThrow(SHARE_SAVE_FAILED)
+ await expect(d.markHandedOff({ hostId: 'H', projectId: 'P' })).rejects.toThrow(SHARE_SAVE_FAILED)
+ })
+
+ it('markPending sets the in-progress mark (no host yet) and saves', async () => {
+ const o = ops()
+ await shareProjectDeps(o).markPending()
+ expect(o.mark).toEqual({ at: 42 })
+ expect(o.calls).toEqual(['mark:-', 'save'])
+ })
+
+ it('release only closes and saves: the mark is already set', async () => {
+ const o = ops()
+ await shareProjectDeps(o).release()
+ expect(o.calls).toEqual(['close', 'save'])
+ })
+
+ it('restore clears the mark, reopens a closed project, and saves', async () => {
+ const o = ops()
+ o.mark = { at: 1 }
+ o.closed = true
+ await shareProjectDeps(o).restore()
+ expect(o.calls).toEqual(['unmark', 'reopen', 'save'])
+ expect(o.mark).toBeUndefined()
+ expect(o.isClosed()).toBe(false)
+ })
+
+ it('restore on a project that was never closed only clears the mark (nothing is reopened or switched to)', async () => {
+ const o = ops()
+ o.mark = { at: 1 }
+ await shareProjectDeps(o).restore()
+ expect(o.calls).toEqual(['unmark', 'save'])
+ })
+
+ it('markHandedOff records the team and the server project, stamped now', async () => {
+ const o = ops()
+ await shareProjectDeps(o).markHandedOff({ hostId: 'H', projectId: 'P' })
+ expect(o.mark).toEqual({ hostId: 'H', projectId: 'P', at: 42 })
+ expect(o.calls).toEqual(['mark:H', 'save'])
+ })
+
+ it('a join that started lands by itself; a busy one (the team is live here) follows the shared tab', () => {
+ const started = ops()
+ shareProjectDeps(started).join('CODE', 'P9')
+ expect(started.calls).toEqual(['join:CODE:P9'])
+ const busy = ops({ join: () => 'busy' })
+ shareProjectDeps(busy).join('CODE', 'P9')
+ expect(busy.calls).toEqual(['follow:P9'])
+ const none = ops({ join: () => null })
+ shareProjectDeps(none).join('CODE', 'P9')
+ expect(none.calls).toEqual([])
+ })
+})
+
+describe('shareFocusStep', () => {
+ it('switches once the tab is open, waits while it is not, and stops when there or moved away', () => {
+ expect(shareFocusStep('T', 'A', { activeId: 'A', targetOpen: true })).toBe('switch')
+ expect(shareFocusStep('T', 'A', { activeId: 'A', targetOpen: false })).toBe('wait')
+ expect(shareFocusStep('T', 'A', { activeId: 'T', targetOpen: true })).toBe('stop')
+ // The user went elsewhere themselves: never pulled back.
+ expect(shareFocusStep('T', 'A', { activeId: 'B', targetOpen: false })).toBe('stop')
+ })
+})
+
+describe('followSharedProject', () => {
+ function harness(initial: { activeId: string; targetOpen: boolean }) {
+ let view = { ...initial }
+ const listeners = new Set<() => void>()
+ const timers: Array<{ fn: () => void; ms: number; cleared: boolean }> = []
+ const switchTo = vi.fn((id: string) => {
+ view = { ...view, activeId: id }
+ })
+ const deps = {
+ targetId: 'T',
+ read: () => view,
+ subscribe: (l: () => void) => {
+ listeners.add(l)
+ return () => void listeners.delete(l)
+ },
+ switchTo,
+ setTimer: (fn: () => void, ms: number) => {
+ const t = { fn, ms, cleared: false }
+ timers.push(t)
+ return t
+ },
+ clearTimer: (t: unknown) => {
+ ;(t as { cleared: boolean }).cleared = true
+ }
+ }
+ const change = (next: Partial<typeof view>): void => {
+ view = { ...view, ...next }
+ for (const l of [...listeners]) l()
+ }
+ return { deps, switchTo, change, listeners, timers }
+ }
+
+ it('switches at once when the tab is already open, and watches nothing', () => {
+ const h = harness({ activeId: 'A', targetOpen: true })
+ followSharedProject(h.deps)
+ expect(h.switchTo).toHaveBeenCalledWith('T')
+ expect(h.listeners.size).toBe(0)
+ expect(h.timers).toHaveLength(0)
+ })
+
+ it('switches when the share event opens the tab, then stops watching', () => {
+ const h = harness({ activeId: 'A', targetOpen: false })
+ followSharedProject(h.deps)
+ expect(h.switchTo).not.toHaveBeenCalled()
+ expect(h.timers[0].ms).toBe(SHARE_FOCUS_WAIT_MS)
+ h.change({ targetOpen: true })
+ expect(h.switchTo).toHaveBeenCalledTimes(1)
+ expect(h.listeners.size).toBe(0)
+ expect(h.timers[0].cleared).toBe(true)
+ h.change({ activeId: 'A' })
+ expect(h.switchTo).toHaveBeenCalledTimes(1)
+ })
+
+ it('gives up when the user switches projects themselves', () => {
+ const h = harness({ activeId: 'A', targetOpen: false })
+ followSharedProject(h.deps)
+ h.change({ activeId: 'B' })
+ h.change({ targetOpen: true })
+ expect(h.switchTo).not.toHaveBeenCalled()
+ expect(h.listeners.size).toBe(0)
+ })
+
+ it('gives up after the wait, and when stopped by its caller', () => {
+ const h = harness({ activeId: 'A', targetOpen: false })
+ followSharedProject(h.deps)
+ h.timers[0].fn()
+ h.change({ targetOpen: true })
+ expect(h.switchTo).not.toHaveBeenCalled()
+ expect(h.listeners.size).toBe(0)
+
+ const k = harness({ activeId: 'A', targetOpen: false })
+ const stop = followSharedProject(k.deps)
+ stop()
+ k.change({ targetOpen: true })
+ expect(k.switchTo).not.toHaveBeenCalled()
+ expect(k.timers[0].cleared).toBe(true)
+ })
+})
diff --git a/src/renderer/lib/shareTeamCanvas.ts b/src/renderer/lib/shareTeamCanvas.ts
new file mode 100644
index 000000000..7f388146f
--- /dev/null
+++ b/src/renderer/lib/shareTeamCanvas.ts
@@ -0,0 +1,143 @@
+// The canvas side of "Share with team": what `runShare` (shareSshTeam.ts) is handed about the
+// project, the project-store steps it calls, and landing on the shared project afterwards. Pure
+// over injected canvas operations, so each rule below is pinned by a test rather than by a reading
+// of Canvas.tsx.
+import type { AgentState } from '@shared/agents/normalize'
+import type { CanvasNodeState, HandedOffTo } from '@shared/types'
+import type { ShareDeps, ShareNode } from './shareSshTeam'
+
+/** The project's terminal nodes as the share sees them. The hook-fed session id wins over the one
+ * persisted at launch: `/clear` and `--fork-session` mint a new one inside the CLI. */
+export function shareTerminals(
+ nodes: CanvasNodeState[],
+ status: Record<string, { sessionId?: string; state?: AgentState } | undefined>
+): ShareNode[] {
+ return nodes
+ .filter((n) => (n.kind ?? 'terminal') === 'terminal')
+ .map((n) => {
+ const live = status[n.id]
+ const sessionId = live?.sessionId ?? n.agentSessionId
+ return {
+ nodeId: n.id,
+ title: n.title || n.id,
+ ...(n.agentId ? { agentId: n.agentId } : {}),
+ ...(sessionId ? { sessionId } : {}),
+ ...(n.accountId ? { accountId: n.accountId } : {}),
+ ...(live?.state ? { state: live.state } : {})
+ }
+ })
+}
+
+/** What the share needs from the canvas for ONE project. */
+export interface ShareCanvasOps {
+ /** Commit the live canvas into the store. */
+ commit(): void
+ /** Save the workspace (on an SSH project this awaits the mirror queue); false = it failed. */
+ save(): Promise<boolean>
+ setHandedOffTo(value: HandedOffTo | undefined): void
+ isClosed(): boolean
+ /** Close the project non-destructively: its sessions keep running, and no dialog is raised. */
+ close(): void
+ /** Reopen it without the handed-off warning: this is the share's own undo. */
+ reopen(): void
+ /** The joiner's answer, or null when there is no joiner to ask. */
+ join(code: string, focusProjectId: string): 'started' | 'busy' | null
+ /** Take the user to this project once its tab is open. */
+ followTab(projectId: string): void
+ now(): number
+}
+
+export const SHARE_SAVE_FAILED = 'The canvas could not be saved on this computer.'
+
+/** The store steps of `runShare` for one project. Each one that saves fails when the save did not
+ * land: the orchestrator relies on "it resolved" meaning "it is on disk" (a mark that never reached
+ * the index does not stop the mirror). The orchestrator owns every undo; nothing here undoes. */
+export function shareProjectDeps(
+ ops: ShareCanvasOps
+): Pick<ShareDeps, 'prepare' | 'markPending' | 'release' | 'restore' | 'markHandedOff' | 'join'> {
+ const save = async (): Promise<void> => {
+ if (!(await ops.save())) throw new Error(SHARE_SAVE_FAILED)
+ }
+ return {
+ async prepare() {
+ ops.commit()
+ await save()
+ },
+ async markPending() {
+ ops.setHandedOffTo({ at: ops.now() })
+ await save()
+ },
+ async release() {
+ ops.close()
+ await save()
+ },
+ // Also called on a project that was never closed (a failure before `release`): reopening only
+ // what is closed means the undo never moves the user to another project.
+ async restore() {
+ ops.setHandedOffTo(undefined)
+ if (ops.isClosed()) ops.reopen()
+ await save()
+ },
+ async markHandedOff(to) {
+ ops.setHandedOffTo({ ...to, at: ops.now() })
+ await save()
+ },
+ // A join that starts lands on the shared project itself. A busy one means this desktop is
+ // already connected to the team: nothing mounts, and the project's tab arrives through the
+ // team's share event, which opens it without taking the screen.
+ join(code, focusProjectId) {
+ if (ops.join(code, focusProjectId) === 'busy') ops.followTab(focusProjectId)
+ }
+ }
+}
+
+/** How long a share follows the shared project's tab before giving up on it. */
+export const SHARE_FOCUS_WAIT_MS = 30_000
+
+export interface ShareFocusView {
+ activeId: string
+ targetOpen: boolean
+}
+
+/** One look at the store: switch to the shared tab now that it is open, keep waiting, or stop
+ * (already there, or the user moved to another project themselves and must not be pulled back). */
+export function shareFocusStep(targetId: string, startActiveId: string, now: ShareFocusView): 'switch' | 'wait' | 'stop' {
+ if (now.activeId === targetId) return 'stop'
+ if (now.targetOpen) return 'switch'
+ if (now.activeId !== startActiveId) return 'stop'
+ return 'wait'
+}
+
+/** Switch to `targetId` once its tab is open, at most `SHARE_FOCUS_WAIT_MS` from now. Returns a
+ * stop function (idempotent). */
+export function followSharedProject(deps: {
+ targetId: string
+ read(): ShareFocusView
+ subscribe(listener: () => void): () => void
+ switchTo(id: string): void
+ setTimer(fn: () => void, ms: number): unknown
+ clearTimer(handle: unknown): void
+}): () => void {
+ const startActiveId = deps.read().activeId
+ let done = false
+ let unsubscribe: () => void = () => {}
+ let timer: unknown
+ const stop = (): void => {
+ if (done) return
+ done = true
+ unsubscribe()
+ if (timer !== undefined) deps.clearTimer(timer)
+ }
+ const check = (): void => {
+ if (done) return
+ const step = shareFocusStep(deps.targetId, startActiveId, deps.read())
+ if (step === 'wait') return
+ stop()
+ if (step === 'switch') deps.switchTo(deps.targetId)
+ }
+ check()
+ if (done) return stop
+ unsubscribe = deps.subscribe(check)
+ timer = deps.setTimer(stop, SHARE_FOCUS_WAIT_MS)
+ return stop
+}
diff --git a/src/renderer/state/projects.test.ts b/src/renderer/state/projects.test.ts
index 80c883114..3c04720d0 100644
--- a/src/renderer/state/projects.test.ts
+++ b/src/renderer/state/projects.test.ts
@@ -376,3 +376,30 @@ describe('closeProject on a background project (issue #848: the offer outlives a
expect(s.getProject(b.id)).toBe(activeBefore)
})
})
+
+describe('setHandedOffTo', () => {
+ it('sets and clears the handover mark, and toWorkspace carries it to the save', () => {
+ const p = useProjects.getState().addProject('box', undefined, {
+ server: { host: 'box', user: 'alice' },
+ remoteCwd: '~/proj'
+ })
+ useProjects.getState().setHandedOffTo(p.id, { at: 5 })
+ expect(useProjects.getState().getProject(p.id)?.handedOffTo).toEqual({ at: 5 })
+ useProjects.getState().setHandedOffTo(p.id, { hostId: 'H', projectId: 'project-9', at: 6 })
+ const saved = useProjects.getState().toWorkspace().projects.find((x) => x.id === p.id)
+ expect(saved?.handedOffTo).toEqual({ hostId: 'H', projectId: 'project-9', at: 6 })
+ useProjects.getState().setHandedOffTo(p.id, undefined)
+ const cleared = useProjects.getState().getProject(p.id)!
+ // Cleared means absent, not `undefined`: the index entry must lose the field.
+ expect('handedOffTo' in cleared).toBe(false)
+ })
+
+ it('leaves other projects alone and ignores an unknown id', () => {
+ const a = useProjects.getState().addProject('a', '/a')
+ const b = useProjects.getState().addProject('b', '/b')
+ useProjects.getState().setHandedOffTo(a.id, { at: 1 })
+ useProjects.getState().setHandedOffTo('nope', { at: 2 })
+ expect(useProjects.getState().getProject(b.id)?.handedOffTo).toBeUndefined()
+ expect(useProjects.getState().projects).toHaveLength(2)
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 6f3583c01..92eea35dd 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -5,6 +5,7 @@ import type {
CanvasMutation,
CanvasNodeState,
ClosedSessionEntry,
+ HandedOffTo,
NavStop,
Project,
ProjectKanban,
@@ -103,6 +104,10 @@ interface ProjectsState {
/** Sets (or clears, with undefined = fall back to the global setting) the project's default
* permission mode for new Claude terminal (CLI) sessions. Chat nodes are not covered. */
setProjectDefaultPermissionMode(id: string, mode: AgentPermissionMode | undefined): void
+ /** Sets (or clears, with undefined) the machine-local mark that this SSH project was handed to a
+ * hosted team (see `HandedOffTo`). Cleared means the field is gone, so the next save drops it
+ * from the index entry. The caller saves. No-op for an unknown id. */
+ setHandedOffTo(id: string, value: HandedOffTo | undefined): void
/**
* THE strict per-project capability setter (@shared/project-capabilities). `on` writes the
* literal `true` the validators accept AND records this machine's 'kept' answer — setting a
@@ -604,6 +609,17 @@ export const useProjects = create<ProjectsState>((set, get) => ({
}))
},
+ setHandedOffTo(id, value) {
+ set((s) => ({
+ projects: s.projects.map((p) => {
+ if (p.id !== id) return p
+ if (value) return { ...p, handedOffTo: value }
+ const { handedOffTo: _drop, ...rest } = p
+ return rest
+ })
+ }))
+ },
+
setProjectCapability(id, cap, on) {
set((s) => ({
projects: s.projects.map((p) => {
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index bf522c5cb..b9c15bad8 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -11771,6 +11771,75 @@ button.pull-checks__name {
color: var(--muted);
font-size: 12px;
}
+/* "Share with team" (ShareTeamDialog): the `.confirm` shell, wider for the lists, with the body as
+ the scrolling region so Share / Close stay on screen however long the lists are. */
+.confirm.share-team {
+ width: 480px;
+}
+.share-team__title {
+ flex: 0 0 auto;
+ margin: 0 0 10px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text);
+ overflow-wrap: anywhere;
+}
+.share-team__body {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ margin-bottom: 14px;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--text);
+}
+.share-team__body p {
+ margin: 0 0 8px;
+ overflow-wrap: anywhere;
+}
+.share-team__heading {
+ color: var(--muted);
+}
+.share-team__list {
+ margin: -4px 0 10px;
+ padding-left: 18px;
+ overflow-wrap: anywhere;
+}
+/* The security sentence: always visible, the status-chip recipe like the live link warning. */
+.share-team__warning {
+ padding: 8px 10px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--state-warning) 12%, transparent);
+}
+.share-team__error {
+ color: var(--danger);
+}
+.share-team__code {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ margin-bottom: 8px;
+}
+.share-team__code .confirm__input {
+ flex: 1 1 auto;
+ min-width: 0;
+ margin: 0;
+}
+/* The installer's output: a sunken well, the tail only (the component keeps the last 4000 chars). */
+.share-team__log {
+ max-height: 180px;
+ overflow: auto;
+ margin: 0 0 8px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ background: var(--surface-sunken);
+ font-family: ui-monospace, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ color: var(--text);
+}
/* The session name in the card modal header: sized to its text, not a flex-filling detail line. */
.kanban-modal__session {
flex: 0 1 auto;