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): shareTeam IPC — probe, install, flush, bootstrap, kill-verify, resume, seed bookmark
reviewb41600c06eb8
diff --git a/src/main/index.ts b/src/main/index.tsindex db77e0e1a..95bfb012a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -133,6 +133,8 @@ import { registerWorktreeSharedPathsHandlers } from '../core/worktree-shared-patimport { makeProjectSpawnOverrides } from '../core/project-spawn-overrides'import { makeLocalSetupRunner } from '../core/project-setup-runner-local'import { makeSshSetupRunner } from './remote-ssh/ssh-setup-runner'+import { createShareTeamHandlers, SHARE_INSTALL_TIMEOUT_MS } from './remote-ssh/share-team'+import { registerShareTeamIpc } from './remote-ssh/share-team-ipc'import { registerGitHubIntegration } from '../core/github/integration'import {answerGitHubRead,@@ -4724,6 +4726,38 @@ app.whenReady().then(async () => {ipcMain.handle(IPC.relayHostedBookmarks, async () => (await bookmarks.list()).map(publicBookmark))// Forgetting a team also forgets the device token this app run holds for it in memory.ipcMain.handle(IPC.relayHostedBookmarkRemove, async (_e, hostId: string) => removeHostedBookmark(String(hostId), bookmarks))+ // Share an SSH project with a hosted team (the desktop half; see share-team.ts). Here because+ // the bookmark store is block-scoped to this relay block. Every dependency resolves the ssh+ // manager lazily: it is created right after this block.+ registerShareTeamIpc(+ createShareTeamHandlers({+ ref: (projectId) => sshProjectManager?.refForProject(projectId),+ run: (args, stdin, timeoutMs) =>+ sshProjectManager ? sshProjectManager.sshRun(args, stdin, { timeoutMs }) : Promise.resolve({ code: 1, stdout: '' }),+ runInstall: (projectId, script, onChunk, signal) => {+ const r = sshProjectManager?.refForProject(projectId)+ if (!r) return Promise.resolve({ exitCode: 255 })+ // The connection is already resolved for this project; the runner's own endpoint match+ // then checks it against the same connection.+ const runner = makeSshSetupRunner(() => ({ conn: r.conn, controlPath: r.controlPath }), {+ timeoutMs: SHARE_INSTALL_TIMEOUT_MS+ })+ return runner({ script, cwd: '~', env: {}, onChunk, signal, ssh: { server: r.conn, remoteCwd: '~' } })+ },+ flushMirror: () => remoteWorkspaceIO.flush(),+ readRemoteProject: (projectId) => {+ const r = sshProjectManager?.refForProject(projectId)+ return r?.remoteCwd+ ? remoteWorkspaceIO.read(projectId, { server: r.conn, remoteCwd: r.remoteCwd })+ : Promise.resolve({ status: 'error' as const })+ },+ ownerKey: async () => publicKeyToB64((await loadOrCreatePeerKeyPair()).publicKey),+ ownerLabel: () => hostname(),+ bookmarks,+ now: () => Date.now()+ }),+ sendTo+ )}// Windows SSH projects: the opt-in to keep passphrase-unlocked keys in the Windows OpenSSH agent// (core/remote-ssh/native/agent-add.ts). Read at each unlock, so a toggle applies to the next one.diff --git a/src/main/remote-ssh/share-team-ipc.ts b/src/main/remote-ssh/share-team-ipc.tsnew file mode 100644index 000000000..83e45df15--- /dev/null+++ b/src/main/remote-ssh/share-team-ipc.ts@@ -0,0 +1,26 @@+import { ipcMain } from 'electron'+import { IPC } from '../../shared/ipc'+import type { ShareTeamHandlers } from './share-team'++/** Raw `ipcMain` handlers, never on the platform: a relay peer can never reach them. Every argument+ * is coerced here, and the handlers re-validate what they use (the resume list included). */+export function registerShareTeamIpc(h: ShareTeamHandlers, send: (channel: string, ...args: unknown[]) => void): void {+ ipcMain.handle(IPC.shareTeamProbe, (_e, projectId: string, nodeIds: unknown) =>+ h.probe(String(projectId), Array.isArray(nodeIds) ? nodeIds.map(String) : [])+ )+ ipcMain.handle(IPC.shareTeamInstall, (_e, projectId: string) =>+ h.install(String(projectId), (text) => send(IPC.shareTeamInstallOutput, { projectId: String(projectId), text }))+ )+ ipcMain.handle(IPC.shareTeamCancelInstall, (_e, projectId: string) => h.cancelInstall(String(projectId)))+ ipcMain.handle(IPC.shareTeamFlushMirror, (_e, projectId: string) => h.flushMirror(String(projectId)))+ ipcMain.handle(IPC.shareTeamBootstrap, (_e, projectId: string, adoptCwd: string) =>+ h.bootstrap(String(projectId), String(adoptCwd))+ )+ ipcMain.handle(IPC.shareTeamKillSessions, (_e, projectId: string, nodeIds: unknown) =>+ h.killSessions(String(projectId), Array.isArray(nodeIds) ? nodeIds.map(String) : [])+ )+ ipcMain.handle(IPC.shareTeamResume, (_e, projectId: string, serverProjectId: string, sessions: unknown) =>+ h.resume(String(projectId), String(serverProjectId), sessions as never)+ )+ ipcMain.handle(IPC.shareTeamSeedBookmark, (_e, joinCode: string) => h.seedBookmark(String(joinCode)))+}diff --git a/src/main/remote-ssh/share-team.test.ts b/src/main/remote-ssh/share-team.test.tsnew file mode 100644index 000000000..786fd7f9e--- /dev/null+++ b/src/main/remote-ssh/share-team.test.ts@@ -0,0 +1,239 @@+import { describe, it, expect } from 'vitest'+import { createShareTeamHandlers, SHARE_TIMEOUTS, type ShareTeamDeps } from './share-team'+import { encodeJoinCode } from '../../core/relay/join-code'+import { genKeyPair, publicKeyToB64 } from '../../core/relay/e2ee'+import { hostIdFromPublicKeyB64 } from '../../core/relay/relay-id'+import type { RelayBookmark } from '../remote/relay-bookmarks'++const OWNER = publicKeyToB64(genKeyPair().publicKey)+const hostKey = publicKeyToB64(genKeyPair().publicKey)+const CODE = encodeJoinCode({ v: 1, relayEndpoint: 'wss://relay.example', hostId: hostIdFromPublicKeyB64(hostKey), hostPublicKeyB64: hostKey, hostDeviceId: 'dev', label: 'box' })++const PROBE_OUT = [+ '##NTP 1', '##OS Linux', '##UID 1000', '##USER alice', '##HOME /home/alice', '##HAVE git yes', '##HAVE curl yes',+ '##UNIT user', '##NODE /usr/bin/node', '##MAIN /home/alice/app/out/server/main.cjs', '##DATADIR /home/alice/.nodeterm-server',+ '##BOOTSTRAP yes', '##STATUSRC 0', '##STATUS', '{"enabled":true,"off":null}', '##STATUSEND',+ '##CWD /home/alice/proj', '##PANES', 'nt-term-a|claude', 'nt-term-b|npm', '##PANESEND', '##END'+].join('\n')++function deps(+ o: {+ connected?: boolean+ remoteCwd?: string+ replies?: string[]+ bookmarks?: RelayBookmark[]+ remote?: { status: 'ok'; content: string } | { status: 'absent' } | { status: 'error' }+ label?: string+ ownerKey?: () => Promise<string>+ runInstall?: ShareTeamDeps['runInstall']+ } = {}+) {+ const calls: Array<{ args: string[]; stdin?: string; timeoutMs: number }> = []+ const replies = [...(o.replies ?? [])]+ const saved: RelayBookmark[] = [...(o.bookmarks ?? [])]+ const order: string[] = []+ const d: ShareTeamDeps = {+ ref: () => (o.connected === false ? undefined : { conn: { host: 'h', user: 'alice' } as never, controlPath: '/cp', remoteCwd: o.remoteCwd ?? '~/proj' }),+ run: async (args, stdin, timeoutMs) => {+ calls.push({ args, stdin, timeoutMs })+ return { code: 0, stdout: replies.shift() ?? '' }+ },+ runInstall: o.runInstall ?? (async () => ({ exitCode: 0 })),+ flushMirror: async () => void order.push('flush'),+ readRemoteProject: async () => (order.push('read'), o.remote ?? { status: 'ok', content: JSON.stringify({ version: 1, nodes: [{ id: 'term-a' }, { id: 'term-b' }] }) }),+ ownerKey: o.ownerKey ?? (async () => OWNER),+ ownerLabel: () => o.label ?? 'My Mac\u0007',+ bookmarks: {+ list: async () => saved,+ upsert: async (b) => void (saved.splice(0, saved.length, ...saved.filter((x) => x.hostId !== b.hostId), b)),+ update: async (hostId, patch) => {+ const i = saved.findIndex((x) => x.hostId === hostId)+ if (i >= 0) saved[i] = { ...saved[i], ...patch }+ }+ },+ now: () => Date.parse('2026-10-01T10:00:00Z')+ }+ return { h: createShareTeamHandlers(d), calls, saved, order }+}+const cli = (body: unknown, rc = 0): string => `##NTB\n${JSON.stringify(body)}\n##NTRC ${rc}\n`+const GOOD = (): Record<string, unknown> => ({+ hostId: hostIdFromPublicKeyB64(hostKey),+ projectId: 'project-1',+ projectName: 'proj',+ joinCode: CODE,+ hosting: 'up',+ created: { team: true, owner: true, project: true, share: true }+})+const lastArg = (c: { args: string[] }): string => c.args[c.args.length - 1]++describe('share-team handlers', () => {+ it('probe: refuses a disconnected project with E_NOT_CONNECTED', async () => {+ const { h } = deps({ connected: false })+ expect(await h.probe('p', [])).toMatchObject({ ok: false, code: 'E_NOT_CONNECTED' })+ })+ it('probe: parses, plans and maps pane commands to node ids, with the probe timeout', async () => {+ const { h, calls } = deps({ replies: [PROBE_OUT] })+ const r = await h.probe('p', ['term-a', 'term-b', 'term-c'])+ expect(r).toMatchObject({ ok: true, plan: { kind: 'ready' }, paneCommands: { 'term-a': 'claude', 'term-b': 'npm' } })+ expect(calls[0].timeoutMs).toBe(SHARE_TIMEOUTS.probe)+ })+ it('probe: an unsafe node id never reaches the pane map', async () => {+ const { h } = deps({ replies: [PROBE_OUT] })+ const r = await h.probe('p', ['term-a', '../term-b'])+ expect(r).toMatchObject({ ok: true, paneCommands: { 'term-a': 'claude' } })+ expect(r.ok && Object.keys(r.paneCommands)).toEqual(['term-a'])+ })+ it('probe: a folder the login shell cannot quote is refused, never run', async () => {+ const { h, calls } = deps({ remoteCwd: "~/it's" })+ expect(await h.probe('p', [])).toMatchObject({ ok: false, error: expect.stringMatching(/quote or backslash/) })+ expect(calls).toHaveLength(0)+ })+ it('probe: a cut-short reply is an error and forgets the earlier probe', async () => {+ const { h } = deps({ replies: [PROBE_OUT, '##NTP 1\n##OS Linux\n'] })+ await h.probe('p', [])+ expect(await h.probe('p', [])).toMatchObject({ ok: false, error: expect.stringMatching(/did not finish/) })+ expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })+ })+ it('bootstrap needs a ready probe first', async () => {+ const { h } = deps()+ expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })+ })+ it('bootstrap: passes the owner key, a control-free label and the folder; validates the join code', async () => {+ const good = GOOD()+ const { h, calls } = deps({ replies: [PROBE_OUT, cli(good)] })+ await h.probe('p', [])+ const r = await h.bootstrap('p', '/home/alice/proj')+ expect(r).toMatchObject({ ok: true, result: good })+ const cmd = lastArg(calls[1])+ expect(cmd).toContain(OWNER)+ expect(cmd).toContain("'My Mac'")+ expect(cmd).toContain("'/home/alice/proj'")+ expect(calls[1].timeoutMs).toBe(SHARE_TIMEOUTS.bootstrap)+ })+ it('bootstrap: a label with an apostrophe or backslash goes through with them removed', async () => {+ const { h, calls } = deps({ label: "Enes's \\Mac", replies: [PROBE_OUT, cli(GOOD())] })+ await h.probe('p', [])+ expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: true })+ expect(lastArg(calls[1])).toContain("'Eness Mac'")+ })+ it('bootstrap: an over-long label is capped, never refused', async () => {+ const { h, calls } = deps({ label: 'x'.repeat(80), replies: [PROBE_OUT, cli(GOOD())] })+ await h.probe('p', [])+ expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: true })+ expect(lastArg(calls[1])).toContain(`'${'x'.repeat(60)}'`)+ expect(lastArg(calls[1])).not.toContain('x'.repeat(61))+ })+ it('bootstrap: only the known result fields come back', async () => {+ const { h } = deps({ replies: [PROBE_OUT, cli({ ...GOOD(), extra: 'ignored' })] })+ await h.probe('p', [])+ const r = await h.bootstrap('p', '/home/alice/proj')+ expect(r.ok && Object.keys(r.result).sort()).toEqual(['created', 'hostId', 'hosting', 'joinCode', 'projectId', 'projectName'])+ })+ it('bootstrap: a server refusal keeps its code; a join code for another host is refused', async () => {+ const { h } = deps({ replies: [PROBE_OUT, cli({ ok: false, code: 'E_HOSTING_OFF', error: 'refused (403)' }, 1)] })+ await h.probe('p', [])+ expect(await h.bootstrap('p', '/x')).toEqual({ ok: false, code: 'E_HOSTING_OFF', error: 'refused (403)' })+ const forged = { hostId: 'someone-else', projectId: 'project-1', projectName: 'p', joinCode: CODE, hosting: 'up', created: { team: false, owner: false, project: false, share: false } }+ const d2 = deps({ replies: [PROBE_OUT, cli(forged)] })+ await d2.h.probe('p', [])+ expect(await d2.h.bootstrap('p', '/x')).toMatchObject({ ok: false, error: expect.stringMatching(/join code/i) })+ })+ it('bootstrap: a refusal code outside the E_* shape is dropped, and a malformed result is refused', async () => {+ const { h } = deps({ replies: [PROBE_OUT, cli({ ok: false, code: 'nope', error: 'no' }, 1), cli({ ...GOOD(), hosting: 'down' })] })+ await h.probe('p', [])+ expect(await h.bootstrap('p', '/x')).toEqual({ ok: false, error: 'no' })+ expect(await h.bootstrap('p', '/x')).toMatchObject({ ok: false })+ })+ it('bootstrap: a key that cannot be read is a reply, never a rejection, and keeps its code', async () => {+ const locked = async (): Promise<string> => {+ throw Object.assign(new Error('The keyring is locked.'), { code: 'E_PEER_KEY_LOCKED' })+ }+ const { h, calls } = deps({ ownerKey: locked, replies: [PROBE_OUT] })+ await h.probe('p', [])+ expect(await h.bootstrap('p', '/x')).toEqual({ ok: false, code: 'E_PEER_KEY_LOCKED', error: 'The keyring is locked.' })+ expect(calls).toHaveLength(1)+ })+ it('killSessions: refuses an unsafe id before running anything; parses per-node states', async () => {+ const { h, calls } = deps({ replies: ['##NTK\n##K nt-term-a gone\n##K nt-term-b alive\n##NTKEND\n'] })+ expect(await h.killSessions('p', ['../x'])).toMatchObject({ ok: false })+ expect(calls).toHaveLength(0)+ expect(await h.killSessions('p', ['term-a', 'term-b'])).toEqual({ ok: true, results: [{ nodeId: 'term-a', state: 'gone' }, { nodeId: 'term-b', state: 'alive' }] })+ expect(calls[0].timeoutMs).toBe(SHARE_TIMEOUTS.kill)+ })+ it('killSessions: an empty list runs nothing; too many ids are refused', async () => {+ const { h, calls } = deps()+ expect(await h.killSessions('p', [])).toEqual({ ok: true, results: [] })+ expect(await h.killSessions('p', Array.from({ length: 201 }, (_, i) => `n${i}`))).toMatchObject({ ok: false })+ expect(calls).toHaveLength(0)+ })+ it('resume: the session list goes on stdin, never argv', async () => {+ const { h, calls } = deps({ replies: [PROBE_OUT, cli({ results: [{ nodeId: 'term-a', status: 'resumed' }] })] })+ await h.probe('p', [])+ const sessions = [{ nodeId: 'term-a', agentId: 'claude', sessionId: 's-1', permissionMode: 'auto' }]+ expect(await h.resume('p', 'project-1', sessions)).toEqual({ ok: true, results: [{ nodeId: 'term-a', status: 'resumed' }] })+ expect(calls[1].stdin).toBe(JSON.stringify(sessions))+ expect(calls[1].args.join(' ')).not.toContain('s-1')+ expect(calls[1].timeoutMs).toBe(SHARE_TIMEOUTS.resume)+ })+ it('resume: needs a probe, a valid project id and a valid session list; a malformed reply is refused', async () => {+ expect(await deps().h.resume('p', 'project-1', [])).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })+ const { h, calls } = deps({ replies: [PROBE_OUT, cli({ results: [{ nodeId: 'term-a', status: 'exploded' }] })] })+ await h.probe('p', [])+ expect(await h.resume('p', '', [])).toMatchObject({ ok: false })+ expect(await h.resume('p', 'project-1', [{ nodeId: 'a' }] as never)).toMatchObject({ ok: false })+ expect(calls).toHaveLength(1)+ expect(await h.resume('p', 'project-1', [])).toMatchObject({ ok: false })+ })+ it('flushMirror: flushes BEFORE reading, and reports the node ids on the host', async () => {+ const { h, order } = deps()+ expect(await h.flushMirror('p')).toEqual({ ok: true, nodeIds: ['term-a', 'term-b'] })+ expect(order).toEqual(['flush', 'read'])+ expect(await deps({ remote: { status: 'error' } }).h.flushMirror('p')).toMatchObject({ ok: false })+ expect(await deps({ remote: { status: 'absent' } }).h.flushMirror('p')).toEqual({ ok: true, nodeIds: [] })+ expect(await deps({ remote: { status: 'ok', content: '{not json' } }).h.flushMirror('p')).toMatchObject({ ok: false })+ })+ it('install: one run per project at a time, cancellable, output streamed', async () => {+ let release: (v: { exitCode: number }) => void = () => {}+ let seenSignal: AbortSignal | null = null+ const { h } = deps({+ runInstall: (_p, script, onChunk, signal) => {+ seenSignal = signal+ onChunk(script.includes('install-server.sh') ? 'installing\n' : '?')+ return new Promise((r) => (release = r))+ }+ })+ const chunks: string[] = []+ const first = h.install('p', (t) => chunks.push(t))+ expect(await h.install('p', () => {})).toEqual({ ok: false, error: 'An install is already running.' })+ await h.cancelInstall('p')+ expect(seenSignal!.aborted).toBe(true)+ release({ exitCode: 143 })+ expect(await first).toEqual({ ok: true, exitCode: 143 })+ expect(chunks).toEqual(['installing\n'])+ // The slot is free again once the run ends.+ const again = h.install('p', () => {})+ release({ exitCode: 0 })+ expect(await again).toEqual({ ok: true, exitCode: 0 })+ })+ it('seedBookmark: a new team gets an approved ssh bookmark; an existing unapproved one is approved; a bad code is refused', async () => {+ const a = deps()+ expect(await a.h.seedBookmark(CODE)).toMatchObject({ ok: true, label: 'box' })+ expect(a.saved).toEqual([{ hostId: hostIdFromPublicKeyB64(hostKey), code: CODE, label: 'box', deviceToken: null, approvedAt: '2026-10-01T10:00:00.000Z', source: 'ssh' }])+ const b = deps({ bookmarks: [{ hostId: hostIdFromPublicKeyB64(hostKey), code: CODE, label: 'box', deviceToken: 'tok', approvedAt: null, source: 'code' }] })+ await b.h.seedBookmark(CODE)+ expect(b.saved[0]).toMatchObject({ deviceToken: 'tok', approvedAt: '2026-10-01T10:00:00.000Z', source: 'code' })+ expect(await a.h.seedBookmark('nodeterm://join/garbage')).toMatchObject({ ok: false })+ })+ it('seedBookmark: an approved bookmark for the same key is left alone; one for another key is replaced', async () => {+ const hostId = hostIdFromPublicKeyB64(hostKey)+ const kept: RelayBookmark = { hostId, code: CODE, label: 'box', deviceToken: 'tok', approvedAt: '2026-01-01T00:00:00.000Z', source: 'code' }+ const a = deps({ bookmarks: [kept] })+ await a.h.seedBookmark(CODE)+ expect(a.saved).toEqual([kept])+ // Same hostId, different stored key: the stored code no longer decodes to this key.+ const stale: RelayBookmark = { ...kept, code: 'nodeterm://join?code=stale' }+ const b = deps({ bookmarks: [stale] })+ await b.h.seedBookmark(CODE)+ expect(b.saved).toEqual([{ hostId, code: CODE, label: 'box', deviceToken: null, approvedAt: '2026-10-01T10:00:00.000Z', source: 'ssh' }])+ })+})diff --git a/src/main/remote-ssh/share-team.ts b/src/main/remote-ssh/share-team.tsnew file mode 100644index 000000000..e1897e024--- /dev/null+++ b/src/main/remote-ssh/share-team.ts@@ -0,0 +1,380 @@+// The desktop's half of "Share with team" for an SSH project: hand the project to a nodeterm-server+// running on the same host as the user's own login, so teammates join it over the relay.+//+// Each verb runs ONE generated command (core/remote-ssh/share-team-remote.ts) over the project's+// ControlMaster, and every reply is parsed strictly: a cut-short or unrecognised answer is an error,+// never a half-read success.+//+// The server is not trusted with what it says about itself. A join code is accepted only through+// `decodeJoinCode`, which checks that the hostId is the hash of the key the code carries and that the+// relay endpoint is `wss:` (or loopback `ws:`); a bootstrap whose code names a different host than+// its own reply is refused.+//+// The probe is cached per project. `bootstrap` and `resume` run the server binary, main.cjs and data+// dir from that cached, validated probe, never from paths the renderer sends.+//+// Electron-free on purpose (only core, shared and the bookmark TYPE), so it is unit-tested directly;+// share-team-ipc.ts is the only file that touches `ipcMain`. Every handler answers a `ShareReply`+// and never rejects: a throw becomes `{ ok: false, error }`.+import { childArgs } from '../../core/remote-ssh/control-master'+import {+ SHARE_INSTALL_SCRIPT,+ killVerifyCommand,+ paneCommandsByNode,+ parseKillVerify,+ parseShareProbe,+ parseTeamCliOutput,+ shareProbeCommand,+ teamCliCommand+} from '../../core/remote-ssh/share-team-remote'+import { decodeJoinCode, encodeJoinCode } from '../../core/relay/join-code'+import { CONTROL_RE, ownerLabelProblem, projectIdProblem } from '../../core/relay/team-admin'+import { ADMIN_ERROR_CODE_RE, adminErrorCode } from '../../core/relay/admin-error'+import { TEAM_LABEL_MAX } from '../../core/relay/team-store'+import type { RemoteReadResult } from '../../core/workspace-store'+import { isSafeNodeId } from '../../shared/safe-id'+import {+ RESUME_MAX_SESSIONS,+ SHARE_MAX_TERMINALS,+ parseResumeSessions,+ sharePlan,+ type BootstrapResult,+ type ResumeResultEntry,+ type ResumeStatus,+ type ShareProbe,+ type ShareReply,+ type ShareTeamApi+} from '../../shared/share-team'+import type { SshConnection } from '../../shared/ssh'+import type { RelayBookmark } from '../remote/relay-bookmarks'++/** ssh timeouts per verb. `bootstrap` and `resume` outlast the server's own admin timeouts behind+ * them (45 s and 60 s) plus the CLI's start-up, so a slow but healthy server answers before ssh+ * gives up; the probe outlasts its own bounded `team status`. */+export const SHARE_TIMEOUTS = { probe: 30_000, bootstrap: 60_000, kill: 30_000, resume: 75_000 } as const+/** The installer clones and builds nodeterm-server on the host; a slow machine takes many minutes. */+export const SHARE_INSTALL_TIMEOUT_MS = 30 * 60_000++export interface ShareTeamDeps {+ /** The project's live connection, or undefined when it is not connected. */+ ref(projectId: string): { conn: SshConnection; controlPath: string; remoteCwd?: string } | undefined+ /** One buffered ssh child over the master: full child args, optional stdin, a hard timeout. */+ run(args: string[], stdin: string | undefined, timeoutMs: number): Promise<{ code: number; stdout: string }>+ /** Stream a script on the host (the installer). Never rejects; a failure is a non-zero exit. */+ runInstall(projectId: string, script: string, onChunk: (text: string) => void, signal: AbortSignal): Promise<{ exitCode: number }>+ /** Push every pending throttled project.json mirror write to its host now. */+ flushMirror(): Promise<void>+ /** Read the project's `.nodeterm/project.json` on its host (a checked read). */+ readRemoteProject(projectId: string): Promise<RemoteReadResult>+ /** This desktop's relay public key (standard base64): the key the team makes its owner. */+ ownerKey(): Promise<string>+ /** A human name for this desktop in the team's member list (cleaned here before use). */+ ownerLabel(): string+ bookmarks: {+ list(): Promise<RelayBookmark[]>+ upsert(b: RelayBookmark): Promise<void>+ update(hostId: string, patch: Partial<Pick<RelayBookmark, 'deviceToken' | 'approvedAt'>>): Promise<void>+ }+ now(): number+}++export interface ShareTeamHandlers extends Omit<ShareTeamApi, 'onInstallOutput' | 'install'> {+ install(projectId: string, onChunk: (text: string) => void): Promise<ShareReply<{ exitCode: number }>>+}++type ShareFail = { ok: false; error: string; code?: string }++const NOT_CONNECTED = {+ ok: false,+ code: 'E_NOT_CONNECTED',+ error: 'The project is not connected. Connect it and try again.'+} as const+const NOT_PROBED = {+ ok: false,+ code: 'E_NOT_PROBED',+ error: 'Check the host first (the probe did not run or found no usable server).'+} as const+const PROBE_SSH_FAILED = 'Could not run the check on the host (ssh failed).'+const TEAM_SSH_FAILED = 'Could not run the team command on the host (ssh failed).'+const KILL_SSH_FAILED = 'Could not stop the sessions on the host (ssh failed).'+const PROJECT_UNREADABLE = 'The project file on the host is not readable.'+const PROJECT_READ_FAILED = 'Could not read the project file on the host.'+const BAD_JOIN_CODE = 'The server sent an invalid join code.'+const BAD_BOOTSTRAP = 'The server answered bootstrap with a result this build cannot read.'+const BAD_RESUME = 'The server answered resume with a result this build cannot read.'++/** The most of a server-sent sentence shown to the user. */+const SHOWN_MAX = 500+const CONTROL_G = new RegExp(CONTROL_RE.source, 'gu')+const QUOTE_OR_BACKSLASH_G = /['\\]/g+const RESUME_STATUSES: ReadonlySet<string> = new Set<ResumeStatus>(['resumed', 'already-running', 'refused'])++const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)+const fail = (error: string, code?: string): ShareFail => ({ ok: false, error, ...(code ? { code } : {}) })+/** A server-sent sentence, made safe to print: controls (and text-direction overrides) blanked, bounded. */+const shown = (text: string): string => text.replace(CONTROL_G, ' ').slice(0, SHOWN_MAX)++/** A thrown error as a reply. A coded error (a locked keyring, a refused value) keeps its code. */+function caught(e: unknown): ShareFail {+ const message = e instanceof Error ? e.message : String(e)+ return fail(message || 'Something went wrong.', adminErrorCode(e))+}++/**+ * The owner label as bootstrap can take it. Controls are stripped, and so are `'` and `\`: the+ * label rides a generated `sh -c '…'` line that every login shell (fish included) must parse, and+ * those two cannot be nested there. Then it is capped at the team's label limit (never splitting a+ * surrogate pair) and, should the server's own check still object, left out.+ */+function ownerLabelFor(raw: string): string {+ let label = raw.replace(CONTROL_G, '').replace(QUOTE_OR_BACKSLASH_G, '').slice(0, TEAM_LABEL_MAX)+ if (/[\uD800-\uDBFF]$/.test(label)) label = label.slice(0, -1)+ return ownerLabelProblem(label) ? '' : label+}++/** A `--name value` flag pair, or `--name=value` when the value itself starts with `--` (the team+ * CLI would otherwise read it as a missing value). */+const flag = (name: string, value: string): string[] => (value.startsWith('--') ? [`--${name}=${value}`] : [`--${name}`, value])++/** The server's own refusal (`{ ok: false, error, code? }`), passed through. Only a code of the+ * admin shape survives: the renderer branches on it, so it must be one the server can mean. */+function refusal(body: unknown): ShareFail | null {+ if (!isRecord(body) || body.ok !== false) return null+ const error = typeof body.error === 'string' && body.error.trim() ? shown(body.error) : 'The host refused the request.'+ const code = typeof body.code === 'string' && ADMIN_ERROR_CODE_RE.test(body.code) ? body.code : undefined+ return fail(error, code)+}++/** `team bootstrap --json`'s success, strictly: only the known fields, each of its kind. */+function bootstrapResult(body: unknown): BootstrapResult | null {+ if (!isRecord(body)) return null+ const { hostId, projectId, projectName, joinCode, hosting, created } = body+ if (typeof hostId !== 'string' || typeof projectId !== 'string' || typeof projectName !== 'string' || typeof joinCode !== 'string') {+ return null+ }+ if (hosting !== 'up' && hosting !== 'starting') return null+ if (!isRecord(created)) return null+ const { team, owner, project, share } = created+ if (typeof team !== 'boolean' || typeof owner !== 'boolean' || typeof project !== 'boolean' || typeof share !== 'boolean') {+ return null+ }+ if (projectIdProblem(projectId) !== null) return null+ return { hostId, projectId, projectName: shown(projectName), joinCode, hosting, created: { team, owner, project, share } }+}++/** `team resume --json`'s results, strictly: one entry per session at most, each of a known status. */+function resumeResults(body: unknown): ResumeResultEntry[] | null {+ if (!isRecord(body) || !Array.isArray(body.results) || body.results.length > RESUME_MAX_SESSIONS) return null+ const out: ResumeResultEntry[] = []+ for (const e of body.results as unknown[]) {+ if (!isRecord(e) || typeof e.nodeId !== 'string' || typeof e.status !== 'string' || !RESUME_STATUSES.has(e.status)) {+ return null+ }+ if (e.reason !== undefined && typeof e.reason !== 'string') return null+ out.push({+ nodeId: e.nodeId,+ status: e.status as ResumeStatus,+ ...(typeof e.reason === 'string' ? { reason: shown(e.reason) } : {})+ })+ }+ return out+}++export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlers {+ const probes = new Map<string, ShareProbe>()+ const installs = new Map<string, AbortController>()++ /** The cached probe, when it found a server that can run `team bootstrap`. */+ const readyProbe = (projectId: string): ShareProbe | undefined => {+ const p = probes.get(projectId)+ return p && p.hasBootstrap && p.node && p.main ? p : undefined+ }++ return {+ async probe(projectId, nodeIds) {+ try {+ const ref = deps.ref(projectId)+ if (!ref) return NOT_CONNECTED+ // A probe that fails must not leave an older one behind for bootstrap to run against.+ probes.delete(projectId)+ const command = shareProbeCommand(ref.remoteCwd ?? '~')+ const r = await deps.run(childArgs(ref.conn, ref.controlPath, command), undefined, SHARE_TIMEOUTS.probe)+ if (r.code !== 0) return fail(PROBE_SSH_FAILED)+ const probe = parseShareProbe(r.stdout)+ if ('error' in probe) return fail(probe.error)+ probes.set(projectId, probe)+ return {+ ok: true,+ probe,+ plan: sharePlan(probe),+ paneCommands: paneCommandsByNode(probe.panes, nodeIds.filter((id) => isSafeNodeId(id)))+ }+ } catch (e) {+ return caught(e)+ }+ },++ // Probe-cache invalidation is not this verb's job: the renderer probes again after an install,+ // and that probe replaces the cached one.+ async install(projectId, onChunk) {+ try {+ if (!deps.ref(projectId)) return NOT_CONNECTED+ if (installs.has(projectId)) return fail('An install is already running.')+ const ctrl = new AbortController()+ installs.set(projectId, ctrl)+ // Output reaches the renderer over IPC, and a send to a disposed frame throws; that must not+ // escape into the runner's stream callbacks.+ const chunk = (text: string): void => {+ try {+ onChunk(text)+ } catch {+ // The window is gone; the run itself carries on and still reports its exit code.+ }+ }+ try {+ const { exitCode } = await deps.runInstall(projectId, SHARE_INSTALL_SCRIPT, chunk, ctrl.signal)+ return { ok: true, exitCode }+ } finally {+ installs.delete(projectId)+ }+ } catch (e) {+ return caught(e)+ }+ },++ async cancelInstall(projectId) {+ installs.get(projectId)?.abort()+ },++ async flushMirror(projectId) {+ try {+ if (!deps.ref(projectId)) return NOT_CONNECTED+ // Flush first: a throttled mirror write still pending would leave nodes out of the read.+ await deps.flushMirror()+ const read = await deps.readRemoteProject(projectId)+ if (read.status === 'absent') return { ok: true, nodeIds: [] }+ if (read.status === 'error') return fail(PROJECT_READ_FAILED)+ let parsed: unknown+ try {+ parsed = JSON.parse(read.content)+ } catch {+ return fail(PROJECT_UNREADABLE)+ }+ if (!isRecord(parsed) || !Array.isArray(parsed.nodes)) return fail(PROJECT_UNREADABLE)+ const nodeIds = (parsed.nodes as unknown[]).flatMap((n) => (isRecord(n) && typeof n.id === 'string' ? [n.id] : []))+ return { ok: true, nodeIds }+ } catch (e) {+ return caught(e)+ }+ },++ async bootstrap(projectId, adoptCwd) {+ try {+ const ref = deps.ref(projectId)+ if (!ref) return NOT_CONNECTED+ const probe = readyProbe(projectId)+ if (!probe) return NOT_PROBED+ const label = ownerLabelFor(deps.ownerLabel())+ const args = [+ 'bootstrap',+ ...flag('owner-key', await deps.ownerKey()),+ ...(label ? flag('owner-label', label) : []),+ ...flag('adopt', adoptCwd),+ '--json'+ ]+ const r = await deps.run(childArgs(ref.conn, ref.controlPath, teamCliCommand(probe, args)), undefined, SHARE_TIMEOUTS.bootstrap)+ if (r.code !== 0) return fail(TEAM_SSH_FAILED)+ const out = parseTeamCliOutput(r.stdout)+ if ('error' in out) return fail(out.error)+ const refused = refusal(out.body)+ if (refused) return refused+ const result = bootstrapResult(out.body)+ if (!result) return fail(BAD_BOOTSTRAP)+ const code = decodeJoinCode(result.joinCode)+ if (!code || code.hostId !== result.hostId) return fail(BAD_JOIN_CODE)+ return { ok: true, result }+ } catch (e) {+ return caught(e)+ }+ },++ async killSessions(projectId, nodeIds) {+ try {+ const ref = deps.ref(projectId)+ if (!ref) return NOT_CONNECTED+ if (nodeIds.length > SHARE_MAX_TERMINALS) {+ return fail(`A share stops at most ${SHARE_MAX_TERMINALS} terminal sessions.`)+ }+ if (!nodeIds.every((id) => isSafeNodeId(id))) {+ return fail('A terminal node id is not a safe id (letters, digits, ".", "_" and "-" only).')+ }+ if (nodeIds.length === 0) return { ok: true, results: [] }+ const command = killVerifyCommand(nodeIds)+ const r = await deps.run(childArgs(ref.conn, ref.controlPath, command), undefined, SHARE_TIMEOUTS.kill)+ if (r.code !== 0) return fail(KILL_SSH_FAILED)+ const results = parseKillVerify(r.stdout, nodeIds)+ if ('error' in results) return fail(results.error)+ return { ok: true, results }+ } catch (e) {+ return caught(e)+ }+ },++ async resume(projectId, serverProjectId, sessions) {+ try {+ const ref = deps.ref(projectId)+ if (!ref) return NOT_CONNECTED+ const probe = readyProbe(projectId)+ if (!probe) return NOT_PROBED+ const idProblem = projectIdProblem(serverProjectId)+ if (idProblem) return fail(idProblem)+ const list = parseResumeSessions(sessions)+ if (typeof list === 'string') return fail(list)+ // The session list travels on stdin, never argv: it is long, and argv shows up in `ps`.+ const command = teamCliCommand(probe, ['resume', ...flag('project', serverProjectId), '--json'])+ const r = await deps.run(childArgs(ref.conn, ref.controlPath, command), JSON.stringify(list), SHARE_TIMEOUTS.resume)+ if (r.code !== 0) return fail(TEAM_SSH_FAILED)+ const out = parseTeamCliOutput(r.stdout)+ if ('error' in out) return fail(out.error)+ const refused = refusal(out.body)+ if (refused) return refused+ const results = resumeResults(out.body)+ if (!results) return fail(BAD_RESUME)+ return { ok: true, results }+ } catch (e) {+ return caught(e)+ }+ },++ async seedBookmark(joinCode) {+ try {+ const code = decodeJoinCode(joinCode)+ if (!code) return fail('That is not a valid team invite code.')+ const at = new Date(deps.now()).toISOString()+ // The ONE join that skips the SAS: this code arrived over the project's own ssh channel,+ // whose host key known_hosts authenticated, and it names the relay key it was minted for —+ // the same assurance a human comparing six digits gives. Any pasted code still compares the+ // SAS.+ const existing = (await deps.bookmarks.list()).find((b) => b.hostId === code.hostId)+ if (existing && decodeJoinCode(existing.code)?.hostPublicKeyB64 === code.hostPublicKeyB64) {+ // Same team, same key: keep its device token; approve it if it never was.+ if (!existing.approvedAt) await deps.bookmarks.update(code.hostId, { approvedAt: at })+ } else {+ // New, or the stored bookmark names another key: its token and approval belong to that+ // key, so they are not carried over.+ await deps.bookmarks.upsert({+ hostId: code.hostId,+ code: encodeJoinCode(code),+ label: code.label,+ deviceToken: null,+ approvedAt: at,+ source: 'ssh'+ })+ }+ return { ok: true, hostId: code.hostId, label: code.label }+ } catch (e) {+ return caught(e)+ }+ }+ }+}diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 3d99b1278..028cdbbea 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -110,8 +110,10 @@ interface Runners {* master rather than guessed from a global timestamp. */pid?: () => number | undefined}- /** Run a one-shot ssh, resolving its stdout + exit code; optional stdin written to the child. */- run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>+ /** Run a one-shot ssh, resolving its stdout + exit code; optional stdin written to the child.+ * `timeoutMs` (default 15 s) bounds the child; only a caller whose remote command legitimately+ * runs longer passes more (Share with team's verbs, up to 75 s for resume). */+ run: (args: string[], stdin?: string, timeoutMs?: number) => Promise<{ code: number; stdout: string }>/** Run a one-shot ssh with a hard timeout, OUTSIDE the per-master child gate, and say only* whether it finished in time. Used by the wake-from-sleep liveness probe: after a sleep the* gate is often full of children hung on the dead master, and a probe queued behind them would@@ -1524,8 +1526,8 @@ export class SshProjectManager {* search read over the SAME ControlMaster. `args` are full ssh child args (e.g. from* `childArgs(conn, controlPath, cmd)`); returns `{ code, stdout }`.*/- sshRun(args: string[], stdin?: string): Promise<{ code: number; stdout: string }> {- return this.r.run(args, stdin)+ sshRun(args: string[], stdin?: string, opts?: { timeoutMs?: number }): Promise<{ code: number; stdout: string }> {+ return this.r.run(args, stdin, opts?.timeoutMs)}/**@@ -2879,12 +2881,12 @@ export function initSshProject(// `MaxSessions` every excess child silently becomes a full login — enough of those at once// and sshd's `MaxStartups` resets some outright, which the app sees as a dropped terminal.// Mux control commands and the terminals themselves are never queued (see ssh-child-gate.ts).- run: (args, stdin) =>+ run: (args, stdin, timeoutMs) =>sshChildGate.run(args, () =>native? // Still gated: sshd's MaxSessions bounds channels on ONE connection just as it bounds// mux clients on a ControlMaster.- runSshArgv(nativeMux(), args, { stdin, timeoutMs: 15000 }).then((r) => ({+ runSshArgv(nativeMux(), args, { stdin, timeoutMs: timeoutMs ?? 15000 }).then((r) => ({code: r.timedOut ? 1 : (r.code ?? 1),stdout: r.stdout.toString('utf-8')}))@@ -2900,7 +2902,7 @@ export function initSshProject(const child = execFile(ssh,args,- { timeout: 15000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ...appSshAgent.env() } },+ { timeout: timeoutMs ?? 15000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ...appSshAgent.env() } },(err, stdout) =>resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: stdout ?? '' }))diff --git a/src/preload/index.ts b/src/preload/index.tsindex a06629180..3ddc71f36 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -319,6 +319,24 @@ const api: NodeTerminalApi = {return () => ipcRenderer.removeListener(IPC.sshPassphraseDismiss, h)}},+ shareTeam: {+ probe: (projectId, nodeIds) => ipcRenderer.invoke(IPC.shareTeamProbe, projectId, nodeIds),+ install: (projectId) => ipcRenderer.invoke(IPC.shareTeamInstall, projectId),+ cancelInstall: (projectId) => ipcRenderer.invoke(IPC.shareTeamCancelInstall, projectId),+ onInstallOutput: (projectId, listener) => {+ const h = (_e: unknown, p: { projectId?: unknown; text?: unknown }) => {+ if (p?.projectId === projectId && typeof p.text === 'string') listener(p.text)+ }+ ipcRenderer.on(IPC.shareTeamInstallOutput, h)+ return () => ipcRenderer.removeListener(IPC.shareTeamInstallOutput, h)+ },+ flushMirror: (projectId) => ipcRenderer.invoke(IPC.shareTeamFlushMirror, projectId),+ bootstrap: (projectId, adoptCwd) => ipcRenderer.invoke(IPC.shareTeamBootstrap, projectId, adoptCwd),+ killSessions: (projectId, nodeIds) => ipcRenderer.invoke(IPC.shareTeamKillSessions, projectId, nodeIds),+ resume: (projectId, serverProjectId, sessions) =>+ ipcRenderer.invoke(IPC.shareTeamResume, projectId, serverProjectId, sessions),+ seedBookmark: (joinCode) => ipcRenderer.invoke(IPC.shareTeamSeedBookmark, joinCode)+ },sshFs: {list: (projectId: string, path: string) => ipcRenderer.invoke(IPC.sshFsList, projectId, path),read: (projectId: string, path: string) => ipcRenderer.invoke(IPC.sshFsRead, projectId, path),diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.tsindex 68e9c0dac..1cdea361d 100644--- a/src/renderer/bridge/relay-api.test.ts+++ b/src/renderer/bridge/relay-api.test.ts@@ -1,6 +1,7 @@import { relayPtyDataKey } from '../../shared/relay-pty-channel'import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { IPC } from '../../shared/ipc'+import { E_UNSUPPORTED } from '../../shared/rpc'import type { NodeTerminalApi } from '../../shared/types'import type { FrameTransport } from './frame-transport'import { buildRelayApi } from './relay-api'@@ -172,6 +173,19 @@ describe('buildRelayApi', () => {expect(t.sent).toEqual([]) // nothing crossed the relay})+ it('share with team: a relay tab takes the E_UNSUPPORTED stub, never the LOCAL preload member', async () => {+ const { local } = fakeLocalApi()+ const localShareTeam = { probe: vi.fn() }+ ;(local as unknown as { shareTeam: unknown }).shareTeam = localShareTeam+ ;(globalThis as Record<string, unknown>).window = { nodeTerminal: local }+ const t = new FakeTransport()+ const { api } = buildRelayApi('conn-1', t)+ expect(api.shareTeam).not.toBe(localShareTeam)+ await expect(api.shareTeam.probe('p', [])).rejects.toMatchObject({ code: E_UNSUPPORTED })+ expect(localShareTeam.probe).not.toHaveBeenCalled()+ expect(t.sent).toEqual([])+ })+it('produces a value that satisfies NodeTerminalApi', () => {const { local } = fakeLocalApi();(globalThis as Record<string, unknown>).window = { nodeTerminal: local }diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex 35440842a..2f50f7fa6 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -206,6 +206,10 @@ export function buildRelayApi(// the inert stub (create answers `unsupported`). Never the local preload's real member, which// `...local` would otherwise hand it: that would offer to publish a node id this core does not run.watchLink: stub.watchLink,+ // Share with team drives THIS machine's ssh for one of THIS machine's SSH projects; a relay+ // tab's projects are the host's, so `...local` would aim a host project id at the local ssh+ // manager. The stub answers E_UNSUPPORTED instead.+ shareTeam: stub.shareTeam,// The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's// core, whose mirror is seeded by the host's own renderer from its own localStorage. This// machine's localStorage holds no identity for them, and `...local` would plant this machine'sdiff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex dd6cfa8b8..e71a45ebc 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -16,6 +16,7 @@ describe('bridge stubs', () => {s.browser.onBrowserNewWindow(() => {}),s.onAgentControl(() => {}),s.sshProject.onStatus(() => {}),+ s.shareTeam.onInstallOutput('p', () => {}),s.usage.onUpdate(() => {}),s.updates.onAvailable(() => {}),s.updates.onProgress(() => {}),@@ -59,6 +60,18 @@ describe('bridge stubs', () => {}).not.toThrow()})+ it('share with team is desktop-only: every verb answers E_UNSUPPORTED', async () => {+ const s = buildStubApi()+ await expect(s.shareTeam.probe('p', [])).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.install('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.cancelInstall('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.flushMirror('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.bootstrap('p', '/x')).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.killSessions('p', [])).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.resume('p', 'project-1', [])).rejects.toMatchObject({ code: E_UNSUPPORTED })+ await expect(s.shareTeam.seedBookmark('code')).rejects.toMatchObject({ code: E_UNSUPPORTED })+ })+it('hosted-team bookmarks answer an empty list: a browser cannot join a relay host', async () => {const s = buildStubApi()await expect(s.relayHosted.bookmarks()).resolves.toEqual([])diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex db4414503..1dbb52a6e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -165,6 +165,19 @@ export function buildStubApi(): Omit<onPassphraseRequest: noopUnsub,onPassphraseDismiss: noopUnsub},+ // Desktop only: the Server Edition has no SSH projects, and a relay tab must never drive the+ // host's ssh (relay-api.ts takes this stub rather than the local preload's member).+ shareTeam: {+ probe: U('shareTeam.probe'),+ install: U('shareTeam.install'),+ cancelInstall: U('shareTeam.cancelInstall'),+ onInstallOutput: noopUnsub,+ flushMirror: U('shareTeam.flushMirror'),+ bootstrap: U('shareTeam.bootstrap'),+ killSessions: U('shareTeam.killSessions'),+ resume: U('shareTeam.resume'),+ seedBookmark: U('shareTeam.seedBookmark')+ },sshFs: {list: U('sshFs.list'),read: U('sshFs.read'),diff --git a/src/shared/ipc.test.ts b/src/shared/ipc.test.tsindex 636d7c88a..dd807ddee 100644--- a/src/shared/ipc.test.ts+++ b/src/shared/ipc.test.ts@@ -53,4 +53,28 @@ describe('IPC channels', () => {expect(IPC.relayHostedBookmarks).toBe('relay:hosted:bookmarks')expect(IPC.relayHostedBookmarkRemove).toBe('relay:hosted:bookmark-remove')})++ it('exposes the desktop-local share-team channels', () => {+ expect([+ IPC.shareTeamProbe,+ IPC.shareTeamInstall,+ IPC.shareTeamCancelInstall,+ IPC.shareTeamInstallOutput,+ IPC.shareTeamFlushMirror,+ IPC.shareTeamBootstrap,+ IPC.shareTeamKillSessions,+ IPC.shareTeamResume,+ IPC.shareTeamSeedBookmark+ ]).toEqual([+ 'share-team:probe',+ 'share-team:install',+ 'share-team:cancel-install',+ 'share-team:install-output',+ 'share-team:flush-mirror',+ 'share-team:bootstrap',+ 'share-team:kill-sessions',+ 'share-team:resume',+ 'share-team:seed-bookmark'+ ])+ })})diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 754d22c3e..e59e2f127 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -704,6 +704,19 @@ export const IPC = {// their device tokens; `relayHostedBookmarkRemove` (hostId) forgets one.relayHostedBookmarks: 'relay:hosted:bookmarks',relayHostedBookmarkRemove: 'relay:hosted:bookmark-remove',+ // "Share with team" for an SSH project (src/main/remote-ssh/share-team.ts): each verb runs one+ // generated command over the project's ControlMaster. These are raw `ipcMain` handlers, never on+ // the platform, so a relay peer can never reach them. `shareTeamInstallOutput` is main → renderer,+ // payload `{ projectId, text }`.+ shareTeamProbe: 'share-team:probe',+ shareTeamInstall: 'share-team:install',+ shareTeamCancelInstall: 'share-team:cancel-install',+ shareTeamInstallOutput: 'share-team:install-output',+ shareTeamFlushMirror: 'share-team:flush-mirror',+ shareTeamBootstrap: 'share-team:bootstrap',+ shareTeamKillSessions: 'share-team:kill-sessions',+ shareTeamResume: 'share-team:resume',+ shareTeamSeedBookmark: 'share-team:seed-bookmark',handoffBuild: 'handoff:build',// Phone pairing (nodeterm iOS "scan a QR" flow): renderer starts/stops the one-shot LAN// listener; main pushes the completion result back over `pairing:done`. The per-devicediff --git a/src/shared/share-team.ts b/src/shared/share-team.tsindex e53aec1d2..34c8fd731 100644--- a/src/shared/share-team.ts+++ b/src/shared/share-team.ts@@ -134,3 +134,32 @@ export function sharePlan(p: ShareProbe): SharePlan {}return { kind: 'install', reason }}++/** Every `shareTeam` answer: never a rejection across IPC. `code` is an `E_*` code when the+ * failure has one the renderer branches on (`E_NOT_CONNECTED`, `E_NOT_PROBED`, a server refusal). */+export type ShareReply<T> = ({ ok: true } & T) | { ok: false; error: string; code?: string }++/** The probe, the plan it implies, and the command each requested node's pane is running on the+ * host's remote tmux socket (a node with no live pane is absent). */+export interface ShareProbeReply {+ probe: ShareProbe+ plan: SharePlan+ paneCommands: Record<string, string>+}++/** The desktop's "Share with team" verbs for an SSH project (`window.nodeTerminal.shareTeam`).+ * Desktop only: the Server Edition and relay tabs answer `E_UNSUPPORTED`. */+export interface ShareTeamApi {+ probe(projectId: string, nodeIds: string[]): Promise<ShareReply<ShareProbeReply>>+ install(projectId: string): Promise<ShareReply<{ exitCode: number }>>+ cancelInstall(projectId: string): Promise<void>+ onInstallOutput(projectId: string, listener: (text: string) => void): () => void+ flushMirror(projectId: string): Promise<ShareReply<{ nodeIds: string[] }>>+ bootstrap(projectId: string, adoptCwd: string): Promise<ShareReply<{ result: BootstrapResult }>>+ killSessions(+ projectId: string,+ nodeIds: string[]+ ): Promise<ShareReply<{ results: Array<{ nodeId: string; state: 'gone' | 'alive' | 'unknown' }> }>>+ resume(projectId: string, serverProjectId: string, sessions: ResumeEntry[]): Promise<ShareReply<ResumeResult>>+ seedBookmark(joinCode: string): Promise<ShareReply<{ hostId: string; label: string }>>+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex c8bd25c1a..6d474cfb7 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -30,6 +30,7 @@ import type { NotchAlign } from './notch-hud'import type { ProjectIcon, ProjectIconPickResult } from './project-icon'import type { AlertSoundKind, AlertSoundSaveResult, CustomAlertSounds } from './alert-sound'import type { CanvasLayout, LayoutViewports } from './canvas-layout'+import type { ShareTeamApi } from './share-team'import type {ModelDiscoveryResult,ModelGatewayCredentialStatus,@@ -4200,6 +4201,9 @@ export interface NodeTerminalApi {relayHost: RelayHostApirelayClient: RelayClientApirelayHosted: RelayHostedApi+ /** "Share with team" for an SSH project. Desktop only (the Server Edition and relay tabs answer+ * `E_UNSUPPORTED`). */+ shareTeam: ShareTeamApi/** The hosted team verbs of THIS session's host — present only on a relay tab joined by a hosted* team's join code; absent everywhere else (local, Server Edition, Team Access relay tabs). */hosted?: HostedSessionApi