Skip to content

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.

Fix Swarm lead startup and refine project navigation (#1471)

Deea20bc437fc5c
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index c0ed6cb02..1b71e1c3e 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -69,6 +69,113 @@ afterAll(async () => {
await replica?.stop()
})
+describe('deleting abandoned swarm projects', () => {
+ it('deletes the project through the API, fences stale requests, and replays only the deletion receipt', async () => {
+ const { tab } = await fixture()
+ const createId = randomUUID()
+ const create = { type: 'project.create' as const, name: 'Abandoned private project', visibility: 'private' as const, brief: '' }
+ const { projectId, conversationId } = (await run(tab, create, owner, undefined, createId)).result as { projectId: string; conversationId: string }
+ const group = String((await run(tab, { type: 'conversation.create', projectId, title: 'Offline work', brief: '', checks: [] })).result.conversationId)
+ const send = { ...message('Private unfinished draft'), conversationId: group } as Command
+ const sendId = randomUUID()
+ await run(tab, send, owner, undefined, sendId)
+ await run(tab, { type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId })
+ const deleteId = randomUUID(), command = { type: 'project.delete' as const, projectId }
+ const response = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`,
+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { operationId: deleteId, command } })
+ expect(response.statusCode).toBe(200)
+ expect(response.json().data.result).toEqual({})
+ expect(await run(tab, command, owner, undefined, deleteId)).toEqual(response.json().data)
+ const state = (await store.read(owner, tab)).state
+ expect(state.projects!.map(p => p.id)).toEqual(['lead'])
+ expect(state.conversations.map(c => c.id)).toEqual(['lead'])
+ expect(state.invitations).toEqual([])
+ for (const id of [conversationId, group]) {
+ await expect(store.messages(owner, tab, id, {})).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(store.attempts(owner, tab, id)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ }
+ await expect(run(tab, send, owner, undefined, sendId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(run(tab, create, owner, undefined, createId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(run(tab, { type: 'project.rename', projectId, name: 'Revived' })).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(run(tab, { type: 'agent.add', conversationId, machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Late lead', configuration: config, lead: true })).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ expect((await store.read(owner, tab)).state.projects!.map(p => p.id)).toEqual(['lead'])
+ })
+
+ it('allows an empty swarm and never assigns a deleted workgroup number again', async () => {
+ const tab = (await store.create(owner, randomUUID(), 'Empty swarm')).id
+ const old = (await run(tab, { type: 'conversation.create', title: 'Old work', brief: '', checks: [] })).result
+ await run(tab, { type: 'project.delete', projectId: 'lead' })
+ const empty = (await store.read(owner, tab)).state
+ expect(empty.projects).toEqual([])
+ expect(empty.conversations).toEqual([])
+ expect(empty.agents).toEqual([])
+ expect(empty.people).toHaveLength(1)
+ const projectId = String((await run(tab, { type: 'project.create', name: 'Fresh project', visibility: 'public', brief: '' })).result.projectId)
+ const next = (await run(tab, { type: 'conversation.create', projectId, title: 'Fresh work', brief: '', checks: [] })).result
+ expect(next.number).toBe(Number(old.number) + 1)
+ await expect(store.messages(owner, tab, String(old.conversationId), {})).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+
+ it('lets only the project owner delete it, and removal revokes receipt replay', async () => {
+ const { tab } = await fixture()
+ await invite(tab)
+ const publicId = String((await run(tab, { type: 'project.create', name: 'Peer project', visibility: 'public', brief: '' }, peer)).result.projectId)
+ const privateId = String((await run(tab, { type: 'project.create', name: 'Peer private project', visibility: 'private', brief: '' }, peer)).result.projectId)
+ await expect(run(tab, { type: 'project.delete', projectId: publicId })).rejects.toMatchObject({ code: 'PROJECT_OWNER_REQUIRED' })
+ await expect(run(tab, { type: 'project.delete', projectId: privateId })).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ const operationId = randomUUID(), command = { type: 'project.delete' as const, projectId: publicId }
+ const deleted = await run(tab, command, peer, undefined, operationId)
+ expect(await run(tab, command, peer, undefined, operationId)).toEqual(deleted)
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ await expect(run(tab, command, peer, undefined, operationId)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ })
+
+ it('refuses pending starts and prevents a failed start from joining after deletion', async () => {
+ const { tab } = await fixture()
+ const { projectId, conversationId } = (await run(tab, { type: 'project.create', name: 'Failed start', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }
+ const request = { conversationId, machineId: 'test-host', engine: 'codex', name: 'Builder', cwd: '/work', worktree: true,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
+ const startId = String((await run(tab, { type: 'agent.start', request })).result.startId)
+ await expect(run(tab, { type: 'project.delete', projectId })).rejects.toMatchObject({ code: 'STARTS_PENDING' })
+ await run(tab, { type: 'agent.startFailed', startId, error: 'The machine refused the prompt before launch.' })
+ await run(tab, { type: 'project.delete', projectId })
+ await expect(store.start(owner, tab, startId)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ await expect(run(tab, { type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+
+ it('does not erase a removed terminal’s private history restriction', async () => {
+ const { tab } = await fixture()
+ const { projectId, conversationId } = (await run(tab, { type: 'project.create', name: 'Private work', visibility: 'private', brief: '' })).result as { projectId: string; conversationId: string }
+ const harnessId = randomUUID()
+ const agentId = String((await run(tab, { type: 'agent.add', conversationId, machineId: 'test-host', harnessId,
+ name: 'Private lead', configuration: config, lead: true })).result.agentId)
+ const context = await store.native.open(owner, tab, { operationId: randomUUID(), conversationId, agentId })
+ await expect(run(tab, { type: 'project.delete', projectId })).rejects.toMatchObject({ code: 'PROJECT_HAS_AGENTS' })
+ await run(tab, { type: 'agent.remove', agentId })
+ await run(tab, { type: 'project.delete', projectId })
+ await expect(store.native.read(host, tab, context.contextId)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
+ expect(await store.mayObserve(owner, tab, 'test-host', harnessId, host.sub)).toBe(false)
+ await expect(run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId,
+ name: 'Moved lead', configuration: config, lead: false })).rejects.toMatchObject({ code: 'PROJECT_SESSION' })
+ })
+
+ it('serializes deletion against a late lead contribution', async () => {
+ const { tab } = await fixture()
+ const { projectId, conversationId } = (await run(tab, { type: 'project.create', name: 'Race', visibility: 'public', brief: '' })).result as { projectId: string; conversationId: string }
+ const results = await Promise.allSettled([
+ run(tab, { type: 'project.delete', projectId }),
+ run(tab, { type: 'agent.add', conversationId, machineId: 'test-host', harnessId: randomUUID(), name: 'Lead', configuration: config, lead: true }),
+ ])
+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1)
+ expect(results.filter(r => r.status === 'rejected')).toHaveLength(1)
+ const state = (await store.read(owner, tab)).state
+ const exists = state.projects!.some(p => p.id === projectId)
+ expect(state.agents.some(a => a.projectId === projectId)).toBe(exists)
+ expect(state.conversations.some(c => c.id === conversationId)).toBe(exists)
+ })
+})
+
describe('private swarm projects on the real control API', () => {
it('uses one contributed machine across projects with a separate authorized checkout for each', async () => {
const { tab } = await fixture()
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 69f66ee57..4b74ed63c 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,12 +1,12 @@
import { admitMachineStart, machineContribution } from './machines.js'
import { z } from 'zod'
import {
- activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations,
+ activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations, nextConversationNumber,
type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,
} from './model.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSchema } from './routingPolicy.js'
-import { agentProjectId, groupProject, manageProject, mutableProjects, projectMembers, projectOf, readAgent, readConversation, readProject, sameProject } from './projects.js'
+import { agentProjectId, deleteProject, groupProject, manageProject, mutableProjects, projectMembers, projectOf, readAgent, readConversation, readProject, sameProject } from './projects.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const title = z.string().trim().min(1).max(160)
@@ -48,6 +48,7 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),
z.object({ type: z.literal('project.create'), name: title, visibility: z.enum(['public', 'private']), brief: z.string().trim().max(8000).default('') }).strict(),
z.object({ type: z.literal('project.rename'), projectId: id, name: title }).strict(),
+ z.object({ type: z.literal('project.delete'), projectId: id }).strict(),
z.object({ type: z.literal('project.sharing'), projectId: id, visibility: z.enum(['public', 'private']), memberIds: z.array(id).max(200) }).strict(),
z.object({ type: z.literal('project.cadence'), projectId: id, minutes: z.union([z.literal(1), z.literal(5), z.literal(15), z.literal(30)]) }).strict(),
z.object({ type: z.literal('project.report'), projectId: id, throughRevision: z.number().int().nonnegative().safe(), text: text.nullable() }).strict(),
@@ -230,6 +231,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
project.name = command.name
break
}
+ case 'project.delete':
+ deleteProject(state, actor, command.projectId)
+ break
case 'project.sharing': {
const project = manageProject(state, actor, command.projectId)
project.members = projectMembers(state, command.memberIds)
@@ -269,11 +273,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
break
}
case 'tab.rename':
- controls(state, actor)
+ // Writable people manage the swarm even when its original project is
+ // gone. Agents retain the existing Lead-conversation authority.
+ if (actor.kind === 'agent') controls(state, actor)
state.name = command.name
break
case 'tab.pause':
- controls(state, actor)
+ if (actor.kind === 'agent') controls(state, actor)
state.paused = command.paused
break
case 'tab.routingPolicy':
@@ -290,7 +296,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
fail('BRIEF_REQUIRED', 'Delegated work needs a brief and acceptance checks.', 400)
}
const leadId = conversation(state, project.leadConversationId).leadId
- const number = Math.max(0, ...state.conversations.map(c => c.number ?? 0)) + 1
+ const number = nextConversationNumber(state)
state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),
number, title: command.title, leadId, agentIds: leadId ? [leadId] : [],
archived: false, brief: command.brief, assignment: null, lastMessageSequence: 0,
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 14e308926..0f31a4554 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -110,6 +110,8 @@ export interface SuperTabState {
people: Person[]
agents: Agent[]
conversations: Conversation[]
+ /** Deleting a project never makes its old # references name new work. */
+ retiredConversationNumber?: number
invitations: Invitation[]
starts?: AgentStart[]
machines?: import('./machines.js').ContributedMachine[]
@@ -165,12 +167,15 @@ export function conversation(state: SuperTabState, id: string): Conversation {
/** Legacy groups keep their append order, including archived groups. Persisted
* numbers are never reassigned; the store serializes concurrent additions. */
export function numberConversations(state: SuperTabState): void {
- let next = Math.max(0, ...state.conversations.map(c => c.number ?? 0)) + 1
+ let next = nextConversationNumber(state)
const leads = new Set(projectsOf(state).map(p => p.leadConversationId))
for (const group of state.conversations) {
if (!leads.has(group.id) && group.number == null) group.number = next++
}
}
+export function nextConversationNumber(state: SuperTabState): number {
+ return Math.max(state.retiredConversationNumber ?? 0, 0, ...state.conversations.map(c => c.number ?? 0)) + 1
+}
export function author(state: SuperTabState, actor: Actor, write = false): Author {
if (actor.kind === 'person') {
const member = person(state, actor.userId)
@@ -200,6 +205,7 @@ export function visibleState(state: SuperTabState, actor: Actor): SuperTabState
const visible = structuredClone(state)
delete visible.sharing
numberConversations(visible)
+ delete visible.retiredConversationNumber
if (visible.projects) {
visible.projects = visible.projects.filter(p => canReadProject(state, actor, p))
visible.conversations = visible.conversations.filter(c => canReadProject(state, actor, groupProject(state, c)))
diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.ts
index 2693e7027..0038a2646 100644
--- a/backend/src/superTabs/projects.test.ts
+++ b/backend/src/superTabs/projects.test.ts
@@ -83,4 +83,120 @@ describe('projects inside an invite-only swarm', () => {
expect(projectsOf(f.state).map(p => p.updateMinutes)).toEqual([5, 15])
expect(() => f.run({ type: 'project.cadence', projectId: p.projectId, minutes: 1 }, peer)).toThrow('unavailable')
})
+
+ it('deletes an empty legacy project without recreating a fallback or reusing its workgroup numbers', () => {
+ const f = setup()
+ const old = f.run({ type: 'conversation.create', title: 'Abandoned', brief: '', checks: [] })
+ f.state.project = { machineId: 'machine', cwd: '/old', repositoryUrl: null }
+ const machine = { machineId: 'old', name: 'Old', contributorId: 'owner', membershipGeneration: 'swarm',
+ generation: 'g', cwd: '/old', engines: ['codex'], maxAgents: 2, paused: false }
+ f.state.machines = [machine, { ...machine, machineId: 'shared', scope: 'swarm' }]
+ f.run({ type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' })
+ expect(f.run({ type: 'project.delete', projectId: 'lead' })).toEqual({})
+ expect(projectsOf(f.state)).toEqual([])
+ expect(f.state.conversations).toEqual([])
+ expect(f.state.invitations).toEqual([])
+ expect(f.state.project).toBeUndefined()
+ expect(f.state.machines?.map(m => m.machineId)).toEqual(['shared'])
+ expect(f.state.people).toHaveLength(2)
+ expect(visibleState(f.state, owner)).not.toHaveProperty('retiredConversationNumber')
+ expect(() => readConversation(f.state, owner, 'lead')).toThrow('unavailable')
+ const p = f.project('public')
+ const next = f.run({ type: 'conversation.create', projectId: p.projectId, title: 'New work', brief: '', checks: [] })
+ expect(next.number).toBe(Number(old.number) + 1)
+ expect(f.state.conversations.map(c => c.id)).not.toContain(old.conversationId)
+ })
+
+ it('requires the project owner and preserves private-project boundaries during deletion', () => {
+ const f = setup(), publicProject = f.project('public', peer), privateProject = f.project('private', peer)
+ expect(() => f.run({ type: 'project.delete', projectId: publicProject.projectId })).toThrow('Only the project owner')
+ expect(() => f.run({ type: 'project.delete', projectId: privateProject.projectId })).toThrow('unavailable')
+ f.state.people.find(p => p.id === 'peer')!.role = 'viewer'
+ expect(() => f.run({ type: 'project.delete', projectId: publicProject.projectId }, peer)).toThrow('read-only')
+ f.state.people.find(p => p.id === 'peer')!.role = 'collaborator'
+ f.run({ type: 'project.delete', projectId: publicProject.projectId }, peer)
+ expect(projectsOf(f.state).map(p => p.id)).toEqual(['lead', privateProject.projectId])
+ })
+
+ it('lets a person unpause an empty swarm and create its next project', () => {
+ const f = setup()
+ f.run({ type: 'tab.pause', paused: true })
+ f.run({ type: 'project.delete', projectId: 'lead' })
+ expect(projectsOf(f.state)).toEqual([])
+ expect(() => f.project()).toThrow('paused')
+ f.run({ type: 'tab.pause', paused: false }, peer)
+ const next = f.project('public')
+ expect(projectsOf(f.state).map(p => p.id)).toEqual([next.projectId])
+ })
+
+ it('keeps human swarm controls separate from private projects and rejects viewers', () => {
+ const f = setup(), privateProject = f.project('private', peer)
+ f.run({ type: 'project.delete', projectId: 'lead' })
+ f.run({ type: 'tab.rename', name: 'Renamed swarm' })
+ f.run({ type: 'tab.pause', paused: true })
+ expect(f.state.name).toBe('Renamed swarm')
+ expect(visibleState(f.state, owner).projects).toEqual([])
+ expect(() => readConversation(f.state, owner, privateProject.conversationId)).toThrow('unavailable')
+ f.state.people.find(p => p.id === 'peer')!.role = 'viewer'
+ expect(() => f.run({ type: 'tab.rename', name: 'Forbidden' }, peer)).toThrow('read-only')
+ expect(() => f.run({ type: 'tab.pause', paused: false }, peer)).toThrow('read-only')
+ expect(f.state.name).toBe('Renamed swarm')
+ expect(f.state.paused).toBe(true)
+ })
+
+ it('does not grant swarm controls to another project’s agent when the original Lead is deleted', () => {
+ const f = setup(), p = f.project()
+ const leadId = f.add('lead', 'original-lead'), workerId = f.add('lead', 'worker', false)
+ const otherId = f.add(p.conversationId, 'other-lead')
+ const actor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host' })
+ f.run({ type: 'tab.rename', name: 'Lead renamed' }, actor(leadId))
+ f.run({ type: 'tab.pause', paused: true }, actor(leadId))
+ for (const command of [{ type: 'tab.rename', name: 'Forbidden' }, { type: 'tab.pause', paused: false }] as Command[]) {
+ expect(() => f.run(command, actor(workerId))).toThrow('coordinating lead')
+ expect(() => f.run(command, actor(otherId))).toThrow('unavailable')
+ }
+ f.run({ type: 'agent.remove', agentId: leadId })
+ f.run({ type: 'agent.remove', agentId: workerId })
+ f.run({ type: 'project.delete', projectId: 'lead' })
+ expect(() => f.run({ type: 'tab.rename', name: 'Forbidden' }, actor(otherId))).toThrow('unavailable')
+ expect(() => f.run({ type: 'tab.pause', paused: false }, actor(otherId))).toThrow('unavailable')
+ f.run({ type: 'tab.pause', paused: false })
+ expect(f.state.name).toBe('Lead renamed')
+ })
+
+ it('refuses any project agent, even after it leaves every workgroup', () => {
+ const f = setup(), p = f.project(), agentId = f.add(p.conversationId, 'idle')
+ f.run({ type: 'conversation.agent', conversationId: p.conversationId, agentId, present: false, lead: false })
+ expect(() => f.run({ type: 'project.delete', projectId: p.projectId })).toThrow('Stop and remove')
+ f.run({ type: 'agent.remove', agentId })
+ f.run({ type: 'project.delete', projectId: p.projectId })
+ expect(projectsOf(f.state).map(p => p.id)).toEqual(['lead'])
+ })
+
+ it.each(['queued', 'dispatched', 'settling'] as const)('refuses %s starts and removes only settled project history', phase => {
+ const f = setup(), p = f.project()
+ const request = { conversationId: p.conversationId, machineId: 'machine', engine: 'codex', name: 'Builder',
+ cwd: '/work', worktree: true,
+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }
+ const startId = String(f.run({ type: 'agent.start', request }).startId)
+ const start = f.state.starts!.find(s => s.id === startId)!
+ start.dispatched = phase !== 'queued'
+ if (phase === 'settling') { start.poolGeneration = 'pool'; start.harnessId = 'native'; start.poolSettled = false }
+ expect(() => f.run({ type: 'project.delete', projectId: p.projectId })).toThrow('pending agent starts')
+ if (phase === 'settling') start.poolSettled = true
+ else f.run({ type: 'agent.startFailed', startId, error: 'The machine confirmed nothing started.' })
+ f.run({ type: 'project.delete', projectId: p.projectId })
+ expect(f.state.starts).toEqual([])
+ expect(() => f.run({ type: 'agent.started', startId, harnessId: 'late', configuration })).toThrow('unavailable')
+ })
+
+ it('keeps active work visible after its contributed agent is removed', () => {
+ const f = setup(), p = f.project(), agentId = f.add(p.conversationId, 'worker')
+ f.run({ type: 'work.define', conversationId: p.conversationId, brief: 'Finish the task',
+ checks: [{ description: 'Verified', independent: false }] })
+ f.run({ type: 'work.assign', conversationId: p.conversationId, agentId })
+ f.run({ type: 'agent.remove', agentId })
+ expect(() => f.run({ type: 'project.delete', projectId: p.projectId })).toThrow('active work')
+ expect(readConversation(f.state, owner, p.conversationId).assignment?.status).toBe('reconciling')
+ })
})
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 15322f55e..7e9692271 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -1,4 +1,4 @@
-import { agent, author, conversation, fail, person, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'
+import { activeWork, agent, author, conversation, fail, nextConversationNumber, person, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'
export type ProjectVisibility = 'public' | 'private'
export interface SwarmProject {
@@ -91,12 +91,37 @@ export function manageProject(state: SuperTabState, actor: Actor, projectId: str
const project = readProject(state, actor, projectId)
author(state, actor, true)
if (actor.kind !== 'person' || actor.userId !== project.ownerId) {
- fail('PROJECT_OWNER_REQUIRED', 'Only the project owner can change its sharing.', 403)
+ fail('PROJECT_OWNER_REQUIRED', 'Only the project owner can manage this project.', 403)
}
mutableProjects(state)
return projectOf(state, projectId)
}
+/** Removes coordination only. Native sessions and pending starts must be
+ * reconciled first; their terminal-history privacy bindings remain permanent. */
+export function deleteProject(state: SuperTabState, actor: Actor, projectId: string): void {
+ const project = manageProject(state, actor, projectId)
+ const groups = state.conversations.filter(c => groupProject(state, c).id === project.id)
+ const groupIds = new Set(groups.map(c => c.id))
+ if (state.agents.some(a => agentProjectId(state, a) === project.id)) {
+ fail('PROJECT_HAS_AGENTS', 'Stop and remove this project’s agents before deleting it.')
+ }
+ if (state.starts?.some(s => groupIds.has(s.request.conversationId) && !s.error &&
+ (!s.harnessId || s.poolGeneration && !s.poolSettled))) {
+ fail('STARTS_PENDING', 'Resolve this project’s pending agent starts before deleting it.')
+ }
+ if (groups.some(activeWork)) fail('WORK_ACTIVE', 'Resolve this project’s active work before deleting it.')
+ state.retiredConversationNumber = nextConversationNumber(state) - 1
+ state.projects = state.projects!.filter(p => p.id !== project.id)
+ state.conversations = state.conversations.filter(c => !groupIds.has(c.id))
+ state.starts = state.starts?.filter(s => !groupIds.has(s.request.conversationId))
+ state.invitations = state.invitations.filter(i => !groupIds.has(i.conversationId))
+ if (project.id === 'lead') {
+ delete state.project
+ state.machines = state.machines?.filter(m => m.scope === 'swarm')
+ }
+}
+
/** Capture current swarm membership so leaving and rejoining does not restore
* an old private-project invitation. */
export function projectMembers(state: SuperTabState, ids: string[]) {
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 93a98f5ad..bf35b7900 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -304,9 +304,10 @@ export class SuperTabStore {
// A leave may be retried by its original author. Nothing except that operation's receipt is returned.
const selfLeave = actor.kind === 'person' && command.type === 'member.remove' && command.userId === actor.userId
if (!selfLeave) {
- if (command.type === 'agent.remove' && !original.agents.some(a => a.id === command.agentId)) {
+ if (command.type === 'agent.remove' && !original.agents.some(a => a.id === command.agentId) ||
+ command.type === 'project.delete' && !projectsOf(original).some(p => p.id === command.projectId)) {
// Retrying one's own completed removal returns only its empty
- // receipt. The removed agent no longer exists to authorize against.
+ // receipt. The removed object no longer exists to authorize against.
author(original, actor, true)
} else {
authorizeCommandAccess(original, actor, command)
@@ -321,6 +322,10 @@ export class SuperTabStore {
readConversation(original, actor, decision.conversationId)
}
}
+ if (command.type === 'project.create' &&
+ !projectsOf(original).some(p => p.id === (prior.result as Record<string, unknown>).projectId)) {
+ fail('NOT_FOUND', 'This project was deleted. Create a new project.', 404)
+ }
return { revision: prior.revision, result: prior.result }
}
if (command.type !== 'invite.accept') author(original, actor)
@@ -379,6 +384,13 @@ export class SuperTabStore {
await makeProjectPrivate(tx, effects.state, command.projectId)
}
await revokeNativeContexts(tx, original, effects.state)
+ const removedGroups = original.conversations.filter(c => !effects.state.conversations.some(n => n.id === c.id))
+ if (removedGroups.length) {
+ // Keep immutable history and operation receipts for audit/replay; all
+ // reads require a live conversation. No removed group can deliver work.
+ await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: { in: removedGroups.map(c => c.id) },
+ status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })
+ }
const revision = row.revision + 1
if (command.type === 'agent.add' || command.type === 'agent.started' || command.type === 'agent.configuration') {
for (const target of effects.state.agents) {
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index c3b4af503..e8403576d 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -7862,11 +7862,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
SwarmDestination(
id: 'command:$_closedSuperTabCommand${tab.id}',
title: tab.name,
- detail: 'Closed Swarms',
+ detail: 'Recent Swarms',
swarmId: null,
current: false,
commandId: '$_closedSuperTabCommand${tab.id}',
- searchFields: ['closed', 'reopen', 'super tab'],
+ searchFields: ['recent', 'closed', 'reopen', 'super tab'],
),
if (_canExecuteCommand('app.settings'))
for (final group in settingsGroups)
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index f8b96902a..2bd1d0c7e 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1948,17 +1948,41 @@ class AppNotifier extends ChangeNotifier {
Future<Agent> recoverSuperTabCreation(
String machineId,
- String creationId,
- ) async {
- final revision = _authRevision;
- final result = await _conn(machineId).request(
+ String creationId, {
+ bool cancelIfMissing = false,
+ }) async {
+ final revision = _authRevision, account = currentUser?.id;
+ var result = await _conn(machineId).request(
'agent_create_status',
payload: {'creationId': creationId},
timeout: const Duration(seconds: 10),
);
- if (!_authWorkCurrent(revision)) {
+ if (!_authWorkCurrent(revision) || currentUser?.id != account) {
throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
}
+ // Older Swarm bootstraps exceeded the native prompt limit, which rejects
+ // before writing a receipt. Fence that exact missing intent durably before
+ // allowing a retry; an uncertain/mismatched response must stay locked.
+ if (cancelIfMissing &&
+ result['creationId'] == creationId &&
+ result['state'] == 'missing') {
+ result = await _conn(machineId).request(
+ 'agent_create_cancel',
+ payload: {'creationId': creationId},
+ timeout: const Duration(seconds: 10),
+ );
+ if (!_authWorkCurrent(revision) || currentUser?.id != account) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ }
+ if (cancelIfMissing &&
+ result['creationId'] == creationId &&
+ result['state'] == 'cancelled') {
+ throw const SuperTabFailure(
+ 'CREATION_FAILED',
+ 'The previous startup request was cancelled. Try again to start this project.',
+ );
+ }
if (result['creationId'] == creationId && result['state'] == 'failed') {
final failure = result['failure'] is Map
? result['failure'] as Map
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index cc8d21835..07907037b 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -16,8 +16,11 @@ class HarnessLaunchIntegration {
this.actionLabel = 'New Harness',
this.projectVisibility,
this.projectVisibilityLocked = false,
+ this.initialTask,
});
final String creationId, actionLabel;
+ // Restores the person's original request from a destination launch journal.
+ final String? initialTask;
String? projectVisibility;
bool projectVisibilityLocked;
final Future<String> Function(String machineId, String task) prepare;
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 748224771..c8a7bff1a 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -479,7 +479,7 @@ class NewHarnessController extends ChangeNotifier {
: _autoProject
? _generatedProject()
: const NewHarnessProject.fresh();
- if (task != null) this.task = task;
+ this.task = this.integration?.initialTask ?? task ?? '';
_worktree = draft?.worktree;
_recoveredWorktreePreference = draft?.worktreePreference;
_branchRef = draft?.branchRef;
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index 7bddc4ae7..7257c90aa 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
+import '../core/first_task.dart';
import '../core/models.dart';
import '../state/app_state.dart';
import '../state/harness_attachments.dart';
@@ -7,6 +8,7 @@ import '../state/harness_launch_integration.dart';
import '../state/swarm.dart';
import 'controller.dart';
import 'model.dart';
+import 'launch_prompt.dart';
/// Captures a conversation before opening New Harness. Its journal survives a
/// closed form or process; a recovered launch only reads the native receipt.
@@ -56,6 +58,7 @@ class SuperTabLaunch {
late final HarnessLaunchIntegration integration;
integration = HarnessLaunchIntegration(
creationId: saved['creationId'] as String? ?? superTabOperationId(),
+ initialTask: saved['initialMessage'] as String?,
actionLabel: saved['newProject'] == true
? 'New Project'
: saved['lead'] == true
@@ -191,28 +194,32 @@ class SuperTabLaunch {
await persist();
}
app.superTabs.deferTabDiscovery(saved['tabId'] as String);
- final command = 'harness super-tab --tab ${saved['tabId']}';
- final prompt =
- 'You are an agent in a Harness Swarm. '
- '${saved['lead'] == true ? 'You are this project’s coordinating lead. Start by discussing the person’s request; build after they authorize it.' : 'Join the conversation before beginning the person’s request.'}\n'
- 'First run `$command status`. Registration may still be finishing: if it reports AGENT_UNAVAILABLE, wait briefly and retry. '
- 'Do not start work or post until it confirms your participation.\n'
- 'Read the conversation: `$command messages ${saved['conversationId']}`. '
- 'Post explanations, questions and results with `$command post ${saved['conversationId']} "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '
- 'Reuse that operation ID and exact message after a lost reply. Your native terminal is not the shared conversation.\n'
- 'If sandbox restrictions block this local Harness command, request permission to run it outside the sandbox. '
- 'For work groups, assignments, acceptance evidence and messages to other agents, use `$command help`. '
- '${saved['lead'] == true ? 'Before starting or assigning work, run `$command route GROUP JSON` with your difficulty and risk assessment, then start or assign its pick with the routeDecisionId it returns. To choose otherwise, pass overrideReason. If it answers NO_CANDIDATE, tell the person in the group why, using its reasons; do not guess another machine. ' : ''}'
- 'Use a group for an independently assignable outcome with acceptance checks. Reuse existing groups and agents. '
- 'Engine-native helper subagents do not need a group. Questions stay in the conversation where the work happens. '
- 'Write to the people in this tab like a helpful colleague. Answer first, in plain words and in the language they used. '
- 'Keep it short: a few sentences, under about 150 words, unless they ask for detail. '
- 'Do not show commands, message or sequence ids, field names or error codes. '
- 'Do not describe your own tools or permission prompts unless that blocks what they asked. '
- 'Answer each message once: post with --reply-to MESSAGE_ID. If you have already answered a message, do not post again. '
- 'When you hand over finished work, give the result with the revision and links they need.\n\n'
- '${saved['lead'] == true ? 'Keep people informed in your project Lead conversation ${saved['conversationId']}: explain your plan, substantive progress, blockers and next steps. Consolidate new workgroup reports about every five minutes while active; the project setting controls scheduled requests. Answer human questions, serious blockers and completion immediately. A scheduled update request tells you which reports are new; read them and use project.report to post one useful update, or acknowledge with text:null when nothing merits repeating. Do not run an extra summarizer over every terminal turn. Workgroups you create belong to your project; each project has separate agent sessions. ' : ''}'
- 'The person’s request:\n${task.isEmpty ? 'Ask what they would like to work on.' : task}';
+ // Revalidate a journal's destination before native submission. A project
+ // deleted on another computer must not leave an unattached native session.
+ final current = await app.superTabs.map(
+ 'GET',
+ '/api/super-tabs/${saved['tabId']}',
+ );
+ checkAccount();
+ final groups =
+ superTabMap(current['state'])['conversations'] as List? ?? const [];
+ if (!groups.any((g) => (g as Map)['id'] == saved['conversationId'])) {
+ if (saved['phase'] != 'starting' && saved['phase'] != 'joining') {
+ // Nothing can still be starting: reopening New Project should get a
+ // fresh destination instead of loading this deleted project forever.
+ await app.superTabs.storage.delete(key);
+ checkAccount();
+ }
+ throw const SuperTabFailure(
+ 'PROJECT_UNAVAILABLE',
+ 'This project is no longer available. Close this form and create a new project.',
+ );
+ }
+ final prompt = superTabLaunchPrompt(
+ tabId: saved['tabId'] as String,
+ conversationId: saved['conversationId'] as String,
+ lead: saved['lead'] == true,
+ );
saved['launchPrompt'] = prompt;
await persist();
return prompt;
@@ -369,6 +376,11 @@ class SuperTabLaunch {
final native = await app.recoverSuperTabCreation(
machine,
saved['creationId'] as String,
+ cancelIfMissing:
+ saved['phase'] == 'starting' &&
+ (saved['launchPrompt'] as String? ?? '').trim().length >
+ kFirstTaskMaxLength &&
+ (saved['files'] as List? ?? const []).isEmpty,
);
await complete(machine, native.id, recovered: native);
}
diff --git a/desktop/lib/super_tabs/launch_prompt.dart b/desktop/lib/super_tabs/launch_prompt.dart
new file mode 100644
index 000000000..fe5b936c1
--- /dev/null
+++ b/desktop/lib/super_tabs/launch_prompt.dart
@@ -0,0 +1,20 @@
+/// Native creation accepts at most 2,000 UTF-16 code units. Keep the bootstrap
+/// bounded independently of the person's request, which agent.add commits to
+/// this exact conversation before status confirms registration.
+String superTabLaunchPrompt({
+ required String tabId,
+ required String conversationId,
+ required bool lead,
+}) =>
+ 'Harness Swarm agent. '
+ '${lead ? 'You are the project lead. Discuss first; build when authorized. ' : ''}'
+ 'Use `harness super-tab --tab $tabId` with the subcommands below. '
+ 'First: `status`. Retry AGENT_UNAVAILABLE briefly until registered; do not work or post before registration. '
+ 'Read `messages $conversationId` for the full human request; if empty, ask what they want to work on. '
+ 'Reply there using `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '
+ 'Use --reply-to for existing messages; answer each message once, do not post again. Retry a lost reply with the exact same operation ID and text. '
+ 'Terminal output is not shared chat. If sandbox restrictions block this command, request permission. Use `help` for syntax. '
+ '${lead ? 'Before starting or assigning work, use `route GROUP JSON` with difficulty/risk; use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}'
+ 'Reuse agents and groups. Each group needs an assignable outcome and acceptance checks; native helper agents need no group. '
+ 'Write like a helpful colleague: answer first, in their language, under about 150 words unless asked for detail. Hide commands, internal IDs and field names. Give results with useful revision/links. '
+ '${lead ? 'Keep the Lead chat informed: plan, substantive progress, blockers, next steps. Consolidate workgroup reports every five minutes, following project cadence. Answer questions, serious blockers and completion immediately. On scheduled requests read new reports; use project.report for one update or text:null if nothing new. No per-turn summarizer. Keep workgroups and sessions scoped to this project.' : ''}';
diff --git a/desktop/lib/super_tabs/project_options.dart b/desktop/lib/super_tabs/project_options.dart
index 3d3d538d8..7026c4a18 100644
--- a/desktop/lib/super_tabs/project_options.dart
+++ b/desktop/lib/super_tabs/project_options.dart
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../widgets/desktop_chrome.dart';
import 'controller.dart';
@@ -13,6 +14,10 @@ Future<void> showProjectAction(
SuperTabProject project,
String action,
) async {
+ if (action == 'delete') {
+ await _deleteProject(context, c, project);
+ return;
+ }
var name = project.name;
var visibility = project.isPrivate ? 'private' : 'public';
final members = project.memberIds.toSet();
@@ -210,3 +215,101 @@ Future<void> showProjectAction(
),
);
}
+
+Future<void> _deleteProject(
+ BuildContext context,
+ SuperTabController c,
+ SuperTabProject project,
+) async {
+ var busy = false;
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ // A confirmed deletion removes this project before command() returns.
+ // Keep the account fence while allowing its original receipt to settle.
+ child: StatefulBuilder(
+ builder: (context, update) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final current = c.snapshot?.projects
+ .where((p) => p.id == project.id)
+ .firstOrNull;
+ final pending = c.pendingCommand;
+ final checking =
+ pending?['type'] == 'project.delete' &&
+ pending?['projectId'] == project.id;
+ final available = current != null || checking;
+ final canDelete =
+ !busy &&
+ !c.saving &&
+ c.canWrite &&
+ (checking ||
+ !c.hasPendingAction && current?.ownerId == c.accountId);
+ return PopScope(
+ canPop: !busy,
+ child: AlertDialog(
+ title: Text(
+ available ? 'Delete Project?' : 'Project unavailable',
+ ),
+ content: SizedBox(
+ width: 400,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ available
+ ? '“${current?.name ?? project.name}” and all of its conversations will be permanently deleted. This can’t be undone.'
+ : 'This project is no longer available.',
+ style: DesktopChrome.text(),
+ ),
+ if (c.operationError != null && available) ...[
+ const SizedBox(height: 12),
+ Text(
+ c.operationError!,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ autofocus: true,
+ onPressed: busy ? null : () => Navigator.pop(context),
+ child: Text(available && !checking ? 'Cancel' : 'Close'),
+ ),
+ if (available)
+ FilledButton(
+ style: grid.dangerButtonStyle(),
+ onPressed: !canDelete
+ ? null
+ : () async {
+ update(() => busy = true);
+ final result = checking
+ ? await c.retry()
+ : await c.command({
+ 'type': 'project.delete',
+ 'projectId': project.id,
+ });
+ if (!context.mounted) return;
+ if (result != null) {
+ Navigator.pop(context);
+ } else {
+ update(() => busy = false);
+ }
+ },
+ child: Text(checking ? 'Retry' : 'Delete Project'),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index 0875f120f..c4c42d4e5 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_icon_button.dart';
import '../widgets/desktop_chrome.dart';
import 'controller.dart';
import 'model.dart';
@@ -34,37 +33,54 @@ class ProjectSidebar extends StatelessWidget {
project != null &&
groups.any((g) => g.id != project.leadConversationId);
return Padding(
- padding: EdgeInsets.only(left: project == null ? 40 : 0, bottom: 2),
+ padding: const EdgeInsets.only(bottom: 2),
child: Material(
color: selected ? grid.AppSurface.selectedFill : Colors.transparent,
borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
clipBehavior: Clip.antiAlias,
- child: Row(
- children: [
- if (project != null && hasChildren)
- AppIconButton(
- key: ValueKey('super-project-expand-${project.id}'),
- icon: expanded ? AppIcons.chevronDown : AppIcons.chevronRight,
- tooltip: '${expanded ? 'Collapse' : 'Expand'} ${project.name}',
- onPressed: () => controller.toggleProject(project.id),
- )
- else if (project != null)
- const SizedBox(width: 32),
- Expanded(
- child: Semantics(
- label: project?.isPrivate == true ? 'Private project' : null,
- selected: selected,
- child: Tooltip(
- message: project?.name ?? group.label,
- child: InkWell(
- key: ValueKey('super-group-${group.id}'),
- onTap: () => onSelect(group.id),
- hoverColor: grid.AppSurface.hoverFill,
+ child: InkWell(
+ key: ValueKey('super-group-${group.id}'),
+ onTap: () => onSelect(group.id),
+ hoverColor: grid.AppSurface.hoverFill,
+ focusColor: grid.AppSurface.hoverFill,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ child: Row(
+ children: [
+ if (project != null && hasChildren)
+ IconButton(
+ key: ValueKey('super-project-expand-${project.id}'),
+ icon: Icon(
+ expanded ? AppIcons.chevronDown : AppIcons.chevronRight,
+ size: AppIcons.inlineSize,
+ ),
+ color: DesktopChrome.muted,
+ // The row owns hover/press feedback. Keep the themed focus
+ // boundary for this independent disclosure action.
+ style: const ButtonStyle(
+ minimumSize: WidgetStatePropertyAll(Size.square(32)),
+ padding: WidgetStatePropertyAll(EdgeInsets.all(6)),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ visualDensity: VisualDensity.standard,
+ overlayColor: WidgetStatePropertyAll(Colors.transparent),
+ backgroundColor: WidgetStatePropertyAll(Colors.transparent),
+ ),
+ tooltip:
+ '${expanded ? 'Collapse' : 'Expand'} ${project.name}',
+ onPressed: () => controller.toggleProject(project.id),
+ )
+ else if (project != null)
+ const SizedBox(width: 32),
+ Expanded(
+ child: Semantics(
+ label: project?.isPrivate == true ? 'Private project' : null,
+ selected: selected,
+ child: Tooltip(
+ message: project?.name ?? group.label,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 36),
child: Padding(
padding: EdgeInsets.fromLTRB(
- project == null ? 12 : 4,
+ project == null ? 44 : 4,
8,
12,
8,
@@ -125,8 +141,8 @@ class ProjectSidebar extends StatelessWidget {
),
),
),
- ),
- ],
+ ],
+ ),
),
),
);
@@ -140,20 +156,36 @@ class ProjectSidebar extends StatelessWidget {
child: Column(
children: [
Padding(
- padding: const EdgeInsets.fromLTRB(16, 18, 16, 12),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- 'Projects',
- style: DesktopChrome.metadata().copyWith(
- fontWeight: FontWeight.w600,
+ padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
+ child: OutlinedButton(
+ key: const ValueKey('super-new-project'),
+ onPressed: controller.canWrite ? onNewProject : null,
+ style: OutlinedButton.styleFrom(
+ foregroundColor: DesktopChrome.muted,
+ backgroundColor: Colors.transparent,
+ disabledBackgroundColor: Colors.transparent,
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 10,
),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ textStyle: DesktopChrome.control(),
+ ),
+ child: const Row(
+ children: [
+ Icon(AppIcons.plus, size: 16),
+ SizedBox(width: 8),
+ Flexible(child: Text('New Project')),
+ ],
),
),
),
Expanded(
child: ListView(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ padding: const EdgeInsets.all(8),
children: [
for (final project
in snapshot?.projects ?? const <SuperTabProject>[])
@@ -174,35 +206,6 @@ class ProjectSidebar extends StatelessWidget {
],
),
),
- Padding(
- padding: const EdgeInsets.fromLTRB(8, 8, 8, 16),
- child: TextButton(
- key: const ValueKey('super-new-project'),
- onPressed: controller.canWrite ? onNewProject : null,
- style: TextButton.styleFrom(
- foregroundColor: DesktopChrome.muted,
- backgroundColor: Colors.transparent,
- disabledBackgroundColor: Colors.transparent,
- alignment: Alignment.centerLeft,
- side: BorderSide.none,
- padding: const EdgeInsets.symmetric(
- horizontal: 12,
- vertical: 10,
- ),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
- ),
- textStyle: DesktopChrome.control(),
- ),
- child: const Row(
- children: [
- Icon(AppIcons.plus, size: 16),
- SizedBox(width: 8),
- Flexible(child: Text('New Project')),
- ],
- ),
- ),
- ),
],
),
);
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 092cc5864..b4c3a78dc 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -655,7 +655,9 @@ class _SuperTabViewState extends State<SuperTabView> {
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
child: Text(
group == null
- ? 'Choose a project'
+ ? c.snapshot?.projects.isEmpty == true
+ ? c.snapshot!.name
+ : 'Choose a project'
: c.snapshot!.isProjectLead(group.id)
? c.snapshot!.projectFor(group.id)!.name
: group.label,
@@ -665,56 +667,58 @@ class _SuperTabViewState extends State<SuperTabView> {
),
),
),
- AppIconButton(
- key: const ValueKey('super-chat'),
- icon: AppIcons.messageSquare,
- size: AppIcons.inlineSize,
- tooltip: 'Chat',
- selected: !_terminalsVisible && !_showPullRequests,
- color: !_terminalsVisible && !_showPullRequests
- ? DesktopChrome.foreground
- : DesktopChrome.muted,
- onPressed: () {
- setState(() => _showPullRequests = false);
- widget.onCloseTerminal?.call();
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _focus.requestFocus();
- });
- },
- ),
- const SizedBox(width: 4),
- AppIconButton(
- key: const ValueKey('super-terminals'),
- icon: AppIcons.terminal,
- size: AppIcons.inlineSize,
- tooltip: 'Group terminals (${group?.agentIds.length ?? 0})',
- selected: _terminalsVisible,
- color: _terminalsVisible
- ? DesktopChrome.foreground
- : DesktopChrome.muted,
- onPressed: group?.agentIds.isNotEmpty == true
- ? () {
- setState(() => _showPullRequests = false);
- widget.onOpenGroupTerminals?.call();
- }
- : null,
- ),
- const SizedBox(width: 4),
- AppIconButton(
- key: const ValueKey('super-pull-requests'),
- icon: AppIcons.gitPullRequest,
- size: AppIcons.inlineSize,
- tooltip: 'Pull requests',
- selected: !_terminalsVisible && _showPullRequests,
- color: !_terminalsVisible && _showPullRequests
- ? DesktopChrome.foreground
- : DesktopChrome.muted,
- onPressed: () {
- widget.onCloseTerminal?.call();
- setState(() => _showPullRequests = true);
- },
- ),
- if (group != null) _options(group),
+ if (group != null) ...[
+ AppIconButton(
+ key: const ValueKey('super-chat'),
+ icon: AppIcons.messageSquare,
+ size: AppIcons.inlineSize,
+ tooltip: 'Chat',
+ selected: !_terminalsVisible && !_showPullRequests,
+ color: !_terminalsVisible && !_showPullRequests
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ onPressed: () {
+ setState(() => _showPullRequests = false);
+ widget.onCloseTerminal?.call();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focus.requestFocus();
+ });
+ },
+ ),
+ const SizedBox(width: 4),
+ AppIconButton(
+ key: const ValueKey('super-terminals'),
+ icon: AppIcons.terminal,
+ size: AppIcons.inlineSize,
+ tooltip: 'Group terminals (${group.agentIds.length})',
+ selected: _terminalsVisible,
+ color: _terminalsVisible
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ onPressed: group.agentIds.isNotEmpty
+ ? () {
+ setState(() => _showPullRequests = false);
+ widget.onOpenGroupTerminals?.call();
+ }
+ : null,
+ ),
+ const SizedBox(width: 4),
+ AppIconButton(
+ key: const ValueKey('super-pull-requests'),
+ icon: AppIcons.gitPullRequest,
+ size: AppIcons.inlineSize,
+ tooltip: 'Pull requests',
+ selected: !_terminalsVisible && _showPullRequests,
+ color: !_terminalsVisible && _showPullRequests
+ ? DesktopChrome.foreground
+ : DesktopChrome.muted,
+ onPressed: () {
+ widget.onCloseTerminal?.call();
+ setState(() => _showPullRequests = true);
+ },
+ ),
+ _options(group),
+ ],
if (!showRoster)
AppIconButton(
icon: AppIcons.users,
@@ -756,6 +760,8 @@ class _SuperTabViewState extends State<SuperTabView> {
if (editable)
item('Update cadence', () => _groupAction('cadence', group)),
item('Swarm routing', () => _groupAction('routing', group)),
+ if (editable && project?.ownerId == c.accountId)
+ item('Delete Project', () => _groupAction('delete', group)),
] else ...[
item('Work details', () => _groupAction('work', group)),
if (editable) ...[
@@ -977,6 +983,31 @@ class _SuperTabViewState extends State<SuperTabView> {
);
Widget _conversation(bool narrow) {
+ if (c.snapshot?.projects.isEmpty == true && !c.accessRevoked) {
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ 'Create a project to get started.',
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ if (c.operationError != null) ...[
+ const SizedBox(height: 12),
+ Text(c.operationError!, style: DesktopChrome.metadata()),
+ ],
+ if (c.hasPendingAction)
+ TextButton(
+ onPressed: c.saving ? null : c.retry,
+ child: const Text('Check pending action'),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
final group = c.selected;
final messages = c.messages(c.selectedId);
final entries = superTabTranscriptEntries(messages);
@@ -1292,6 +1323,7 @@ class _SuperTabViewState extends State<SuperTabView> {
return KeyEventResult.ignored;
},
child: DecoratedBox(
+ key: const ValueKey('super-message-composer-surface'),
decoration: BoxDecoration(
color: DesktopChrome.field,
borderRadius: BorderRadius.circular(
@@ -1299,73 +1331,87 @@ class _SuperTabViewState extends State<SuperTabView> {
),
border: Border.all(color: DesktopChrome.rim),
),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Expanded(
- child: TextField(
- key: const ValueKey('super-message-composer'),
- controller: _composer,
- focusNode: _focus,
- autofocus: !_terminalsVisible,
- enabled: c.canWrite && group != null && !group.archived,
- minLines: 1,
- maxLines: MediaQuery.sizeOf(context).height < 600
- ? 3
- : 8,
- maxLength: 32000,
- keyboardType: TextInputType.multiline,
- textAlignVertical: TextAlignVertical.center,
- style: DesktopChrome.text(),
- decoration: InputDecoration(
- isDense: true,
- hintStyle: DesktopChrome.text(
- color: DesktopChrome.muted,
+ child: GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onTap: c.canWrite && group != null && !group.archived
+ ? _focus.requestFocus
+ : null,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: grid.AppControl.heightFieldScaled,
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('super-message-composer'),
+ controller: _composer,
+ focusNode: _focus,
+ autofocus: !_terminalsVisible,
+ enabled:
+ c.canWrite && group != null && !group.archived,
+ minLines: 1,
+ maxLines: MediaQuery.sizeOf(context).height < 600
+ ? 3
+ : 8,
+ maxLength: 32000,
+ keyboardType: TextInputType.multiline,
+ textAlignVertical: TextAlignVertical.center,
+ style: DesktopChrome.text(),
+ decoration: InputDecoration(
+ // The row centers the line. Inheriting a decorated
+ // field's minimum height leaves slack below its text.
+ isCollapsed: true,
+ constraints: const BoxConstraints(),
+ visualDensity: VisualDensity.standard,
+ hintStyle: DesktopChrome.text(
+ color: DesktopChrome.muted,
+ ),
+ contentPadding: EdgeInsets.zero,
+ hintText: group == null
+ ? 'Loading conversation…'
+ : c.canWrite
+ ? 'Message ${group.title}'
+ : 'Read-only conversation',
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ filled: false,
+ counterText: '',
+ ),
+ onChanged: (text) {
+ c.setDraft(c.selectedId, text);
+ setState(() {
+ _mentionIndex = 0;
+ _dismissedMention = null;
+ });
+ },
),
- contentPadding: const EdgeInsets.symmetric(
- vertical: 6,
+ ),
+ ValueListenableBuilder(
+ valueListenable: _composer,
+ builder: (context, value, _) => AppIconButton(
+ icon: AppIcons.arrowUp,
+ tooltip: 'Send message',
+ color: DesktopChrome.accent,
+ onPressed:
+ c.canWrite &&
+ group != null &&
+ !group.archived &&
+ !c.saving &&
+ !c.hasPendingAction &&
+ value.text.trim().isNotEmpty
+ ? () => unawaited(_send())
+ : null,
),
- hintText: group == null
- ? 'Loading conversation…'
- : c.canWrite
- ? 'Message ${group.title}'
- : 'Read-only conversation',
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- disabledBorder: InputBorder.none,
- filled: false,
- counterText: '',
),
- onChanged: (text) {
- c.setDraft(c.selectedId, text);
- setState(() {
- _mentionIndex = 0;
- _dismissedMention = null;
- });
- },
- ),
- ),
- ValueListenableBuilder(
- valueListenable: _composer,
- builder: (context, value, _) => AppIconButton(
- icon: AppIcons.arrowUp,
- tooltip: 'Send message',
- color: DesktopChrome.accent,
- onPressed:
- c.canWrite &&
- group != null &&
- !group.archived &&
- !c.saving &&
- !c.hasPendingAction &&
- value.text.trim().isNotEmpty
- ? () => unawaited(_send())
- : null,
- ),
+ ],
),
- ],
+ ),
),
),
),
@@ -1416,7 +1462,9 @@ class _SuperTabViewState extends State<SuperTabView> {
_header(c.selected, narrow, showRoster),
Expanded(
child: IndexedStack(
- index: _terminalsVisible
+ index: c.snapshot?.projects.isEmpty == true
+ ? 0
+ : _terminalsVisible
? 1
: _showPullRequests
? 2
diff --git a/desktop/lib/widgets/workspace_welcome.dart b/desktop/lib/widgets/workspace_welcome.dart
index 5f9f9e562..7c929adc3 100644
--- a/desktop/lib/widgets/workspace_welcome.dart
+++ b/desktop/lib/widgets/workspace_welcome.dart
@@ -423,18 +423,39 @@ class _WorkspaceWelcomeState extends State<WorkspaceWelcome> {
padding: const EdgeInsets.only(bottom: 8, left: 10),
child: Semantics(
header: true,
- child: Text('Closed Swarms', style: headerStyle),
+ child: Text('Recent Swarms', style: headerStyle),
),
),
for (final tab in widget.closedSuperTabs)
TextButton(
key: ValueKey('welcome-closed-super-tab-${tab.id}'),
onPressed: () => open(tab.id),
- style: TextButton.styleFrom(
- foregroundColor: color,
- alignment: Alignment.centerLeft,
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
- ),
+ style:
+ TextButton.styleFrom(
+ foregroundColor: color,
+ backgroundColor: Colors.transparent,
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 8,
+ ),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ grid.AppDesktop.rowRadius,
+ ),
+ ),
+ ).copyWith(
+ side: WidgetStateProperty.resolveWith(
+ (states) => BorderSide(
+ width: 1.5,
+ color: states.contains(WidgetState.focused)
+ ? (MediaQuery.highContrastOf(context)
+ ? DesktopChrome.accent
+ : DesktopChrome.focusRing)
+ : Colors.transparent,
+ ),
+ ),
+ ),
child: Text(
tab.name,
maxLines: 1,
diff --git a/desktop/test/super_tab_composer_layout_test.dart b/desktop/test/super_tab_composer_layout_test.dart
new file mode 100644
index 000000000..bcda9b6f7
--- /dev/null
+++ b/desktop/test/super_tab_composer_layout_test.dart
@@ -0,0 +1,156 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ final capture = Platform.environment['HARNESS_SWARM_COMPOSER_CAPTURE'];
+ final field = find.byKey(const ValueKey('super-message-composer'));
+ final surface = find.byKey(const ValueKey('super-message-composer-surface'));
+ setUpAll(() async {
+ if (capture == null || !Platform.isMacOS) return;
+ final bytes = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('composer text centers in ${brightness.name} at ${scale}x', (
+ tester,
+ ) async {
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() {
+ grid.AppTheme.brightness.value = previousBrightness;
+ });
+ await tester.binding.setSurfaceSize(const Size(1100, 720));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ final controller = server.controller();
+ await controller.refresh();
+ addTearDown(controller.dispose);
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final measurements = <String, Object>{};
+ Future<void> record(String name) async {
+ final editor = tester
+ .state<EditableTextState>(
+ find.descendant(of: field, matching: find.byType(EditableText)),
+ )
+ .renderEditable;
+ final rect = tester.getRect(surface);
+ final caret = editor
+ .getLocalRectForCaret(const TextPosition(offset: 0))
+ .shift(editor.localToGlobal(Offset.zero));
+ final editableRect = editor.localToGlobal(Offset.zero) & editor.size;
+ final hint = find.descendant(
+ of: field,
+ matching: find.text('Message Lead'),
+ );
+ measurements[name] = {
+ 'surfaceHeight': rect.height,
+ 'surfaceCenter': rect.center.dy,
+ 'editableCenter': editableRect.center.dy,
+ 'caretCenter': caret.center.dy,
+ if (hint.evaluate().isNotEmpty)
+ 'hintCenter': tester.getRect(hint).center.dy,
+ };
+ if (capture != null) {
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ final path = '$capture/${brightness.name}-${scale}x-$name';
+ await Directory(capture).create(recursive: true);
+ await File('$path.png').writeAsBytes(bytes!.buffer.asUint8List());
+ await File('$path.json').writeAsString(
+ const JsonEncoder.withIndent(' ').convert(measurements),
+ );
+ image.dispose();
+ });
+ }
+ debugPrint('Composer $name: ${measurements[name]}');
+ expect(editableRect.center.dy, closeTo(rect.center.dy, .75));
+ expect(caret.center.dy, closeTo(rect.center.dy, .75));
+ if (name == 'empty') {
+ expect(
+ tester.getRect(hint).center.dy,
+ closeTo(rect.center.dy, .75),
+ );
+ }
+ }
+
+ await record('empty');
+ final singleHeight = tester.getSize(surface).height;
+ final focus = tester.widget<TextField>(field).focusNode!;
+ focus.unfocus();
+ await tester.pump();
+ await tester.tapAt(
+ tester.getRect(surface).topLeft + const Offset(40, 10),
+ );
+ await tester.pump();
+ expect(focus.hasFocus, isTrue);
+ await tester.enterText(field, 'Keep me up to date.');
+ await tester.pumpAndSettle();
+ await record('typed');
+ expect(tester.getSize(surface).height, singleHeight);
+ await tester.enterText(field, 'First line\nSecond line\nThird line');
+ await tester.pumpAndSettle();
+ expect(tester.getSize(surface).height, greaterThan(singleHeight));
+ expect(tester.takeException(), isNull);
+ await tester.enterText(field, 'Back to one line');
+ await tester.pumpAndSettle();
+ await record('collapsed');
+ expect(tester.getSize(surface).height, singleHeight);
+ await tester.pump(const Duration(milliseconds: 250));
+ await tester.pumpWidget(const SizedBox());
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+ }
+ }
+}
diff --git a/desktop/test/super_tab_discovery_test.dart b/desktop/test/super_tab_discovery_test.dart
index 93f7c3c40..d71a297d5 100644
--- a/desktop/test/super_tab_discovery_test.dart
+++ b/desktop/test/super_tab_discovery_test.dart
@@ -291,7 +291,7 @@ void main() {
'>Pilot',
);
await tester.pumpAndSettle();
- expect(find.text('Closed Swarms'), findsWidgets);
+ expect(find.text('Recent Swarms'), findsWidgets);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(app.activeSwarm.superTabId, tab.superTabId);
@@ -312,10 +312,10 @@ void main() {
await _close(first, tab);
final app = _computer(catalog, store)..newSwarm(newTabPage: true);
await mount(tester, app);
- expect(find.text('Closed Swarms'), findsNothing);
+ expect(find.text('Recent Swarms'), findsNothing);
await app.superTabs.refreshTabs();
await tester.pump();
- expect(find.text('Closed Swarms'), findsOneWidget);
+ expect(find.text('Recent Swarms'), findsOneWidget);
await tester.tap(
find.byKey(ValueKey('welcome-closed-super-tab-${tab.superTabId}')),
);
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 562834307..7c1a2f879 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/first_task.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/new_harness.dart';
@@ -47,6 +48,9 @@ class SuperTabFixtureConnection extends WsConn {
static const streamId = '00112233-4455-6677-8899-aabbccddeeff';
Map<String, dynamic>? native;
String nativeName = 'Lead';
+ bool cancelledCreation = false;
+ Future<Map<String, dynamic>> Function(String, Map<String, dynamic>)?
+ creationRecovery;
Future<void> event(String type, Map<String, dynamic> payload) =>
app.handleMachineEventForTest('m', {'type': type, 'payload': payload});
@@ -232,7 +236,29 @@ class SuperTabFixtureConnection extends WsConn {
'agent': native,
};
}
+ if (type == 'agent_create_status' || type == 'agent_create_cancel') {
+ if (creationRecovery case final recover?) return recover(type, payload);
+ }
+ if (type == 'agent_create_cancel') {
+ cancelledCreation = native == null;
+ return {
+ 'creationId': payload['creationId'],
+ 'state': cancelledCreation ? 'cancelled' : 'created',
+ 'agent': native,
+ };
+ }
if (type == 'agent_create') {
+ // Match the native daemon: this refusal happens before a receipt or pane.
+ if ((payload['prompt'] as String? ?? '').trim().length >
+ kFirstTaskMaxLength) {
+ throw const WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: 'PROMPT_TOO_LONG',
+ detail: 'First task exceeds the native limit.',
+ payload: {},
+ );
+ }
+ cancelledCreation = false;
final records = store.values.entries.where(
(e) => e.key.startsWith('super_tab.launch.'),
);
@@ -263,7 +289,11 @@ class SuperTabFixtureConnection extends WsConn {
}
return {
'creationId': payload['creationId'],
- 'state': native == null ? 'missing' : 'created',
+ 'state': cancelledCreation
+ ? 'cancelled'
+ : native == null
+ ? 'missing'
+ : 'created',
'agent': native,
};
}
@@ -316,6 +346,7 @@ class SuperTabLaunchFixture {
String engine = 'codex',
HarnessAttachments? attachments,
bool newProject = false,
+ String? task = 'Discuss the architecture.',
}) async {
final integration = await SuperTabLaunch.open(
app,
@@ -328,7 +359,7 @@ class SuperTabLaunchFixture {
machineId: 'm',
engine: engine,
folder: '/work/project',
- task: 'Discuss the architecture.',
+ task: task,
integration: integration,
attachments: attachments,
);
@@ -592,7 +623,7 @@ void main() {
f.connection.terminalCalls
.singleWhere((c) => c.$1 == 'message')
.$2['content'],
- contains('Discuss the architecture.'),
+ contains('messages lead'),
);
expect(f.connection.terminalCalls.last.$1, 'terminal_close');
expect(f.app.activeSwarm.panes, isEmpty);
@@ -681,10 +712,7 @@ void main() {
expect(creates, hasLength(1));
expect(creates.single.$2['engine'], engine);
expect(f.connection.joins.single['command']['name'], 'Lead');
- expect(
- creates.single.$2['prompt'],
- contains('Discuss the architecture.'),
- );
+ expect(creates.single.$2['prompt'], contains('messages lead'));
expect(
creates.single.$2['prompt'],
contains('harness super-tab --tab $tabId'),
@@ -728,7 +756,7 @@ void main() {
expect(prompt, contains('like a helpful colleague'));
expect(prompt, contains('under about 150 words'));
expect(prompt, contains('UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`'));
- expect(prompt, contains('post with --reply-to MESSAGE_ID'));
+ expect(prompt, contains('answer each message once'));
expect(prompt, contains('do not post again'));
expect(prompt, isNot(contains('Report exact revisions')));
expect(prompt, isNot(contains('email addresses')));
diff --git a/desktop/test/super_tab_polish_test.dart b/desktop/test/super_tab_polish_test.dart
index 4d31fc6c2..490947a9b 100644
--- a/desktop/test/super_tab_polish_test.dart
+++ b/desktop/test/super_tab_polish_test.dart
@@ -393,6 +393,26 @@ void main() {
),
);
}
+ // Capture one row treatment across disclosure, label and nested work.
+ final mouse = await tester.createGesture(
+ kind: ui.PointerDeviceKind.mouse,
+ );
+ await mouse.addPointer(location: Offset.zero);
+ for (final target in [
+ ('project-hover', const ValueKey('super-group-lead')),
+ ('disclosure-hover', const ValueKey('super-project-expand-lead')),
+ ('workgroup-hover', const ValueKey('super-group-offline')),
+ ]) {
+ await mouse.moveTo(tester.getCenter(find.byKey(target.$2)));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 200));
+ await shot('-${target.$1}');
+ }
+ c.select('offline');
+ await tester.pumpAndSettle();
+ await shot('-workgroup-selected');
+ await mouse.removePointer();
+ expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
await c.flush();
c.dispose();
diff --git a/desktop/test/super_tab_project_delete_test.dart b/desktop/test/super_tab_project_delete_test.dart
new file mode 100644
index 000000000..022c59058
--- /dev/null
+++ b/desktop/test/super_tab_project_delete_test.dart
@@ -0,0 +1,249 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ final confirm = find.widgetWithText(FilledButton, 'Delete Project');
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+
+ Future<(ConversationServer, SuperTabController)> mount(
+ WidgetTester tester, {
+ ConversationServer? server,
+ String account = 'owner',
+ }) async {
+ server ??= ConversationServer();
+ final c = server.controller(account: account);
+ await c.refresh();
+ addTearDown(c.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ onNewProject: () {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return (server, c);
+ }
+
+ Future<void> openDelete(WidgetTester tester) async {
+ await tester.tap(find.byTooltip('Project options'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(MenuItemButton, 'Delete Project'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> finish(WidgetTester tester) async {
+ await tester.pump(const Duration(milliseconds: 250));
+ await tester.pumpWidget(const SizedBox());
+ }
+
+ testWidgets('Delete Project names the project and defaults to Cancel', (
+ tester,
+ ) async {
+ final (server, c) = await mount(tester);
+ expect(c.snapshot!.agents, isEmpty);
+ await openDelete(tester);
+ expect(server.posts, isEmpty);
+ expect(
+ find.text(
+ '“Pilot” and all of its conversations will be permanently deleted. This can’t be undone.',
+ ),
+ findsOneWidget,
+ );
+ expect(tester.widget<FilledButton>(confirm).onPressed, isNotNull);
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Cancel'))
+ .autofocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(server.posts, isEmpty);
+ expect(c.snapshot!.projects, hasLength(1));
+ await finish(tester);
+ });
+
+ testWidgets(
+ 'deleting one project selects the remaining lead and clears its conversations',
+ (tester) async {
+ final server = ConversationServer();
+ server.state['projects'] = [
+ projectFixture('lead', 'Pilot', 'lead'),
+ projectFixture('design', 'Design', 'design-lead'),
+ ];
+ (server.state['conversations'] as List).add({
+ ...conversationFixture('design-lead', 'Lead'),
+ 'projectId': 'design',
+ });
+ server.append('Old project conversation.');
+ final (_, c) = await mount(tester, server: server);
+ c.setDraft('offline', 'Unsent project draft');
+ await openDelete(tester);
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(server.posts.single['command'], {
+ 'type': 'project.delete',
+ 'projectId': 'lead',
+ });
+ expect(c.snapshot!.projects.single.id, 'design');
+ expect(c.selectedId, 'design-lead');
+ expect(c.snapshot!.conversations.single.id, 'design-lead');
+ expect(c.draft('offline'), isEmpty);
+ expect(find.text('Old project conversation.'), findsNothing);
+ expect(composer, findsOneWidget);
+ await finish(tester);
+ },
+ );
+
+ testWidgets(
+ 'deleting the final project shows an empty Swarm without a composer',
+ (tester) async {
+ final (_, c) = await mount(tester);
+ await openDelete(tester);
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(c.snapshot!.projects, isEmpty);
+ expect(c.snapshot!.conversations, isEmpty);
+ expect(find.text('Create a project to get started.'), findsOneWidget);
+ expect(find.text('Loading conversation…'), findsNothing);
+ expect(composer, findsNothing);
+ expect(find.byTooltip('Project options'), findsNothing);
+ expect(find.text('New Project'), findsOneWidget);
+ expect(find.byTooltip('Chat'), findsNothing);
+ await finish(tester);
+ },
+ );
+
+ for (final (code, message) in [
+ (
+ 'PROJECT_HAS_AGENTS',
+ 'Stop and remove this project’s agents before deleting it.',
+ ),
+ (
+ 'STARTS_PENDING',
+ 'Resolve this project’s pending agent starts before deleting it.',
+ ),
+ ('WORK_ACTIVE', 'Resolve this project’s active work before deleting it.'),
+ ]) {
+ testWidgets('$code refusal preserves the project and shows its reason', (
+ tester,
+ ) async {
+ final (server, c) = await mount(tester);
+ server.refuse = {'code': code, 'message': message};
+ await openDelete(tester);
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byType(AlertDialog),
+ matching: find.text(message),
+ ),
+ findsOneWidget,
+ );
+ expect(c.snapshot!.projects, hasLength(1));
+ expect(c.hasPendingAction, isFalse);
+ expect(tester.widget<FilledButton>(confirm).onPressed, isNotNull);
+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));
+ await tester.pumpAndSettle();
+ expect(server.posts, hasLength(1));
+ await finish(tester);
+ });
+ }
+
+ testWidgets(
+ 'lost deletion reply retries the same receipt after polling removes the project',
+ (tester) async {
+ final (server, c) = await mount(tester);
+ server.loseReply = true;
+ await openDelete(tester);
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ expect(c.hasPendingAction, isTrue);
+ expect(find.widgetWithText(FilledButton, 'Retry'), findsOneWidget);
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(c.snapshot!.projects, isEmpty);
+ expect(find.widgetWithText(FilledButton, 'Retry'), findsOneWidget);
+ await tester.tap(find.widgetWithText(FilledButton, 'Retry'));
+ await tester.pumpAndSettle();
+ expect(server.posts, hasLength(2));
+ expect(server.posts[1]['operationId'], server.posts[0]['operationId']);
+ expect(c.hasPendingAction, isFalse);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(find.text('Create a project to get started.'), findsOneWidget);
+ await finish(tester);
+ },
+ );
+
+ testWidgets(
+ 'closing an uncertain deletion leaves a recoverable action in the empty Swarm',
+ (tester) async {
+ final (server, c) = await mount(tester);
+ server.loseReply = true;
+ await openDelete(tester);
+ await tester.tap(confirm);
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(TextButton, 'Close'));
+ await tester.pumpAndSettle();
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(c.hasPendingAction, isTrue);
+ expect(c.snapshot!.projects, isEmpty);
+ await tester.tap(find.widgetWithText(TextButton, 'Check pending action'));
+ await tester.pumpAndSettle();
+ expect(c.hasPendingAction, isFalse);
+ expect(server.posts, hasLength(2));
+ expect(server.posts[1]['operationId'], server.posts[0]['operationId']);
+ expect(find.text('Create a project to get started.'), findsOneWidget);
+ await finish(tester);
+ },
+ );
+
+ testWidgets('a collaborator cannot open Delete Project', (tester) async {
+ final server = ConversationServer();
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ await mount(tester, server: server, account: 'peer');
+ await tester.tap(find.byTooltip('Project options'));
+ await tester.pumpAndSettle();
+ expect(find.text('Delete Project'), findsNothing);
+ expect(server.posts, isEmpty);
+ await finish(tester);
+ });
+
+ testWidgets('access revocation removes the captured confirmation', (
+ tester,
+ ) async {
+ final (server, c) = await mount(tester);
+ await openDelete(tester);
+ c.revokeAccess('Account changed');
+ await tester.pumpAndSettle();
+ expect(confirm, findsNothing);
+ expect(find.textContaining('permanently deleted'), findsNothing);
+ expect(find.text('This action is no longer available.'), findsOneWidget);
+ expect(server.posts, isEmpty);
+ await finish(tester);
+ });
+}
diff --git a/desktop/test/super_tab_startup_recovery_test.dart b/desktop/test/super_tab_startup_recovery_test.dart
new file mode 100644
index 000000000..9ad79e9fb
--- /dev/null
+++ b/desktop/test/super_tab_startup_recovery_test.dart
@@ -0,0 +1,288 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/first_task.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/super_tabs/launch_prompt.dart';
+
+import 'super_tab_launch_test.dart';
+
+Future<String> legacyLaunch(
+ SuperTabLaunchFixture f, {
+ String task = 'Discuss the architecture.',
+ String phase = 'starting',
+ bool files = false,
+ bool oversized = true,
+ bool newProject = false,
+}) async {
+ if (newProject) f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final box = await f.box(task: task, newProject: newProject);
+ await box.integration!.prepare('m', task);
+ final key = f.store.values.keys.singleWhere(
+ (key) => key.startsWith('super_tab.launch.'),
+ );
+ final saved = jsonDecode(f.store.values[key]!) as Map<String, dynamic>;
+ saved.addAll({
+ 'phase': phase,
+ 'creationId': 'legacy-launch',
+ 'launchPrompt': oversized ? 'x' * (kFirstTaskMaxLength + 1) : 'short',
+ 'files': [
+ if (files) {'name': 'test.txt', 'bytes': 'aGk='},
+ ],
+ });
+ f.store.values[key] = jsonEncode(saved);
+ return key;
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test('bootstrap fits native limit with maximum server IDs', () {
+ for (final lead in [true, false]) {
+ final prompt = superTabLaunchPrompt(
+ tabId: 'a' * 160,
+ conversationId: 'b' * 160,
+ lead: lead,
+ );
+ expect(prompt.length, lessThanOrEqualTo(kFirstTaskMaxLength));
+ }
+ });
+
+ for (final engine in ['codex', 'claude']) {
+ for (final newProject in [false, true]) {
+ for (final task in ['', 'hi', '文🙂\n' * 500]) {
+ test(
+ '$engine ${newProject ? 'project' : 'swarm'} preserves ${task.length}-unit request',
+ () async {
+ final f = SuperTabLaunchFixture();
+ if (newProject) {
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ }
+ final box = await f.box(
+ engine: engine,
+ newProject: newProject,
+ task: task,
+ );
+ expect(
+ await box.create(),
+ NewHarnessOutcome.created,
+ reason: box.error,
+ );
+ final create = f.connection.calls.singleWhere(
+ (c) => c.$1 == 'agent_create',
+ );
+ expect(
+ (create.$2['prompt'] as String).length,
+ lessThanOrEqualTo(kFirstTaskMaxLength),
+ );
+ final messages = f.connection.server.messages;
+ expect(messages, hasLength(task.trim().isEmpty ? 0 : 1));
+ if (messages.isNotEmpty) {
+ expect(messages.single['text'], task.trim());
+ }
+ expect(f.connection.joins, hasLength(1));
+ },
+ );
+ }
+ }
+ }
+
+ test('legacy refusal is fenced before retrying the same project with its saved task', () async {
+ final f = SuperTabLaunchFixture();
+ final task = '文🙂\n' * 500;
+ await legacyLaunch(f, task: task, newProject: true);
+ final box = await f.box(task: '', newProject: true);
+ expect(box.task, task);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('previous startup request was cancelled'));
+ expect(box.checking, isFalse);
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ final cancel = f.connection.calls.singleWhere(
+ (c) => c.$1 == 'agent_create_cancel',
+ );
+ expect(cancel.$2['creationId'], 'legacy-launch');
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(
+ f.connection.server.posts.where(
+ (p) => (p['command'] as Map)['type'] == 'project.create',
+ ),
+ hasLength(1),
+ );
+ expect(f.connection.server.messages.single['text'], task.trim());
+ final created = f.connection.calls.singleWhere(
+ (c) => c.$1 == 'agent_create',
+ );
+ expect(created.$2['creationId'], isNot('legacy-launch'));
+ });
+
+ test(
+ 'lost cancellation reply stays locked until its durable receipt is read',
+ () async {
+ final f = SuperTabLaunchFixture();
+ await legacyLaunch(f);
+ f.connection.creationRecovery = (type, payload) async {
+ if (type == 'agent_create_cancel') {
+ f.connection.cancelledCreation = true;
+ throw TimeoutException('Lost cancellation reply');
+ }
+ return {'creationId': payload['creationId'], 'state': 'missing'};
+ };
+ final first = await f.box();
+ expect(await first.create(), NewHarnessOutcome.failed);
+ expect(first.checking, isTrue);
+ f.connection.creationRecovery = null;
+ final reopened = await f.box();
+ expect(await reopened.create(), NewHarnessOutcome.failed);
+ expect(reopened.checking, isFalse);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create_cancel'),
+ hasLength(1),
+ );
+ expect(
+ await reopened.create(),
+ NewHarnessOutcome.created,
+ reason: reopened.error,
+ );
+ },
+ );
+
+ test('a cancellation race that returns a created harness completes that exact launch', () async {
+ final f = SuperTabLaunchFixture();
+ await legacyLaunch(f);
+ f.connection.creationRecovery = (type, payload) async {
+ if (type == 'agent_create_status') {
+ return {'creationId': payload['creationId'], 'state': 'missing'};
+ }
+ f.connection.native = {
+ 'id': 'race-agent',
+ 'engine': 'codex',
+ 'name': 'Recovered lead',
+ 'project': {'cwd': '/work/project', 'label': 'Project'},
+ };
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': f.connection.native,
+ };
+ };
+ final box = await f.box();
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(f.connection.joins.single['command']['harnessId'], 'race-agent');
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ });
+
+ for (final state in ['pending', 'missing', 'wrong-id', 'error']) {
+ test(
+ 'unconfirmed cancellation $state cannot unlock or launch a duplicate',
+ () async {
+ final f = SuperTabLaunchFixture();
+ await legacyLaunch(f);
+ f.connection.creationRecovery = (type, payload) async {
+ if (type == 'agent_create_status') {
+ return {'creationId': payload['creationId'], 'state': 'missing'};
+ }
+ if (state == 'error') throw StateError('Connection lost');
+ return {
+ 'creationId': state == 'wrong-id'
+ ? 'someone-else'
+ : payload['creationId'],
+ 'state': state == 'wrong-id' ? 'cancelled' : state,
+ };
+ };
+ final box = await f.box();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.checking, isTrue);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ isEmpty,
+ );
+ },
+ );
+ }
+
+ for (final changeAt in ['agent_create_status', 'agent_create_cancel']) {
+ test(
+ 'account change after $changeAt cannot unlock the old request',
+ () async {
+ final f = SuperTabLaunchFixture();
+ await legacyLaunch(f);
+ f.connection.creationRecovery = (type, payload) async {
+ if (type == changeAt) {
+ f.app.currentUser = const CurrentUserProfile(
+ id: 'other',
+ email: '[email protected]',
+ );
+ }
+ return {
+ 'creationId': payload['creationId'],
+ 'state': type == 'agent_create_status' ? 'missing' : 'cancelled',
+ };
+ };
+ final box = await f.box();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('account changed'));
+ expect(box.checking, isTrue);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ isEmpty,
+ );
+ if (changeAt == 'agent_create_status') {
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create_cancel'),
+ isEmpty,
+ );
+ }
+ },
+ );
+ }
+
+ for (final kind in ['joining', 'files', 'bounded']) {
+ test('$kind recovery does not cancel an unknown native launch', () async {
+ final f = SuperTabLaunchFixture();
+ await legacyLaunch(
+ f,
+ phase: kind == 'joining' ? 'joining' : 'starting',
+ files: kind == 'files',
+ oversized: kind != 'bounded',
+ );
+ final box = await f.box();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.checking, isTrue);
+ expect(
+ f.connection.calls.where(
+ (c) => c.$1 == 'agent_create_cancel' || c.$1 == 'agent_create',
+ ),
+ isEmpty,
+ );
+ });
+ }
+
+ test(
+ 'a deleted destination blocks native submission from an old journal',
+ () async {
+ final f = SuperTabLaunchFixture();
+ await legacyLaunch(f, newProject: true);
+ final box = await f.box(newProject: true);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.checking, isFalse);
+ (f.connection.server.state['conversations'] as List).removeWhere(
+ (g) => (g as Map)['projectId'] != null,
+ );
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('project is no longer available'));
+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);
+ final fresh = await f.box(newProject: true);
+ expect(
+ await fresh.create(),
+ NewHarnessOutcome.created,
+ reason: fresh.error,
+ );
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ },
+ );
+}
diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dart
index 262870416..111d068e0 100644
--- a/desktop/test/super_tab_view_test.dart
+++ b/desktop/test/super_tab_view_test.dart
@@ -223,7 +223,7 @@ void main() {
);
testWidgets(
- 'projects stay collapsed and creation stays in the sidebar footer',
+ 'projects stay collapsed and creation remains in the sidebar',
(tester) async {
await tester.binding.setSurfaceSize(const Size(1100, 700));
addTearDown(() => tester.binding.setSurfaceSize(null));
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index b8e13dc91..da06b3ca6 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -139,6 +139,22 @@ class ConversationServer {
'brief': command['brief'] ?? '',
});
output.addAll({'projectId': id, 'conversationId': leadId});
+ } else if (command['type'] == 'project.delete') {
+ final projectId = command['projectId'];
+ final projects =
+ state['projects'] ??
+ [projectFixture('lead', state['name'] as String, 'lead')];
+ state['projects'] = (projects as List)
+ .where((p) => p['id'] != projectId)
+ .toList();
+ final groups = state['conversations'] as List;
+ final removed = groups
+ .where((g) => (g['projectId'] ?? 'lead') == projectId)
+ .map((g) => g['id'])
+ .toSet();
+ groups.removeWhere((g) => removed.contains(g['id']));
+ messages.removeWhere((m) => removed.contains(m['conversationId']));
+ revision++;
} else if ([
'project.rename',
'project.cadence',
diff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dart
index bc3420c2d..a3eb1f6b7 100644
--- a/desktop/test/swarm_projects_test.dart
+++ b/desktop/test/swarm_projects_test.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/super_tabs/view.dart';
@@ -67,8 +68,17 @@ void main() {
findsNothing,
);
expect(find.text('Leads'), findsNothing);
+ expect(find.text('Projects'), findsNothing);
expect(find.text('Humans'), findsOneWidget);
expect(find.text('Agents'), findsOneWidget);
+ final create = find.byKey(const ValueKey('super-new-project'));
+ final project = find.byKey(const ValueKey('super-group-lead'));
+ expect(
+ tester.getBottomLeft(create).dy,
+ lessThan(tester.getTopLeft(project).dy),
+ );
+ expect(tester.getRect(create).left, tester.getRect(project).left);
+ expect(tester.getRect(create).right, tester.getRect(project).right);
await tester.tap(find.byKey(const ValueKey('super-project-expand-lead')));
await tester.pumpAndSettle();
expect(c.selectedId, 'lead');
@@ -91,6 +101,59 @@ void main() {
},
);
+ testWidgets(
+ 'project and workgroup rows align while both project actions remain keyboard accessible',
+ (tester) async {
+ final server = projectsServer(), c = server.controller();
+ await mount(tester, c);
+ final project = find.byKey(const ValueKey('super-group-lead'));
+ final disclosure = find.byKey(
+ const ValueKey('super-project-expand-lead'),
+ );
+ final icon = find.descendant(of: disclosure, matching: find.byType(Icon));
+ Focus.of(tester.element(icon)).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(c.expandedProjects, {'lead'});
+ expect(c.selectedId, 'lead');
+
+ final workgroup = find.byKey(const ValueKey('super-group-offline'));
+ final projectBounds = tester.getRect(project);
+ final workgroupBounds = tester.getRect(workgroup);
+ expect(workgroupBounds.left, projectBounds.left);
+ expect(workgroupBounds.right, projectBounds.right);
+ final projectName = find.descendant(
+ of: project,
+ matching: find.text('Lamp OS'),
+ );
+ expect(
+ tester.getTopLeft(find.text('#12 Offline editing')).dx -
+ tester.getTopLeft(projectName).dx,
+ 8,
+ );
+
+ // A child row's formerly empty inset is part of its one click target.
+ await tester.tapAt(workgroupBounds.centerLeft + const Offset(8, 0));
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'offline');
+ Focus.of(tester.element(icon)).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.space);
+ await tester.pumpAndSettle();
+ expect(c.expandedProjects, isEmpty);
+ expect(c.selectedId, 'offline');
+ Focus.of(tester.element(projectName)).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'lead');
+ expect(c.expandedProjects, isEmpty);
+ expect(server.posts, isEmpty);
+ await unmount(tester, c);
+ },
+ );
+
testWidgets('project pull requests include its workgroups and stay scoped', (
tester,
) async {
diff --git a/desktop/test/welcome_closed_super_tabs_test.dart b/desktop/test/welcome_closed_super_tabs_test.dart
index c50b0bd45..984eaae01 100644
--- a/desktop/test/welcome_closed_super_tabs_test.dart
+++ b/desktop/test/welcome_closed_super_tabs_test.dart
@@ -1,26 +1,44 @@
+import 'dart:io';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/widgets/workspace_welcome.dart';
+import 'support/capture.dart';
+
const _closed = [(id: 'tab-1', name: 'Pilot'), (id: 'tab-2', name: 'Build')];
Future<List<String>> _mount(
WidgetTester tester, {
List<({String id, String name})> closed = _closed,
bool composer = false,
+ Brightness brightness = Brightness.dark,
+ double textScale = 1,
}) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(1280, 800);
addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
final opened = <String>[];
await tester.pumpWidget(
MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(textScale)),
+ child: child!,
+ ),
home: WorkspaceWelcome(
onCommand: (_) {},
closedSuperTabs: closed,
onOpenSuperTab: opened.add,
composerBuilder: composer
- ? (recents) => recents ?? const SizedBox()
+ ? (recents) => Center(child: SizedBox(width: 640, child: recents))
: null,
),
),
@@ -30,13 +48,15 @@ Future<List<String>> _mount(
}
void main() {
+ final capture = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];
+ setUpAll(() => loadCaptureFonts(capture));
for (final composer in [false, true]) {
final layout = composer ? 'composer' : 'classic';
testWidgets('$layout welcome lists closed Swarms and opens one', (
tester,
) async {
final opened = await _mount(tester, composer: composer);
- expect(find.text('Closed Swarms'), findsOneWidget);
+ expect(find.text('Recent Swarms'), findsOneWidget);
expect(find.text('Pilot'), findsOneWidget);
await tester.tap(
find.byKey(const ValueKey('welcome-closed-super-tab-tab-2')),
@@ -48,7 +68,39 @@ void main() {
tester,
) async {
await _mount(tester, closed: const [], composer: composer);
- expect(find.text('Closed Swarms'), findsNothing);
+ expect(find.text('Recent Swarms'), findsNothing);
});
}
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'recent Swarm rows remain keyboard accessible in ${brightness.name} at $scale',
+ (tester) async {
+ final opened = await _mount(
+ tester,
+ composer: true,
+ brightness: brightness,
+ textScale: scale,
+ );
+ await captureWindow(
+ tester,
+ capture,
+ 'swarm-recents-${brightness.name}-$scale',
+ );
+ Focus.of(tester.element(find.text('Build'))).requestFocus();
+ await tester.pumpAndSettle();
+ await captureWindow(
+ tester,
+ capture,
+ 'swarm-recents-${brightness.name}-$scale-focus',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(opened, ['tab-2']);
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+ }
}