The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Batch H: #2025 #2049 #1973 #2057 (#2058)
0xken1550bcac3ad188
diff --git a/backend/integration/harnessSharesList.test.ts b/backend/integration/harnessSharesList.test.tsnew file mode 100644index 000000000..d482372df--- /dev/null+++ b/backend/integration/harnessSharesList.test.ts@@ -0,0 +1,362 @@+import { randomUUID } from 'node:crypto'+import { performance } from 'node:perf_hooks'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import type { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import type { Command } from '../src/superTabs/commands.js'+import { localDatabase, type LocalDatabase } from './bench/mongo.js'+import { DEFAULT_CONFIG } from './bench/config.js'+import { DRIVERS } from './bench/bench.js'+import { machineId, seedAccounts } from './bench/fixtures.js'+import { plan } from './bench/plan.js'+import { seedSwarm, AGENT_CONFIGURATION, type Swarm } from './bench/seed.js'+import { poolRows } from './hostRows.test-support.js'++// The harness shares list (routes/harnessShares.ts) against a Swarm-sized database. Prod 2026-10-28: CLI daemons' list calls+// took half the backend's busy time in spike minutes (p95 13.4 s), each share loading its whole Swarm to check it. Every+// permission read here is real; Redis is replaced by "every machine is running".+const shared = vi.hoisted(() => ({ db: null as unknown as PrismaClient }))+vi.mock('../src/lib/prisma.js', async original => ({ ...await original<typeof import('../src/lib/prisma.js')>(), get prisma() { return shared.db } }))+vi.mock('../src/lib/bus.js', async original => ({ ...await original<typeof import('../src/lib/bus.js')>(),+ getAgentPresenceMany: async (ids: string[]) => new Map(ids.map(id => [id, 'running'])) }))+const { harnessShareRoutes } = await import('../src/routes/harnessShares.js')+const { SuperTabStore } = await import('../src/superTabs/store.js')++/** The Swarm the benchmark runs on, with 40 workers over 6 machines, most of them shared with the recipient. */+const CONFIG = { ...structuredClone(DEFAULT_CONFIG), groups: 200, doneShare: 0.8, workers: 40 }+const RUNS = 30, WAVE = 20++let database: LocalDatabase+let app: FastifyInstance+let swarm: Swarm+let recipient: AuthUser+/** Who the next list call is made as. */+let viewer: AuthUser+/** The shares the recipient must be listed, by hand: each worker not on its own machine, the Swarm's Lead, and the ordinary share. */+let expected: string[]+/** Every share addressed to the recipient that the list must leave out, by why. */+let hidden: Record<string, string>++const list = async (as: AuthUser = recipient) => {+ viewer = as+ const res = await app.inject({ method: 'GET', url: '/api/harness-shares' })+ expect(res.statusCode).toBe(200)+ return (res.json().data.machines as Array<{ machineId: string; shares: Array<{ id: string }> }>)+}+const listedIds = (machines: Awaited<ReturnType<typeof list>>) => machines.flatMap(m => m.shares.map(s => s.id)).sort()+const percentile = (values: number[], p: number) => [...values].sort((a, b) => a - b)[Math.min(values.length - 1, Math.floor(values.length * p))]!++interface Profiled { collection: string; plans: string[]; keysExamined: number; docsExamined: number; returned: number }+/** What Mongo did for each collection while `read` ran: plans, documents examined and rows returned. */+async function profiled(read: () => Promise<unknown>): Promise<Profiled[]> {+ const db = database.db+ await db.$runCommandRaw({ profile: 2 })+ await read()+ await db.$runCommandRaw({ profile: 0 })+ const found = await db.$runCommandRaw({ find: 'system.profile', filter: { 'command.profile': { $exists: false } }, batchSize: 10000 }) as+ unknown as { cursor: { firstBatch: Array<{ ns: string; planSummary?: string; keysExamined?: number; docsExamined?: number; nreturned?: number }> } }+ await db.$runCommandRaw({ drop: 'system.profile' })+ const byCollection = new Map<string, Profiled>()+ for (const row of found.cursor.firstBatch) {+ const collection = row.ns.slice(row.ns.indexOf('.') + 1)+ if (collection.startsWith('system.') || collection.startsWith('$cmd')) continue+ const entry = byCollection.get(collection) ?? { collection, plans: [], keysExamined: 0, docsExamined: 0, returned: 0 }+ if (row.planSummary && !entry.plans.includes(row.planSummary)) entry.plans.push(row.planSummary)+ entry.keysExamined += row.keysExamined ?? 0+ entry.docsExamined += row.docsExamined ?? 0+ entry.returned += row.nreturned ?? 0+ byCollection.set(collection, entry)+ }+ return [...byCollection.values()]+}++beforeAll(async () => {+ database = await localDatabase()+ const db = shared.db = database.db+ const people = await seedAccounts(db, CONFIG.machines)+ const driver = await DRIVERS.parts!(db, () => people)+ swarm = (await seedSwarm(driver, CONFIG, plan(CONFIG), people)).swarm+ await driver.close()+ recipient = people[1]!+ const share = (id: string, data: { superTabId: string | null; owner: number; agentId: string; recipientEmail?: string; expiresAt?: Date; revokedAt?: Date }) =>+ db.harnessShare.create({ data: { id, superTabId: data.superTabId, ownerId: people[data.owner]!.sub, machineId: machineId(data.owner),+ agentId: data.agentId, recipientEmail: data.recipientEmail ?? recipient.email, autonomousEnv: 'prod', name: data.agentId,+ ownerPublicKey: 'fixture-key', expiresAt: data.expiresAt ?? new Date(Date.now() + 86_400_000), revokedAt: data.revokedAt ?? null } })+ expected = []+ for (const worker of swarm.workers) {+ if (worker.machine === 1) continue+ const id = randomUUID()+ await share(id, { superTabId: swarm.tabId, owner: worker.machine, agentId: worker.harnessId })+ expected.push(id)+ }+ const plain = randomUUID()+ await share(plain, { superTabId: null, owner: 2, agentId: 'plain-harness' })+ expected.push(plain)+ // The Swarm's current Lead is open to its readers (projects.ts watchClosed); confidential, it is closed everywhere else.+ const lead = randomUUID()+ await share(lead, { superTabId: swarm.tabId, owner: 0, agentId: 'bench-lead' })+ expected.push(lead)+ expected.sort()+ // A Swarm the recipient is not in, with one agent shared through it, and its Lead, shared outside any Swarm.+ const store = new SuperTabStore(db)+ const other = (await store.create(people[0]!, randomUUID(), 'Elsewhere')).id+ await store.execute(people[0]!, other, { operationId: randomUUID(), command: { type: 'machine.contribute', machineId: machineId(0), name: 'Bench machine 0',+ cwd: '/bench/repo', engines: ['codex'], maxAgents: 4 } })+ await store.execute(people[0]!, other, { operationId: randomUUID(), command: { type: 'agent.add', conversationId: 'lead', machineId: machineId(0),+ harnessId: 'elsewhere-worker', name: 'Elsewhere', configuration: AGENT_CONFIGURATION, lead: false } })+ await store.execute(people[0]!, other, { operationId: randomUUID(), command: { type: 'agent.add', conversationId: 'lead', machineId: machineId(0),+ harnessId: 'elsewhere-lead', name: 'Lead', configuration: AGENT_CONFIGURATION, lead: true } })+ // Agents of 200 other Swarms, as production holds them: a read of these agents' keys must not walk theirs.+ const { id: _row, ...template } = await db.swarmAgent.findFirstOrThrow({ where: { tabId: swarm.tabId } })+ await db.swarmAgent.createMany({ data: Array.from({ length: 200 }, (_, i) => ({ ...template, id: `crowd-${i}`, tabId: `crowd-tab-${i}`,+ key: `crowd-agent-${i}`, data: template.data as object })) })+ hidden = {}+ const hide = async (why: string, data: Parameters<typeof share>[1]) => { const id = randomUUID(); hidden[id] = why; await share(id, data) }+ await hide('an ordinary share of a confidential session', { superTabId: null, owner: 0, agentId: 'elsewhere-lead' })+ await hide('a Swarm the recipient is not in', { superTabId: other, owner: 0, agentId: 'elsewhere-worker' })+ await hide('an agent not in the Swarm', { superTabId: swarm.tabId, owner: 2, agentId: 'gone-worker' })+ await hide('expired', { superTabId: null, owner: 3, agentId: 'expired-harness', expiresAt: new Date(Date.now() - 1000) })+ await hide('revoked', { superTabId: null, owner: 3, agentId: 'revoked-harness', revokedAt: new Date() })+ await share(randomUUID(), { superTabId: swarm.tabId, owner: 2, agentId: swarm.workers.find(w => w.machine === 2)!.harnessId, recipientEmail: '[email protected]' })+ app = Fastify()+ app.decorateRequest('user', null)+ app.addHook('onRequest', async req => { req.user = viewer })+ await app.register(harnessShareRoutes)+ await app.ready()+}, 300_000)+afterAll(async () => {+ await app?.close()+ await database?.stop()+})++describe('the harness shares list on a Swarm-sized database', () => {+ it('lists exactly the shares the recipient may open, as each share alone would answer', async () => {+ expect(listedIds(await list())).toEqual(expected)+ const store = new SuperTabStore(database.db)+ const all = await database.db.harnessShare.findMany({ where: { recipientEmail: recipient.email, revokedAt: null, expiresAt: { gt: new Date() } } })+ const alone = []+ for (const share of all) if (await store.mayOpenShare(recipient, share)) alone.push(share.id)+ expect(alone.sort()).toEqual(expected)+ for (const id of Object.keys(hidden)) expect(expected).not.toContain(id)+ })++ it('answers well under 200 ms at p95, alone and in a wave of daemons asking at once', async () => {+ await list()+ const alone: number[] = []+ for (let i = 0; i < RUNS; i++) {+ const started = performance.now()+ await list()+ alone.push(performance.now() - started)+ }+ const started = performance.now()+ await Promise.all(Array.from({ length: WAVE }, () => list()))+ const wave = performance.now() - started+ const numbers = { shares: expected.length + Object.keys(hidden).length, p50Ms: Math.round(percentile(alone, 0.5)), p95Ms: Math.round(percentile(alone, 0.95)),+ waveOf20Ms: Math.round(wave) }+ process.stdout.write(`harness shares list: ${JSON.stringify(numbers)}\n`)+ expect(numbers.p95Ms).toBeLessThan(100)+ expect(numbers.waveOf20Ms).toBeLessThan(1000)+ })++ it('reads every collection through an index, examining about as many documents as it returns', async () => {+ const reads = await profiled(list)+ process.stdout.write(`harness shares list reads: ${JSON.stringify(reads)}\n`)+ for (const read of reads) {+ expect(read.plans.filter(p => p.startsWith('COLLSCAN')), read.collection).toEqual([])+ // Prisma's `in` is planned as one index scan per value (an OR of N branches), each read planned anew: one $in scan instead.+ expect(read.plans.filter(p => p.includes('}, IXSCAN')), read.collection).toEqual([])+ expect(read.docsExamined, read.collection).toBeLessThanOrEqual(read.returned + 2)+ // Keys too: an agent read by key that walks the (tabId, key) index costs every other Swarm in production.+ expect(read.keysExamined, read.collection).toBeLessThanOrEqual(read.returned + 10)+ }+ })+})++/**+ * The list against each share asked alone (mayOpenShare), and against what each person must see by hand, as people and+ * permissions change under a warm read cache (review of #1973): a Lead and its private conversation, a session confidential+ * here or in another Swarm, a private project, a Lead's replacement, a removed member, and a machine grant taken back. Two members ask in turn, each after the other's change.+ */+describe('the harness shares list as permissions change', () => {+ const fixture = (n: number): AuthUser => ({ sub: (0x200000000000000000000001n + BigInt(n)).toString(16).padStart(24, '0'),+ email: `perm-${n}@example.com`, autonomousEnv: 'prod', role: 'user' })+ /** The Swarm's owner, who adds every agent; the host whose machine is shared with the owner; and two members. */+ const owner = fixture(0), host = fixture(1), a = fixture(2), b = fixture(3)+ let store: InstanceType<typeof SuperTabStore>+ let cases = 0++ beforeAll(async () => {+ const db = database.db+ store = new SuperTabStore(db)+ for (const user of [owner, host, a, b]) await db.user.create({ data: { id: user.sub, externalId: `perm-${user.sub}`, email: user.email, autonomousEnv: 'prod' } })+ for (const [machine, user] of [['grant-host', host], ['own-host', owner], ['a-mac', a]] as const) {+ await db.machine.create({ data: { machineId: machine, userId: user.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ }+ })++ /** A Swarm of the owner with both members, and three Builders shared with each member: X and Y on the host's machine+ * (the owner's through its grant), Z on the owner's own machine. */+ async function swarmWithShares() {+ const db = database.db, n = ++cases+ await db.machineShare.upsert({ where: { machineId: 'grant-host' }, create: { machineId: 'grant-host', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] },+ update: { emails: [owner.email] } })+ const tab = (await store.create(owner, randomUUID(), `Permissions ${n}`)).id+ const run = (command: Command, as = owner) => store.execute(as, tab, { operationId: randomUUID(), command })+ for (const person of [a, b]) {+ const invitation = await run({ type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })+ await run({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)+ }+ const agents: Record<string, string> = {}+ const shares: Record<string, { name: string; to: AuthUser }> = {}+ /** Adds agent `name` to `conversationId` on the host's machine through the owner's grant, and shares it with both members. */+ /** Shares session `harnessId` on `machine`, as `claimedOwner` names it, with both members, under agent name `name`. */+ const shareWithBoth = async (name: string, machine: string, harnessId: string, claimedOwner: AuthUser) => {+ for (const to of [a, b]) {+ const id = randomUUID()+ shares[id] = { name, to }+ await db.harnessShare.create({ data: { id, superTabId: tab, ownerId: claimedOwner.sub, machineId: machine, agentId: harnessId,+ recipientEmail: to.email, autonomousEnv: 'prod', name, ownerPublicKey: 'fixture-key', expiresAt: new Date(Date.now() + 86_400_000), revokedAt: null } })+ }+ }+ const shared = async (name: string, conversationId = 'lead', lead = false, [machine, machineOwner] = ['grant-host', host] as const,+ claimedOwner: AuthUser = machineOwner) => {+ const harnessId = `perm-${n}-${name}`+ agents[name] = (await run({ type: 'agent.add', conversationId, machineId: machine, harnessId, name: `Builder ${name}`,+ configuration: AGENT_CONFIGURATION, lead })).result.agentId as string+ await shareWithBoth(name, machine, harnessId, claimedOwner)+ }+ await shared('X')+ await shared('Y')+ await shared('Z', 'lead', false, ['own-host', owner])+ /** What `as` is listed of this Swarm, by agent name; first checked against each share asked alone. */+ const sees = async (as: AuthUser) => {+ const listed = new Set(listedIds(await list(as)))+ const mine = Object.keys(shares).filter(id => shares[id]!.to === as)+ const rows = await db.harnessShare.findMany({ where: { id: { in: mine } } })+ const alone = new Set<string>()+ for (const share of rows) if (await store.mayOpenShare(as, share)) alone.add(share.id)+ expect(mine.filter(id => listed.has(id)).sort(), `${as.email}: the list and each share alone`).toEqual([...alone].sort())+ // The store's answer too, before the route's own machine filter could hide a share it let through.+ expect((await store.openableShares(as, rows)).map(share => share.id).sort(), `${as.email}: the store's batch and each share alone`).toEqual([...alone].sort())+ return mine.filter(id => listed.has(id)).map(id => shares[id]!.name).sort().join('')+ }+ return { tab, run, agents, sees, shared, shareWithBoth, n }+ }++ /** Marks agent `agentId` of this Swarm confidential in another Swarm too, as a registration there would have left it. */+ async function confidentialElsewhere(tab: string, agentId: string) {+ const { id, ...row } = await database.db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agentId } })+ await database.db.swarmAgent.create({ data: { ...row, id: `elsewhere-${id}`, tabId: `elsewhere-${tab}`, data: { ...row.data as object, confidential: true } } })+ }++ it('keeps the Swarm\'s current Lead open to its readers, in a private conversation too, and closes it once confidential elsewhere', async () => {+ const { tab, run, agents, sees } = await swarmWithShares()+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ await run({ type: 'conversation.agent', conversationId: 'lead', agentId: agents.X!, present: true, lead: true })+ expect([await sees(b), await sees(a)]).toEqual(['XYZ', 'XYZ'])+ const chat = (await run({ type: 'conversation.create', title: 'Private', brief: 'Owner and A only.', checks: [], audience: { personIds: [owner.sub, a.sub] } }))+ .result.conversationId as string+ await run({ type: 'conversation.agent', conversationId: chat, agentId: agents.X!, present: true, lead: false })+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ await confidentialElsewhere(tab, agents.X!)+ expect([await sees(b), await sees(a)]).toEqual(['YZ', 'YZ'])+ })++ it('closes a session confidential in another Swarm, though it is an ordinary Builder here', async () => {+ const { tab, agents, sees } = await swarmWithShares()+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ await confidentialElsewhere(tab, agents.Z!)+ expect([await sees(b), await sees(a)]).toEqual(['XY', 'XY'])+ })++ it('closes a session marked confidential that no longer leads here', async () => {+ const { tab, agents, sees } = await swarmWithShares()+ // Written before any list of this Swarm, so no read holds the agent as it was: a mark a Lead or private member leaves.+ const part = await database.db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agents.Y! } })+ await database.db.swarmAgent.update({ where: { id: part.id }, data: { data: { ...part.data as object, confidential: true } } })+ expect([await sees(a), await sees(b)]).toEqual(['XZ', 'XZ'])+ })++ it('shows a project\'s Lead to the Swarm\'s readers, and the next project\'s Lead once the first project is deleted', async () => {+ // A Lead leaves only with its project (commands.ts protectLead): replacing one is a new project with a new Lead.+ const { run, sees, shared } = await swarmWithShares()+ const first = (await run({ type: 'project.create', name: 'First', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }+ await shared('L', first.conversationId, true)+ expect([await sees(a), await sees(b)]).toEqual(['LXYZ', 'LXYZ'])+ await run({ type: 'project.delete', projectId: first.projectId })+ expect([await sees(b), await sees(a)]).toEqual(['XYZ', 'XYZ'])+ const next = (await run({ type: 'project.create', name: 'Next', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }+ await shared('M', next.conversationId, true)+ await shared('W', next.conversationId)+ expect([await sees(a), await sees(b)]).toEqual(['MWXYZ', 'MWXYZ'])+ })++ it('shows a private project only to its members, and again to everyone once it is shared', async () => {+ const { run, sees } = await swarmWithShares()+ expect([await sees(b), await sees(a)]).toEqual(['XYZ', 'XYZ'])+ await run({ type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [owner.sub, a.sub] })+ expect([await sees(b), await sees(a)]).toEqual(['', 'XYZ'])+ await run({ type: 'project.sharing', projectId: 'lead', visibility: 'public', memberIds: [] })+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ })++ it('lists nothing of the Swarm to a removed member, and the same to the member who stays', async () => {+ const { run, sees } = await swarmWithShares()+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ await run({ type: 'member.remove', userId: b.sub })+ expect([await sees(b), await sees(a)]).toEqual(['', 'XYZ'])+ })++ it('hides the agents a machine grant ran once the host takes it back, and only those', async () => {+ const { sees } = await swarmWithShares()+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ await database.db.machineShare.update({ where: { machineId: 'grant-host' }, data: { emails: [] } })+ expect([await sees(b), await sees(a)]).toEqual(['Z', 'Z'])+ await database.db.machineShare.update({ where: { machineId: 'grant-host' }, data: { emails: [owner.email] } })+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ })++ it('hides the Swarm from a member taken out of its Workspace, and only from them', async () => {+ const { tab, sees } = await swarmWithShares()+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ const { workspaceId } = await database.db.superTab.findUniqueOrThrow({ where: { id: tab }, select: { workspaceId: true } })+ await database.db.swarmWorkspaceMember.update({ where: { id: `${workspaceId}:${b.sub}` }, data: { removedAt: new Date(), removedBy: owner.sub } })+ expect([await sees(b), await sees(a)]).toEqual(['', 'XYZ'])+ })++ it('hides an agent its contributor must share again, as when they left and came back', async () => {+ const { tab, agents, sees } = await swarmWithShares()+ // Written before any list of this Swarm, so no read holds the agent as it was.+ const part = await database.db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agents.X! } })+ await database.db.swarmAgent.update({ where: { id: part.id }, data: { data: { ...part.data as object, membershipGeneration: 'an-earlier-membership' } } })+ expect([await sees(a), await sees(b)]).toEqual(['YZ', 'YZ'])+ })++ it('hides a share whose owner is not the machine\'s owner, though it names a session of the Swarm', async () => {+ const { shared, sees } = await swarmWithShares()+ await shared('V', 'lead', false, ['grant-host', host], owner)+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ })++ it('lists a member\'s Buddy to that member alone, never to another, as each share alone does', async () => {+ // A Buddy is in its owner's private chat (buddies.ts), so its session is confidential: only its machine's person watches it.+ const { tab, sees, shareWithBoth, n } = await swarmWithShares()+ const execute = (command: Command, as: AuthUser, hostMachineId?: string) =>+ store.execute(as, tab, { operationId: randomUUID(), command }, undefined, hostMachineId)+ await execute({ type: 'machine.contribute', machineId: 'a-mac', name: 'A Mac', cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 2 }, a)+ const generation = (await poolRows(store, a, 'a-mac')).find(p => p.tabId === tab)!.machine.generation+ await store.observeMachine(a, tab, 'a-mac', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })+ await execute({ type: 'tab.buddies', enabled: true }, owner)+ const startId = String((await execute({ type: 'buddy.create', projectId: 'lead', machineId: 'a-mac', engine: 'claude' }, a)).result.startId)+ // Started by A's host, as a running host does.+ const harnessId = `perm-${n}-buddy`+ await execute({ type: 'agent.startDispatch', startId }, a, 'a-mac')+ await execute({ type: 'agent.started', startId, harnessId, configuration: { ...AGENT_CONFIGURATION, engine: 'claude' } }, a, 'a-mac')+ await execute({ type: 'agent.startSettled', startId, warning: null }, a, 'a-mac')+ await shareWithBoth('B', 'a-mac', harnessId, a)+ expect([await sees(a), await sees(b)]).toEqual(['BXYZ', 'XYZ'])+ })+})diff --git a/backend/src/lib/devicePing.test.ts b/backend/src/lib/devicePing.test.tsnew file mode 100644index 000000000..8dc0a70cb--- /dev/null+++ b/backend/src/lib/devicePing.test.ts@@ -0,0 +1,83 @@+import { EventEmitter } from 'node:events'+import { afterAll, expect, it, vi } from 'vitest'++// A device's 15 s presence ping is for the backend alone: its liveness rides the socket (hub.ts+// trackSocketLiveness). Relayed to the attached machine, the ping reached a daemon that has no use for it+// and refused it as plaintext, a warning every 15 s per device.+const m = vi.hoisted(() => {+ // Before hub.ts is imported: its liveness sweep is a module-level interval.+ vi.useFakeTimers()+ return {+ auth: vi.fn(async () => ({ sub: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' })),+ upgrade: vi.fn(),+ sendDown: vi.fn(),+ }+})+vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))+vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))+vi.mock('../services/index.js', () => ({+ deviceService: {+ resolveOrCreateForComputer: vi.fn(async () => ({ userId: 'owner', deviceId: 'dial-1' })),+ machinesForUser: vi.fn(async () => []), setActiveMachine: vi.fn(async () => {}), recordHello: vi.fn(async () => {}),+ },+}))+vi.mock('./prisma.js', () => ({+ prisma: { machine: { findUnique: vi.fn(async () => ({ machineId: 'mac', userId: 'owner', autonomousEnv: 'prod', billingStatus: 'not_required', authMode: 'remote', deletedAt: null })) } },+ machineAlive: {},+}))+vi.mock('./machineLifecycle.js', () => ({ ensureMachineReady: vi.fn(async () => {}), getMachineLifecycleStatus: vi.fn(async () => 'running') }))+vi.mock('./bus.js', () => ({+ getAgentPresence: vi.fn(async () => null), getAgentPresenceMany: vi.fn(async () => new Map()), getMachineAppStateMany: vi.fn(async () => new Map()),+ subscribeStatus: vi.fn(async () => () => {}), setDevicePresence: vi.fn(async () => {}), clearDevicePresence: vi.fn(async () => 'cleared'),+ publishDeviceStatus: vi.fn(async () => {}), subscribeDeviceControl: vi.fn(async () => () => {}), publishDeviceControl: vi.fn(async () => {}),+ subscribeDeviceMachineListChanged: vi.fn(async () => () => {}), setDeviceLastMachine: vi.fn(async () => {}), getDeviceLastMachine: vi.fn(async () => null),+ parkVoiceUpload: vi.fn(async () => {}), resumeVoiceUpload: vi.fn(async () => null), evictVoiceUpload: vi.fn(async () => {}),+ bumpCommanderJoinGeneration: vi.fn(), getAgentClientState: vi.fn(), publishDown: vi.fn(), publishTerminalDown: vi.fn(), publishUp: vi.fn(),+ setAgentClientCount: vi.fn(), setAgentClientCountsBatch: vi.fn(), subscribeUp: vi.fn(), subscribeTerminalUp: vi.fn(),+}))+vi.mock('./dailyTracking.js', async original => ({ ...await original<typeof import('./dailyTracking.js')>(), touchDeviceOnlineDay: vi.fn(async () => {}) }))+// The real hub, so the socket's real liveness deadline is what keeps it or drops it; only the machine side is faked.+vi.mock('./hub.js', async original => ({+ ...await original<typeof import('./hub.js')>(),+ attachHubClient: vi.fn(() => ({ connId: 'conn-1', sendDown: m.sendDown, setActive: vi.fn(), detach: vi.fn() })),+}))++import { handleDeviceUpgrade } from './deviceWs.js'+import { DEVICE_IDLE_DEADLINE_MS } from './hub.js'++class Socket extends EventEmitter {+ readyState = 1; bufferedAmount = 0+ send = vi.fn()+ ping = vi.fn()+ close = vi.fn(() => { this.readyState = 3; this.emit('close') })+ terminate = vi.fn(() => this.close())+ frame(body: unknown) { this.emit('message', Buffer.from(JSON.stringify(body)), false) }+ sent() { return this.send.mock.calls.map(c => JSON.parse(c[0] as string)) }+}+const flush = async () => { for (let i = 0; i < 400; i++) await Promise.resolve() }+const raw = () => ({ write: vi.fn(), destroy: vi.fn(), destroyed: false, on: vi.fn(), once: vi.fn() })++afterAll(() => { vi.useRealTimers() })++it('a device attached to a machine pings the backend alone, and the ping still keeps its socket alive', async () => {+ const device = new Socket()+ m.upgrade.mockImplementation((_r, _s, _h, done) => done(device))+ handleDeviceUpgrade({ url: '/api/device-ws?computer=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', headers: { 'sec-websocket-protocol': 'access-token' } } as never,+ raw() as never, Buffer.alloc(0))+ await flush()+ device.frame({ type: 'machine_select', payload: { machineId: 'mac' } })+ await flush()+ expect(device.sent()).toContainEqual({ type: 'machine_selected', payload: { machineId: 'mac' } })++ // Twice the silence deadline, the device's own 15 s ping its only traffic.+ for (let t = 0; t < 2 * DEVICE_IDLE_DEADLINE_MS; t += 15_000) {+ device.frame({ type: 'ping' })+ await vi.advanceTimersByTimeAsync(15_000)+ }+ expect(m.sendDown).not.toHaveBeenCalled()+ expect(device.terminate).not.toHaveBeenCalled()++ // The same socket, silent, is dropped: the sweep above was live.+ await vi.advanceTimersByTimeAsync(DEVICE_IDLE_DEADLINE_MS + 5_000)+ expect(device.terminate).toHaveBeenCalled()+})diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.tsindex ca9909066..aeb15699a 100644--- a/backend/src/lib/deviceWs.ts+++ b/backend/src/lib/deviceWs.ts@@ -1273,6 +1273,9 @@ function relay(device: WebSocket, opts: RelayOpts): void {if (msg.type === 'voice_end') { void finishVoice(); return }if (msg.type === 'voice_resume') { void handleVoiceResume(msg); return }if (msg.type === 'device_hello') { handleHello(msg); return }+ // Presence for us alone: any inbound frame already refreshed this socket's liveness (trackSocketLiveness).+ // Relayed, it reached a machine that refuses it as plaintext and logged that every 15 s.+ if (msg.type === 'ping') returninbox.enqueue(msg)})device.on('close', closeBoth)diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.tsindex ee067ea7a..8f1dc7bc3 100644--- a/backend/src/routes/harnessShares.test.ts+++ b/backend/src/routes/harnessShares.test.ts@@ -6,7 +6,15 @@ const mocks = vi.hoisted(() => ({machine: { findFirst: vi.fn(), findMany: vi.fn() }, user: { findMany: vi.fn(), findUnique: vi.fn() }, harnessLink: { findMany: vi.fn() } },mayOpenShare: vi.fn(), presence: vi.fn(), changed: vi.fn(), listChanged: vi.fn(), auth: vi.fn(),}))-vi.mock('../superTabs/store.js', () => ({ SuperTabStore: class { mayOpenShare = mocks.mayOpenShare } }))+// The list asks about every share at once; share by share it answers as mayOpenShare would (integration/harnessSharesList.test.ts).+vi.mock('../superTabs/store.js', () => ({ SuperTabStore: class {+ mayOpenShare = mocks.mayOpenShare+ openableShares = async (user: unknown, shares: unknown[]) => {+ const open = []+ for (const share of shares) if (await mocks.mayOpenShare(user, share)) open.push(share)+ return open+ }+} }))vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: mocks.presence, publishShareChanged: mocks.changed,publishDeviceMachineListChanged: mocks.listChanged }))diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.tsindex 717a57026..c324a77db 100644--- a/backend/src/routes/harnessShares.ts+++ b/backend/src/routes/harnessShares.ts@@ -71,10 +71,8 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {recipientEmail: req.user!.email.trim().toLowerCase(), autonomousEnv: req.user!.autonomousEnv,revokedAt: null, expiresAt: { gt: new Date() },}, orderBy: { createdAt: 'asc' }, take: 1000 })- const visible: typeof shares = []- for (const share of shares) {- if (await new SuperTabStore(prisma).mayOpenShare(req.user!, share)) visible.push(share)- }+ // All at once: share by share, each loaded its whole Swarm again (prod 2026-10-28, p95 13.4 s).+ const visible = await new SuperTabStore(prisma).openableShares(req.user!, shares)const machines = await prisma.machine.findMany({ where: {machineId: { in: [...new Set(visible.map(s => s.machineId))] },autonomousEnv: req.user!.autonomousEnv, ...machineAlive,diff --git a/backend/src/superTabs/confidential.ts b/backend/src/superTabs/confidential.tsindex 8c11c55ec..c34793e46 100644--- a/backend/src/superTabs/confidential.ts+++ b/backend/src/superTabs/confidential.ts@@ -13,20 +13,26 @@ type Transaction = Prisma.TransactionClient* A confidential session is watched by nobody but its machine's person, whichever Swarm or share asks, except by its own* Swarm's readers while it is that Swarm's current Lead (projects.ts watchClosed), which is why a Swarm asks about the others.*/-export async function confidentialSessions(tx: Transaction, agentIds: string[], exceptTabId?: string): Promise<Set<string>> {+/** `stateOf` gives a Swarm's active parts with these agents' groups, as loadActive in `tx` does; a read outside a transaction may+ * give the read cache's (cachedReads.ts readParts gives the same parts), uncopied, as nothing here changes it. */+export async function confidentialSessions(tx: Transaction, agentIds: string[], exceptTabId?: string,+ stateOf: (tabId: string, agentIds: string[]) => Promise<SuperTabState> = async (tabId, ids) => reassemble(await loadActive(tx, tabId, { agentIds: ids }))): Promise<Set<string>> {const found = new Set<string>()if (!agentIds.length) return found- const rows = await tx.swarmAgent.findMany({ where: { key: { in: [...new Set(agentIds)] }, deleted: false, ...(exceptTabId ? { tabId: { not: exceptTabId } } : {}) },- select: { tabId: true, key: true, data: true } })+ // One $in scan of the key index, and only the mark: Prisma's `in` is planned as one index scan per id, and `data` is the whole agent.+ // `exceptTabId` is left out after the read: in the filter the planner took the (tabId, key) index and walked every other Swarm.+ const rows = (await tx.swarmAgent.aggregateRaw({ pipeline: [{ $match: { key: { $in: [...new Set(agentIds)] }, deleted: false } },+ { $project: { _id: 0, tabId: 1, key: 1, confidential: '$data.confidential' } }] }) as unknown as Array<{ tabId: string; key: string; confidential?: Agent['confidential'] }>)+ .filter(row => row.tabId !== exceptTabId)const unmarked = new Map<string, string[]>()for (const row of rows) {- if ((row.data as unknown as Agent).confidential) found.add(row.key)+ if (row.confidential) found.add(row.key)else unmarked.set(row.tabId, [...unmarked.get(row.tabId) ?? [], row.key])}for (const [tabId, keys] of unmarked) {const pending = keys.filter(key => !found.has(key))if (!pending.length) continue- const state = reassemble(await loadActive(tx, tabId, { agentIds: pending }))+ const state = await stateOf(tabId, pending)for (const target of state.agents) if (pending.includes(target.id) && confidentialSession(state, target)) found.add(target.id)}return founddiff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 085434fd3..e0a590991 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1974,6 +1974,55 @@ export class SuperTabStore {return user.sub === share.ownerId || !await this.confidential(this.db, stableId(share.machineId, share.agentId))}+ /** The shares among `shares` that mayOpenShare opens, for a person's whole list (routes/harnessShares.ts): each Swarm loaded+ * once and the confidential sessions read once per Swarm, where share by share each loaded its whole Swarm (prod 2026-10-28:+ * half the backend's busy time in spike minutes). The same answer as mayOpenShare for each share, in the same order. */+ async openableShares<T extends { superTabId: string | null; machineId: string; agentId: string; ownerId: string }>(user: AuthUser, shares: T[]): Promise<T[]> {+ const key = (share: T) => stableId(share.machineId, share.agentId)+ // An ordinary share: never of a session confidential in any Swarm, but for its machine's person.+ const anywhere = await confidentialSessions(this.db, shares.filter(s => !s.superTabId && user.sub !== s.ownerId).map(key), undefined, this.cachedState)+ const byTab = new Map<string, T[]>()+ for (const share of shares) if (share.superTabId) byTab.set(share.superTabId, [...byTab.get(share.superTabId) ?? [], share])+ const observable = new Set<T>()+ for (const [tabId, tabShares] of byTab) for (const share of await this.observable(user, tabId, tabShares)) observable.add(share)+ return shares.filter(s => s.superTabId ? observable.has(s) : user.sub === s.ownerId || !anywhere.has(key(s)))+ }++ /** A Swarm's parts as loadActive gives them, through the read cache and uncopied: for confidentialSessions outside a transaction. */+ private readonly cachedState = async (tabId: string, agentIds: string[]) =>+ reassemble(await readParts(this.db, await this.view([tabId]), tabId, { agentIds }), { share: true })++ /** mayObserve for each of `shares`, all in Swarm `tabId`, from one load of it. */+ private async observable<T extends { machineId: string; agentId: string; ownerId: string }>(user: AuthUser, tabId: string, shares: T[]): Promise<T[]> {+ if (isTeamSession(user)) return []+ let state: SuperTabState+ try {+ state = (await this.readLoad(user, tabId)).state+ person(state, user.sub)+ await requireWorkspaceAccess(this.db, state, user.sub)+ } catch (error) { if (error instanceof SuperTabError) return []; throw error }+ // agentGrant reads only the agent's contributor, machine and grant: agents sharing those share its answer.+ const grants = new Map<string, Promise<boolean>>()+ const granted = (target: Agent) => {+ const key = JSON.stringify([target.contributorId, target.machineId, target.machineOwnerId, target.hostGrant])+ if (!grants.has(key)) grants.set(key, this.agentGrant(this.db, state, target).then(() => true,+ error => { if (error instanceof SuperTabError) return false; throw error }))+ return grants.get(key)!+ }+ const targets = shares.map(share => state.agents.find(a => a.machineId === share.machineId && a.harnessId === share.agentId && a.machineOwnerId === share.ownerId))+ // Confidential in another Swarm closes it here too; in this one, its current Lead stays open to readers (projects.ts watchClosed).+ const elsewhere = await confidentialSessions(this.db, targets.flatMap(t => t ? [t.id] : []), tabId, this.cachedState)+ const allowed: T[] = []+ for (const [i, share] of shares.entries()) {+ const target = targets[i]+ if (!target) continue+ try { agent(state, target.id) } catch (error) { if (error instanceof SuperTabError) continue; throw error }+ if (canWatchAgent(state, { kind: 'person', userId: user.sub, email: user.email }, target, elsewhere.has(target.id))+ && await granted(target)) allowed.push(share)+ }+ return allowed+ }+private deliveryAllowed(state: SuperTabState, delivery: SuperTabDelivery): boolean {const target = state.agents.find(a => a.id === delivery.agentId)const group = state.conversations.find(c => c.id === delivery.conversationId)diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 388cfc0cc..425392715 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -3,5 +3,6 @@ import { defineConfig } from 'vitest/config'export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts','integration/superTabRead.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts','integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts',- 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],+ 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts',+ 'integration/harnessSharesList.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/scripts/install.ps1 b/cli/scripts/install.ps1index e6eadee49..267cab2d3 100644--- a/cli/scripts/install.ps1+++ b/cli/scripts/install.ps1@@ -516,6 +516,53 @@ function Write-HarnessDone {Write-Host ' harness works in this window now. Terminals that were already open see it once they are reopened.'}+function Find-HarnessGit {+ # The git Store installs clone with, or '' when this computer has none. Windows does not come with one, and git+ # was missing on computers where every Store install failed at once (0 of 25 in three days, 2026-10-28). PATH+ # first, then where Git for Windows installs, for everyone or for this user alone, in case PATH is not updated yet.+ param(+ [string]$Path = $env:PATH,+ [string[]]$Roots = @($env:ProgramFiles, ${env:ProgramFiles(x86)}, $(if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'Programs' }))+ )+ foreach ($dir in ($Path -split ';')) {+ $git = Get-HarnessFileIn -Folder $dir -Name 'git.exe'+ if ($git) { return $git }+ }+ foreach ($root in $Roots) {+ $git = Get-HarnessFileIn -Folder $root -Name 'Git\cmd\git.exe'+ if ($git) { return $git }+ }+ return ''+}++function Get-HarnessFileIn {+ # [Folder]\[Name] when that file exists, else ''. Joined as text and tried on its own: PATH can name a drive that is+ # not there (an unplugged USB disk, an unmapped share), where Join-Path stops with 'Cannot find drive', or hold an+ # entry in quotes, which .NET calls illegal. Under the installer's errors-stop either one turned a finished install+ # into a failed one (review of #2025).+ param([string]$Folder, [string]$Name)+ if (-not $Folder) { return '' }+ try {+ $file = [IO.Path]::Combine($Folder, $Name)+ if (Test-Path -LiteralPath $file -PathType Leaf) { return $file }+ } catch { }+ return ''+}++function Write-HarnessGitNote {+ # Said, not done: installing Git for Windows is the person's choice, and this installer changes nothing outside+ # their own folder and PATH. Harness itself runs without git; the Store's harnesses do not.+ param([string]$Git = (Find-HarnessGit))+ if ($Git) { return }+ Write-Host ''+ Write-Host ' Git for Windows is not installed. Harnesses from the Store are installed with git, and run their setup in its Git Bash.' -ForegroundColor Yellow+ Write-Host ' Install it, then open a new window:'+ Write-Host ''+ Write-Host ' winget install --id Git.Git -e'+ Write-Host ''+ Write-Host ' or download it from https://git-scm.com/download/win'+}+function Read-HarnessCurrentCli {# The version cli\current names, or '' before a first install.param([string]$Root)@@ -625,6 +672,7 @@ function Install-Harness {return 1}Write-HarnessDone -Version $version -Desktop:$Desktop -NoService:$NoService -Command $command+ Write-HarnessGitNotereturn 0}@@ -729,6 +777,7 @@ function Install-HarnessApp {Write-Host ''Write-Host "Harness $version is installed, and it is opening now."Write-Host 'Next time, open it from the Start menu. On its first start it sets up the Harness command line.'+ Write-HarnessGitNotereturn 0}diff --git a/cli/src/dsh/install.spec.ts b/cli/src/dsh/install.spec.tsindex cc7762548..e397f5c27 100644--- a/cli/src/dsh/install.spec.ts+++ b/cli/src/dsh/install.spec.ts@@ -6,7 +6,7 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync,import { tmpdir } from 'node:os'import { join } from 'node:path'import { env } from '../config/env.js'-import { DOCTOR_TIMEOUT_MS, installDsh, isTransientGitFailure, removeDsh, resolveInstallSource, runDshDoctor, type DshInstallProgress } from './install.js'+import { DOCTOR_TIMEOUT_MS, gitStartFailure, installDsh, isTransientGitFailure, removeDsh, resolveInstallSource, runDshDoctor, type DshInstallProgress } from './install.js'import { dshInstallDir, installedDsh, invalidateInstalledDsh, listInstalledDsh, readInstalledIndex, type InstalledDsh } from './installed.js'import { HARNESS_MONOREPO, type DshRegistryEntry } from './registry.js'@@ -375,6 +375,16 @@ describe('installDsh, every way it can go', () => {expect(leftovers()).toEqual([])})+ it('on Windows, where git does not come with the system, no git says to install Git for Windows', () => {+ const missing = Object.assign(new Error('spawn git ENOENT'), { code: 'ENOENT' })+ expect(gitStartFailure(missing, 'win32')).toBe('Git is not installed on this computer, and harnesses are installed with it. Install Git for Windows from https://git-scm.com/download/win (or run: winget install --id Git.Git -e), then try again.')+ // Elsewhere, the plain sentence; any other failure to start, what Node said.+ const plain = 'Git is not installed on this computer, and installing a harness needs it. Install Git, then try again.'+ expect(gitStartFailure(missing, 'darwin')).toBe(plain)+ expect(gitStartFailure(missing, 'linux')).toBe(plain)+ expect(gitStartFailure(Object.assign(new Error('spawn git EACCES'), { code: 'EACCES' }), 'win32')).toBe('spawn git EACCES')+ })+it('a clone still running after ten minutes is stopped, and said to have been', async () => {stubGit('echo "Cloning into x..." >&2\nexec sleep 30')vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })@@ -477,7 +487,8 @@ describe('installDsh, every way it can go', () => {it('a harness with a setup or a doctor is refused once fetched, before it is placed, and nothing stays on disk', async () => {// 2026-10-28: every Store install on Windows failed; their setup and doctor ran through a /bin/sh Windows lacks.// The review of #2026 found the refusal came after the package was placed, so its files stayed, unrecorded.- const detail = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'+ // They run in Git Bash now; this computer, taken for Windows, has none (no Program Files, no git.exe on PATH).+ const detail = 'This harness runs a setup or check script, which needs Git Bash on Windows, and it was not found. Install Git for Windows from https://git-scm.com/download/win (or run: winget install --id Git.Git -e), then try again.'const placed = (): boolean => { try { lstatSync(dshInstallDir('acme/thing')); return true } catch { return false } }for (const [toolchain, link] of [[{ setup: 'setup.sh' }, false], [{ doctor: 'doctor.sh' }, false], [{ setup: 'setup.sh' }, true]] as const) {rmSync(join(root, 'src'), { recursive: true, force: true })diff --git a/cli/src/dsh/install.ts b/cli/src/dsh/install.tsindex 89c55319e..8a145b3bd 100644--- a/cli/src/dsh/install.ts+++ b/cli/src/dsh/install.ts@@ -24,6 +24,7 @@ import { resolveDshCommand } from './materialize.js'import { DSH_SHELL_UNAVAILABLE, dshShellAvailable, runDshCommand } from './shell.js'import { lockDsh, dshBusy } from './lock.js'import { insideGitCheckout } from '../lib/gitProject.js'+import { INSTALL_GIT_FOR_WINDOWS } from '../lib/windows/gitBash.js'const execFileAsync = promisify(execFile)@@ -188,7 +189,7 @@ async function cloneOnce(// `--progress` because stderr is not a tty here and git would otherwise stay silent until the end;// streamed, not collected, so "Receiving objects: 39%" reaches the dialog while it is true.const clone = await cloneRepo(source, ref, tmpDir, false, onLine)- if (!clone.ok) return fail(clone.noGit ? 'GIT_UNAVAILABLE' : 'CLONE_FAILED', clone.noGit ? NO_GIT : clone.detail)+ if (!clone.ok) return fail(clone.noGit ? 'GIT_UNAVAILABLE' : 'CLONE_FAILED', clone.detail)commit = await gitHead(tmpDir)revision = await gitHead(tmpDir, 'HEAD^{tree}')} else {@@ -199,7 +200,7 @@ async function cloneOnce(// whole-repo one (the manifest at its root) and nothing else of the monorepo lands on the machine.const repoDir = join(root, `.tmp-${randomUUID()}`)const clone = await cloneRepo(source, ref, repoDir, true, onLine)- if (!clone.ok) return fail(clone.noGit ? 'GIT_UNAVAILABLE' : 'CLONE_FAILED', clone.noGit ? NO_GIT : clone.detail, repoDir)+ if (!clone.ok) return fail(clone.noGit ? 'GIT_UNAVAILABLE' : 'CLONE_FAILED', clone.detail, repoDir)const sparse = await streamGit(['-C', repoDir, 'sparse-checkout', 'set', '--', path], onLine)if (!sparse.ok) return fail('CLONE_FAILED', sparse.detail, repoDir)const folder = join(repoDir, ...path.split('/'))@@ -280,7 +281,7 @@ function streamGit(args: string[], onLine: ((line: string) => void) | undefined)})child.on('error', (error: NodeJS.ErrnoException) => {clearTimeout(timer)- resolve({ ok: false, detail: error.message, ...(error.code === 'ENOENT' ? { noGit: true as const } : {}) })+ resolve({ ok: false, detail: gitStartFailure(error), ...(error.code === 'ENOENT' ? { noGit: true as const } : {}) })})// Exit may precede the last stderr data. Classify the failure only once// the pipe closes, so a retryable Git error cannot become an empty one.@@ -296,6 +297,16 @@ function streamGit(args: string[], onLine: ((line: string) => void) | undefined)})}+/**+ * What a git that could not start is reported as. A missing one is said in words (NO_GIT); on Windows, where git is+ * not part of the system and the installer does not bring it, with where to get Git for Windows and the winget line+ * that installs it (0 of 25 Windows Store installs succeeded, 2026-10-28). Any other failure to start: what Node said.+ */+export function gitStartFailure(error: NodeJS.ErrnoException, platform: NodeJS.Platform = process.platform): string {+ if (error.code !== 'ENOENT') return error.message+ return platform === 'win32' ? `Git is not installed on this computer, and harnesses are installed with it. ${INSTALL_GIT_FOR_WINDOWS}` : NO_GIT+}+/** Put the clone (or the link) at its final path, replacing whatever an earlier install left there. */function placeAt(id: string, from: { tmpDir: string } | { linkTo: string }): string {const dir = dshInstallDir(id)diff --git a/cli/src/dsh/service.spec.ts b/cli/src/dsh/service.spec.tsindex ae2595afe..ae169f0a5 100644--- a/cli/src/dsh/service.spec.ts+++ b/cli/src/dsh/service.spec.ts@@ -12,6 +12,9 @@ vi.mock('./catalog.js', () => ({}))vi.mock('./install.js', async original => ({ ...await original<typeof import('./install.js')>(), installDsh: vi.fn() }))vi.mock('./update.js', () => ({ updateDsh: vi.fn() }))+// Where Git for Windows' bash is, as the lookup would find it on disk: none, unless a test installs it.+const gitBash = vi.hoisted(() => ({ path: null as string | null }))+vi.mock('../lib/windows/gitBash.js', async original => ({ ...await original<typeof import('../lib/windows/gitBash.js')>(), findGitBash: () => gitBash.path }))const success: DshInstallResult = { ok: true, installed: {id: 'acme/thing', dir: '/fixture', realDir: '/fixture', source: 'https://example.com/thing',@@ -56,7 +59,8 @@ describe('daemon package mutations', () => {const platform = Object.getOwnPropertyDescriptor(process, 'platform')!beforeEach(() => { Object.defineProperty(process, 'platform', { ...platform, value: 'win32' }) })afterEach(() => { Object.defineProperty(process, 'platform', platform) })- const detail = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'+ // Scripts run in Git Bash on Windows; this computer, taken for Windows, has none (no Program Files, no git.exe on PATH).+ const detail = 'This harness runs a setup or check script, which needs Git Bash on Windows, and it was not found. Install Git for Windows from https://git-scm.com/download/win (or run: winget install --id Git.Git -e), then try again.'it('refuses from the catalog entry, before downloading anything, a package or its viewer that runs one', async () => {// 2026-10-28 review of #2026: refused only after the download was placed, its files stayed on disk.@@ -78,6 +82,17 @@ describe('daemon package mutations', () => {expect(await mutateDsh({ url: 'https://example.com/unlisted' }, () => {})).toMatchObject({ ok: true })expect(installDsh).toHaveBeenCalledTimes(2)})++ it('installs a package that runs scripts once Git for Windows is there, since they run in its Git Bash', async () => {+ gitBash.path = 'C:\\Program Files\\Git\\bin\\bash.exe'+ try {+ catalog.entries = [{ id: 'acme/thing', name: 'Thing', engine: 'claude', repo: 'https://example.com/thing', runsScripts: true }]+ expect(await mutateDsh({ id: 'acme/thing' }, () => {})).toMatchObject({ ok: true })+ expect(installDsh).toHaveBeenCalledTimes(1)+ } finally {+ gitBash.path = null+ }+ })})it('a package that runs scripts installs where a shell runs them', async () => {diff --git a/cli/src/dsh/shell.spec.ts b/cli/src/dsh/shell.spec.tsindex 3deeb2c04..553b79750 100644--- a/cli/src/dsh/shell.spec.ts+++ b/cli/src/dsh/shell.spec.ts@@ -1,9 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { EventEmitter } from 'node:events'-import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'-import { dirname, join } from 'node:path'-import type { ChildProcess } from 'node:child_process'+import { dirname, join, win32 } from 'node:path'+import { spawnSync, type ChildProcess } from 'node:child_process'// Two switches, both off by default: `sh` makes commands run under plain `/bin/sh -c` (as when no user// shell is known) so output is exactly the command's; `fakeChild` hands runDshCommand a scripted child.@@ -19,7 +19,7 @@ vi.mock('node:child_process', async (importOriginal) => {})const { managedNodePath } = await import('../lib/nodeRuntime.js')-const { dshNodeFallback, dshShellArgv, isKilledJobReport, isShellNoise, killProcessGroup, runDshCommand, spawnDshCommand } = await import('./shell.js')+const { dshNodeFallback, dshShellArgv, dshShellAvailable, isKilledJobReport, isShellNoise, killProcessGroup, runDshCommand, spawnDshCommand } = await import('./shell.js')describe('dshShellArgv', () => {const original = process.env.SHELL@@ -45,6 +45,65 @@ describe('dshShellArgv', () => {})})+describe('dshShellArgv on Windows', () => {+ const gitBash = () => 'C:\\Program Files\\Git\\bin\\bash.exe'++ it('runs setup and doctor through Git Bash as a login shell, never /bin/sh, which Windows has not', () => {+ const { path, args } = dshShellArgv('./doctor.sh', { platform: 'win32', gitBash })+ expect(path).toBe('C:\\Program Files\\Git\\bin\\bash.exe')+ expect(args).toHaveLength(2)+ expect(args[0]).toBe('-lic')+ expect(args[1].endsWith('\n./doctor.sh')).toBe(true)+ })++ it('says to install Git for Windows when there is no Git Bash, instead of trying a shell that is not there', () => {+ expect(() => dshShellArgv('./doctor.sh', { platform: 'win32', gitBash: () => null }))+ .toThrow('This harness runs a setup or check script, which needs Git Bash on Windows, and it was not found. Install Git for Windows from https://git-scm.com/download/win (or run: winget install --id Git.Git -e), then try again.')+ })++ describe('the script it runs, in a real bash', () => {+ let dir: string+ beforeEach(() => { dir = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-gitbash-'))) })+ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })++ it('ignores a profile\'s `node` alias and finds Harness\'s Node through cygpath when PATH has none', () => {+ // Git Bash profiles can say `alias node='winpty node.exe'`, and winpty fails without a terminal ("stdin is not a+ // tty"). Harness's Node is a C:\ folder, which Git Bash's PATH cannot hold until cygpath writes it as /c/....+ const home = join(dir, 'home'); const stubs = join(dir, 'stubs'); const runtime = join(dir, 'runtime')+ for (const folder of [home, stubs, runtime]) mkdirSync(folder)+ writeFileSync(join(home, '.bash_profile'), "alias node='echo winpty-node'\n")+ writeFileSync(join(runtime, 'node'), '#!/bin/sh\necho harness-node\n', { mode: 0o755 })+ writeFileSync(join(stubs, 'cygpath'), `#!/bin/sh\n[ "$1" = -u ] && [ "$2" = -- ] || exit 9\nprintf '%s\\n' "$3" > '${join(dir, 'asked')}'\nprintf '%s\\n' '${runtime}'\n`, { mode: 0o755 })+ const { args } = dshShellArgv('node', { platform: 'win32', gitBash: () => '/bin/bash' })+ const ran = spawnSync('/bin/bash', args, { cwd: dir, encoding: 'utf8', env: { HOME: home, PATH: stubs } })+ expect(ran.stdout).toBe('harness-node\n')+ expect(readFileSync(join(dir, 'asked'), 'utf8')).toBe(`${win32.dirname(managedNodePath())}\n`)+ })++ it('runs setup and doctor in the harness folder, though a login Git Bash goes home', async () => {+ // Git for Windows' /etc/profile changes to $HOME in a login shell unless CHERE_INVOKING is set; this profile+ // does the same, so the command would otherwise run in the home folder, not the harness's.+ const home = join(dir, 'home'); const stubs = join(dir, 'stubs'); const harness = join(dir, 'harness')+ for (const folder of [home, stubs, harness]) mkdirSync(folder)+ writeFileSync(join(home, '.bash_profile'), '[ -n "$CHERE_INVOKING" ] || cd "$HOME"\n')+ writeFileSync(join(stubs, 'cygpath'), `#!/bin/sh\nprintf '%s\\n' '${stubs}'\n`, { mode: 0o755 })+ const result = await runDshCommand('echo "ran in $(pwd)"', { cwd: harness, env: { HOME: home, PATH: stubs }, host: { platform: 'win32', gitBash: () => '/bin/bash' } })+ // Only the script's own line: this is a real login bash, and the host's /etc/profile says what it likes (Ubuntu's+ // CI runner: 'run-parts: command not found', with the PATH the test gives it).+ expect(result.lines.filter((line) => line.startsWith('ran in '))).toEqual([`ran in ${harness}`])+ })+ })+})++describe('dshShellAvailable', () => {+ it('is on wherever there is a shell for setup and doctor: a POSIX system, or Windows with Git Bash', () => {+ expect(dshShellAvailable({ platform: 'darwin' })).toBe(true)+ expect(dshShellAvailable({ platform: 'linux', gitBash: () => null })).toBe(true)+ expect(dshShellAvailable({ platform: 'win32', gitBash: () => 'C:\\Program Files\\Git\\bin\\bash.exe' })).toBe(true)+ expect(dshShellAvailable({ platform: 'win32', gitBash: () => null })).toBe(false)+ })+})+describe('dshNodeFallback', () => {let dir: stringbeforeEach(() => { seams.sh = true; dir = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-node-'))) })diff --git a/cli/src/dsh/shell.ts b/cli/src/dsh/shell.tsindex 6c76f88d6..b23af905f 100644--- a/cli/src/dsh/shell.ts+++ b/cli/src/dsh/shell.ts@@ -5,8 +5,11 @@* same shell selection) `engineLaunch.ts` uses to exec an engine in a pane.*/import { spawn, type ChildProcess } from 'node:child_process'+import { win32 } from 'node:path'import { harnessNodePrelude, interactiveEngineShell } from '../lib/engineLaunch.js'import { managedNodePath } from '../lib/nodeRuntime.js'+import { shellSingleQuote } from '../lib/shellQuote.js'+import { findGitBash, INSTALL_GIT_FOR_WINDOWS } from '../lib/windows/gitBash.js'export interface DshCommandOptions {cwd: string@@ -14,6 +17,8 @@ export interface DshCommandOptions {/** Each line of combined stdout+stderr, as it arrives. */onLine?: (line: string) => voidtimeoutMs?: number+ /** The platform and Git Bash to run under, when not this computer's: a test runs Windows' path on any computer. */+ host?: DshShellHost}export interface DshCommandResult {@@ -49,7 +54,8 @@ export function isKilledJobReport(line: string): boolean {}/**- * `[path, ...args]` that runs `script` through the user's shell, or `/bin/sh -c` when none is known.+ * `[path, ...args]` that runs `script` through the user's shell, or `/bin/sh -c` when none is known; on Windows,+ * which has neither, through Git Bash (`gitBashArgv`).** AS A LOGIN SHELL, whatever the shell. interactiveEngineShell gives bash `-ic` on purpose for a pane* (see tmuxOnPath.ts on why), but a bash user's PATH conventionally lives in `.bash_profile`, which@@ -59,7 +65,8 @@ export function isKilledJobReport(line: string): boolean {* is sourced from `.bash_profile`. A setup or a doctor is one process, so the reason bash panes avoid* `-l` (a PATH built in .bashrc compounding across subshells) does not apply here.*/-export function dshShellArgv(script: string): { path: string; args: string[] } {+export function dshShellArgv(script: string, host: DshShellHost = {}): { path: string; args: string[]; env?: Record<string, string> } {+ if ((host.platform ?? process.platform) === 'win32') return gitBashArgv(script, (host.gitBash ?? findGitBash)())const shell = interactiveEngineShell()const body = `${dshNodeFallback()}\n${script}`if (shell) {@@ -69,17 +76,49 @@ export function dshShellArgv(script: string): { path: string; args: string[] } {return { path: '/bin/sh', args: ['-c', body] }}+/** The platform and the Git Bash lookup `dshShellArgv` uses; a test gives Windows' on any computer. */+export interface DshShellHost {+ platform?: NodeJS.Platform+ gitBash?: () => string | null+}++/** What a person is told when a package's setup or doctor cannot run here: a Windows computer without Git Bash, as an+ * install's refusal (before the download, or once fetched) or as a command's one line. */+export const DSH_SHELL_UNAVAILABLE = `This harness runs a setup or check script, which needs Git Bash on Windows, and it was not found. ${INSTALL_GIT_FOR_WINDOWS}`+/**- * Whether this computer has a shell for a DSH's commands. Windows has none yet: interactiveEngineShell gives it no- * shell, and the `/bin/sh` fallback is not there, so every Store install on Windows failed in its setup or doctor- * (2026-10-28: 0 of 25 since 10-26). Running them under Git Bash there is its own change, which turns this on.+ * Windows: Git Bash, as a login shell like the user's shell elsewhere, so its profile builds PATH (and puts cygpath+ * on it). Thrown when there is none, and runDshCommand reports that as the command's one line: the doctor or setup+ * says what to install, where `spawn /bin/sh ENOENT` said nothing a person could act on.+ *+ * Two lines go before the command. `unalias node`: Git Bash profiles can say `alias node='winpty node.exe'`, and winpty+ * fails with "stdin is not a tty" here, where the command's output is a pipe. And Harness's Node at the end of a PATH+ * with none, as `dshNodeFallback` does elsewhere, but written by cygpath: its folder is a `C:\...` path, whose colon+ * would split a Git Bash PATH in two. Both were found, and checked on Windows 11, by an outside contribution (#1511).+ *+ * CHERE_INVOKING: Git for Windows' /etc/profile changes a login shell to $HOME unless it is set, and a setup or doctor+ * runs in the harness's folder (review of #2025).*/-export function dshShellAvailable(): boolean {- return process.platform !== 'win32'+function gitBashArgv(script: string, bash: string | null): { path: string; args: string[]; env: Record<string, string> } {+ if (!bash) throw new Error(DSH_SHELL_UNAVAILABLE)+ const runtimeDir = shellSingleQuote(win32.dirname(managedNodePath()))+ const body = [+ 'unalias node 2>/dev/null || true',+ `if ! command -v node >/dev/null 2>&1; then PATH="\${PATH:+$PATH:}$(cygpath -u -- ${runtimeDir})"; export PATH; fi`,+ script,+ ].join('\n')+ return { path: bash, args: ['-lic', body], env: { CHERE_INVOKING: '1' } }}-/** What a person is told when a package's setup or doctor cannot run here. */-export const DSH_SHELL_UNAVAILABLE = 'This harness runs a setup or check script, and Harness cannot run those on Windows yet.'+/**+ * Whether this computer has a shell for a DSH's commands. Every Store install on Windows failed in its setup or doctor+ * (2026-10-28: 0 of 25 since 10-26): there was no shell there, and the `/bin/sh` fallback is not there. They run in+ * Git Bash now (`gitBashArgv`), so Windows has one when Git for Windows is installed; without it, an install is refused+ * before anything runs, with DSH_SHELL_UNAVAILABLE as its words.+ */+export function dshShellAvailable(host: DshShellHost = {}): boolean {+ return (host.platform ?? process.platform) !== 'win32' || (host.gitBash ?? findGitBash)() !== null+}/*** The line run before a DSH's command: when the login shell's PATH has no `node`, the Node this@@ -93,11 +132,11 @@ export function dshNodeFallback(): string {return harnessNodePrelude(managedNodePath()).trimEnd()}-export function spawnDshCommand(script: string, opts: { cwd: string; env?: Record<string, string> }): ChildProcess {- const { path, args } = dshShellArgv(script)+export function spawnDshCommand(script: string, opts: { cwd: string; env?: Record<string, string>; host?: DshShellHost }): ChildProcess {+ const { path, args, env } = dshShellArgv(script, opts.host)return spawn(path, args, {cwd: opts.cwd,- env: { ...process.env, ...(opts.env ?? {}) },+ env: { ...process.env, ...env, ...(opts.env ?? {}) },stdio: ['ignore', 'pipe', 'pipe'],// Its own process group, so stopping it stops what it started (`sh -c node …`).detached: true,@@ -112,7 +151,7 @@ export function runDshCommand(script: string, opts: DshCommandOptions): Promise<let settled = falselet child: ChildProcesstry {- child = spawnDshCommand(script, { cwd: opts.cwd, env: opts.env })+ child = spawnDshCommand(script, { cwd: opts.cwd, env: opts.env, host: opts.host })} catch (error) {// spawn throws only Errors (an invalid argument: a NUL in the cwd, say).const line = `could not start: ${(error as Error).message}`diff --git a/cli/src/lib/windows/gitBash.spec.ts b/cli/src/lib/windows/gitBash.spec.tsnew file mode 100644index 000000000..0d5c88533--- /dev/null+++ b/cli/src/lib/windows/gitBash.spec.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'+import { findGitBash } from './gitBash.js'++/** A fake Windows disk: the files that exist, compared as Windows does, without regard to case. */+const disk = (...files: string[]) => {+ const present = new Set(files.map((file) => file.toLowerCase()))+ return (path: string) => present.has(path.toLowerCase())+}++describe('findGitBash', () => {+ it('finds bash.exe beside the git on PATH, in each layout Git for Windows puts git in', () => {+ const cmd = disk('D:\\Tools\\Git\\cmd\\git.exe', 'D:\\Tools\\Git\\bin\\bash.exe')+ expect(findGitBash({ env: { PATH: 'C:\\Windows\\System32;D:\\Tools\\Git\\cmd' }, isFile: cmd })).toBe('D:\\Tools\\Git\\bin\\bash.exe')+ const bin = disk('D:\\Git\\bin\\git.exe', 'D:\\Git\\bin\\bash.exe')+ expect(findGitBash({ env: { PATH: 'D:\\Git\\bin' }, isFile: bin })).toBe('D:\\Git\\bin\\bash.exe')+ const mingw = disk('D:\\Git\\mingw64\\bin\\git.exe', 'D:\\Git\\bin\\bash.exe')+ expect(findGitBash({ env: { PATH: 'D:\\Git\\mingw64\\bin' }, isFile: mingw })).toBe('D:\\Git\\bin\\bash.exe')+ })++ it('looks in the folders Git for Windows installs to when git is not on PATH, the per-user one included', () => {+ const machine = disk('C:\\Program Files\\Git\\bin\\bash.exe')+ expect(findGitBash({ env: { PATH: '', ProgramFiles: 'C:\\Program Files' }, isFile: machine })).toBe('C:\\Program Files\\Git\\bin\\bash.exe')+ const user = disk('C:\\Users\\ana\\AppData\\Local\\Programs\\Git\\bin\\bash.exe')+ expect(findGitBash({ env: { LOCALAPPDATA: 'C:\\Users\\ana\\AppData\\Local' }, isFile: user })).toBe('C:\\Users\\ana\\AppData\\Local\\Programs\\Git\\bin\\bash.exe')+ })++ it('prefers the git on PATH over an older install in Program Files', () => {+ const both = disk('C:\\Program Files\\Git\\bin\\bash.exe', 'D:\\Git\\cmd\\git.exe', 'D:\\Git\\bin\\bash.exe')+ expect(findGitBash({ env: { PATH: 'D:\\Git\\cmd', ProgramFiles: 'C:\\Program Files' }, isFile: both })).toBe('D:\\Git\\bin\\bash.exe')+ })++ it('never takes the bash.exe on PATH that is WSL\'s, nor a git with no bash beside it', () => {+ // System32\bash.exe starts a Linux distribution, where C:\ paths and the Windows PATH mean nothing.+ const wsl = disk('C:\\Windows\\System32\\bash.exe', 'C:\\Windows\\System32\\git.exe', 'D:\\MinGit\\cmd\\git.exe')+ expect(findGitBash({ env: { PATH: 'C:\\Windows\\System32;D:\\MinGit\\cmd' }, isFile: wsl })).toBeNull()+ })++ it('is null on a computer with no Git for Windows at all', () => {+ expect(findGitBash({ env: { PATH: 'C:\\Windows\\System32', ProgramFiles: 'C:\\Program Files' }, isFile: disk() })).toBeNull()+ expect(findGitBash({ env: {}, isFile: disk() })).toBeNull()+ })+})diff --git a/cli/src/lib/windows/gitBash.ts b/cli/src/lib/windows/gitBash.tsnew file mode 100644index 000000000..32afd9613--- /dev/null+++ b/cli/src/lib/windows/gitBash.ts@@ -0,0 +1,42 @@+/**+ * The Git Bash that runs a harness's own scripts on Windows: its setup, its doctor, its workspace init and its viewer+ * (dsh/shell.ts). 65 of the Store's 67 harnesses have a setup or a doctor, and they are POSIX shell scripts; Windows has+ * no /bin/sh, and every Windows Store install failed at `spawn /bin/sh ENOENT` (0 of 25 in three days, 2026-10-28).+ * The same installs clone with git, so Git for Windows, which ships bash, is already the one thing they need.+ *+ * Found from the git install, never from a `bash.exe` on PATH: `C:\Windows\System32\bash.exe` is WSL's launcher, which+ * starts a Linux distribution where `C:\` paths and the Windows PATH mean nothing. MinGit, the git without a shell,+ * has no `bin\bash.exe`, so it is not taken for one.+ *+ * Where to look was first worked out, and checked on Windows 11, by an outside contribution (PR #1511).+ */+import { statSync } from 'node:fs'+import { win32 } from 'node:path'++export interface GitBashSearch {+ env?: NodeJS.ProcessEnv+ isFile?: (path: string) => boolean+}++/** What a person is told to do when Git for Windows is missing. */+export const INSTALL_GIT_FOR_WINDOWS = 'Install Git for Windows from https://git-scm.com/download/win (or run: winget install --id Git.Git -e), then try again.'++export function findGitBash({ env = process.env, isFile = fileExists }: GitBashSearch = {}): string | null {+ const candidates: string[] = []+ // The git on PATH first, as the person's own terminal would run it. Git for Windows puts it in <root>\cmd (the+ // installer's default), <root>\bin or <root>\mingw64\bin; its bash is <root>\bin\bash.exe in each.+ for (const dir of (env.PATH ?? '').split(';').filter(Boolean)) {+ if (!isFile(win32.join(dir, 'git.exe'))) continue+ candidates.push(win32.resolve(dir, '..', 'bin', 'bash.exe'), win32.resolve(dir, '..', '..', 'bin', 'bash.exe'))+ }+ // Then where its installer puts it: for everyone, or for this user alone (no administrator rights).+ for (const root of [env.ProgramFiles, env.ProgramW6432, env['ProgramFiles(x86)']]) {+ if (root) candidates.push(win32.join(root, 'Git', 'bin', 'bash.exe'))+ }+ if (env.LOCALAPPDATA) candidates.push(win32.join(env.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'))+ return candidates.find((candidate) => isFile(candidate)) ?? null+}++function fileExists(path: string): boolean {+ try { return statSync(path).isFile() } catch { return false }+}diff --git a/cli/src/scripts/installPs1.spec.ts b/cli/src/scripts/installPs1.spec.tsindex fc04c6efa..7c15ef6fc 100644--- a/cli/src/scripts/installPs1.spec.ts+++ b/cli/src/scripts/installPs1.spec.ts@@ -166,6 +166,29 @@ describe.runIf(windows)('install.ps1 building blocks, in Windows PowerShell 5.1'expect(ps('Test-HarnessHost').stdout.toLowerCase()).toBe(join(process.env.SystemRoot!, 'System32', 'tar.exe').toLowerCase())})+ // 2026-10-28: 0 of 25 Windows Store installs succeeded; where git was missing, the clone failed at once.+ it('finds git on PATH or where Git for Windows installs it, and says how to get Git for Windows when there is none', () => {+ const root = mkdtempSync(join(tmpdir(), 'harness-ps1-git-'))+ scratch.push(root)+ const cmd = join(root, 'Git', 'cmd')+ mkdirSync(cmd, { recursive: true })+ writeFileSync(join(cmd, 'git.exe'), '')+ expect(ps(`Find-HarnessGit -Path 'C:\\nowhere;${cmd}' -Roots @()`).stdout).toBe(join(cmd, 'git.exe'))+ expect(ps(`Find-HarnessGit -Path '' -Roots @('${root}')`).stdout).toBe(join(cmd, 'git.exe'))+ expect(ps(`Find-HarnessGit -Path '' -Roots @()`).stdout).toBe('')+ // A PATH entry on a drive that is not there (an unplugged USB disk, an unmapped share), or one written in quotes:+ // Join-Path stops on the first under errors-stop, and a finished install then exited as failed (review of #2025).+ const absent = 'ZYXWVUTSRQ'.split('').find((letter) => !existsSync(`${letter}:\\`))!+ const odd = ps(`Find-HarnessGit -Path '${absent}:\\gone;"C:\\quoted dir";${cmd}' -Roots @('${absent}:\\gone')`)+ expect(odd.stdout, odd.stderr).toBe(join(cmd, 'git.exe'))+ expect(odd.status).toBe(0)+ const missing = ps(`Write-HarnessGitNote -Git ''`).stdout+ expect(missing).toContain('Git for Windows is not installed')+ expect(missing).toContain('winget install --id Git.Git -e')+ expect(missing).toContain('https://git-scm.com/download/win')+ expect(ps(`Write-HarnessGitNote -Git '${join(cmd, 'git.exe')}'`).stdout).toBe('')+ })+it('trusts https:// and local files only, and resolves a local manifest\'s relative names against its folder', () => {const dir = mkdtempSync(join(tmpdir(), 'harness-ps1-ref-'))scratch.push(dir)diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dartindex 964dc96e2..408d9be9e 100644--- a/desktop/lib/super_tabs/buddies.dart+++ b/desktop/lib/super_tabs/buddies.dart@@ -105,10 +105,31 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {projects.where((p) => p.id == c.currentProjectId).firstOrNull?.id ??projects.firstOrNull?.id;_machine = buddyMachines(c).firstOrNull?.id;+ c.addListener(_swarmChanged);+ }++ @override+ void dispose() {+ c.removeListener(_swarmChanged);+ super.dispose();+ }++ /// The Swarm changed under the open dialog: its machines may have too.+ void _swarmChanged() {+ if (mounted) setState(() {});+ }++ /// The chosen machine while it is still one of the reader's, else the+ /// first that is; null when none is left.+ String? get _listedMachine {+ final machines = buddyMachines(c);+ return machines.any((m) => m.id == _machine)+ ? _machine+ : machines.firstOrNull?.id;}Future<void> _submit() async {- final project = _project, machine = _machine;+ final project = _project, machine = _listedMachine;if (_busy || project == null || machine == null) return;setState(() {_busy = true;@@ -193,7 +214,7 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {): AppSelectField<String>(key: const ValueKey('super-buddy-machine'),- value: _machine ?? '',+ value: _listedMachine ?? '',semanticLabel: 'Machine',textStyle: DesktopChrome.control(),options: [@@ -252,7 +273,7 @@ class _AddBuddyDialogState extends State<_AddBuddyDialog> {child: const Text('Cancel'),),FilledButton(- onPressed: _busy || _project == null || _machine == null+ onPressed: _busy || _project == null || _listedMachine == null? null: () => unawaited(_submit()),child: Text(_busy ? 'Adding…' : 'Add Buddy'),diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dartindex b3bbca9ea..8252663c3 100644--- a/desktop/test/super_tab_buddies_test.dart+++ b/desktop/test/super_tab_buddies_test.dart@@ -394,7 +394,6 @@ void main() {group('Add a Buddy', () {final machine = find.byKey(const ValueKey('super-buddy-machine'));final submit = find.widgetWithText(FilledButton, 'Add Buddy');- final notice = find.byKey(const ValueKey('super-buddy-machine-notice'));Future<void> open(WidgetTester tester) async {await tester.tap(addBuddy);@@ -412,7 +411,6 @@ void main() {find.descendant(of: machine, matching: find.text('Kens-MacBook')),findsOneWidget,);- expect(notice, findsNothing);await tester.tap(submit);await tester.pumpAndSettle();@@ -465,7 +463,6 @@ void main() {expect(find.text('Kens-Mini'), findsWidgets);await tester.tap(find.text('Kens-Mini').last);await tester.pumpAndSettle();- expect(notice, findsNothing);await tester.tap(find.text('Codex'));await tester.pumpAndSettle();await tester.tap(submit);@@ -500,6 +497,31 @@ void main() {await close(tester, c);});+ testWidgets(+ 'if the chosen machine leaves the Swarm while the dialog is open, Add Buddy turns off',+ (tester) async {+ final server = buddySwarm();+ final c = await show(tester, server);+ await open(tester);+ expect(tester.widget<FilledButton>(submit).onPressed, isNotNull);++ (server.state['machines'] as List).removeWhere(+ (m) => (m as Map)['machineId'] == 'ken-mac',+ );+ await c.refresh();+ await tester.pumpAndSettle();++ expect(+ find.text(+ 'A Buddy runs on one of your own machines. Add one of yours to this Swarm first.',+ ),+ findsOneWidget,+ );+ expect(tester.widget<FilledButton>(submit).onPressed, isNull);+ await close(tester, c);+ },+ );+testWidgets('a refusal shows in the dialog, which keeps the choices', (tester,) async {