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.

Team account batch: #1976 #1978 #1980 #1996 #1997 #1998 (#2006)

0xken159a1b3ee0c2f2
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.ts
index ad2628bc1..6bb4340a5 100644
--- a/backend/integration/superTabGithub.test.ts
+++ b/backend/integration/superTabGithub.test.ts
@@ -56,7 +56,8 @@ async function fresh(options: { github?: boolean; approveAll?: boolean; signIn?:
const log = { warn: vi.fn() }
const tokens = new GitHubTokens(fakeApp(key.privateKey, github), new MemoryTokenCache(), { log, secret: randomBytes(32) })
const releases: Promise<void>[] = []
- const store = new SuperTabStore(db, Date.now, null, { workEnded: (tab, ended) => { releases.push(tokens.release(tab, ended)) } })
+ const store = new SuperTabStore(db, Date.now, null, { workEnded: (tab, ended) => { releases.push(tokens.release(tab, ended)) },
+ workStarted: (tab, started) => { releases.push(tokens.resume(tab, started)) } })
const app: FastifyInstance = Fastify()
app.setErrorHandler(errorHandler)
app.addHook('onRequest', async (request, reply) => {
@@ -74,6 +75,8 @@ async function fresh(options: { github?: boolean; approveAll?: boolean; signIn?:
approved: async (_env, tabId, projectId, repository) => options.approveAll !== false
|| approved.some(a => a.tabId === tabId && a.repository === repository.toLowerCase() && (a.scope === 'swarm' || a.projectId === projectId)),
approve: async (request, login) => { approved.push({ ...request, login }) },
+ approvedProjects: async (_env, tabId, repository) => approved
+ .filter(a => a.tabId === tabId && a.repository === repository.toLowerCase() && a.scope === 'project').map(a => a.projectId),
}
await app.register(superTabRoutes, { store, github: options.github === false ? null : tokens, approvals, signIn: options.signIn ?? null })
await app.ready()
@@ -310,6 +313,11 @@ describe('a queued start\'s preparation token', () => {
const { authorizeUrl, installUrl } = asked.json().data as { authorizeUrl: string; installUrl: string }
expect(installUrl).toMatch(/\/installations\/new\?state=/)
const state = new URL(authorizeUrl).searchParams.get('state')!
+ // The state is signed, not sealed, and goes to GitHub in the address: ids and the repository only, never the project's
+ // name (privacy review of #1980).
+ const carried = JSON.parse(Buffer.from(state.split('.')[0]!, 'base64url').toString())
+ expect(Object.keys(carried).sort()).toEqual(['autonomousEnv', 'exp', 'projectId', 'repository', 'scope', 'tabId', 'userId'])
+ expect(decodeURIComponent(authorizeUrl + installUrl)).not.toContain('Pool')
// Someone who cannot push is told so, and nothing is approved.
push = false
const refused = await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` })
@@ -319,6 +327,8 @@ describe('a queued start\'s preparation token', () => {
const done = await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` })
expect(done.statusCode).toBe(200)
expect(done.body).toContain('example/app approved')
+ // The page names the project it was approved for (local Team account run, 2026-10-28: 'This project can now use it').
+ expect(done.body).toContain('Teammates&#39; agents in Pool can now push to it.')
expect(env.approved).toEqual([expect.objectContaining({ tabId: tab, projectId: 'lead', repository: 'example/app', scope: 'project', login: 'olive' })])
expect((await prepare(env, tab, startId)).statusCode).toBe(200)
// A forged or missing state, or an installation without a sign-in, approves nothing.
@@ -347,6 +357,60 @@ describe('a queued start\'s preparation token', () => {
expect(env.approved).toEqual([])
})
+ // Local Team account run, 2026-10-28: a second project on a repository already approved for another asked again with no hint.
+ it('names the reader\'s other projects the repository is approved for, when it is not approved for this one', async () => {
+ const signIn = { authorizeUrl: (state: string) => `https://github.test/login/oauth/authorize?state=${state}`,
+ permission: async () => ({ login: 'olive', push: true }) } as unknown as GitHubSignIn
+ teamAccounts()
+ const env = await fresh({ approveAll: false, signIn })
+ const { tab } = await working(env)
+ const invited = await env.run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' } as Command)
+ await env.run(tab, { type: 'invite.accept', inviteId: invited.result.inviteId as string } as Command, host)
+ const project = async (name: string, visibility: 'public' | 'private') => {
+ const made = (await env.run(tab, { type: 'project.create', name, visibility, brief: '' } as Command)).result
+ await env.run(tab, { type: 'agent.add', conversationId: made.conversationId, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Lead',
+ configuration: config, lead: true, project: { cwd: `/work/${name}`, repositoryUrl: 'https://github.com/example/app.git' } } as Command)
+ return String(made.projectId)
+ }
+ const docs = await project('Docs', 'public'), secret = await project('Secret', 'private')
+ const approve = async (projectId: string) => {
+ const asked = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/${projectId}/github/approve`,
+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope: 'project' } })
+ const state = new URL((asked.json().data as { authorizeUrl: string }).authorizeUrl).searchParams.get('state')!
+ expect((await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` })).statusCode).toBe(200)
+ }
+ await approve('lead')
+ await approve(secret)
+ const read = async (user: AuthUser, projectId: string) => (await env.app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/projects/${projectId}/github`,
+ headers: { authorization: `Bearer ${user.sub}` } })).json().data
+ expect(await read(owner, docs)).toMatchObject({ state: 'not-approved', repository: 'example/app', approvedFor: ['Pilot', 'Secret'] })
+ // A teammate who cannot open Secret reads only Pilot.
+ expect(await read(host, docs)).toMatchObject({ state: 'not-approved', approvedFor: ['Pilot'] })
+ // An approved project says nothing of the others.
+ expect(await read(owner, 'lead')).not.toHaveProperty('approvedFor')
+ })
+
+ // Security re-check of #1976: a task lost to a usage limit keeps its id when it resumes, and its loss marked it ended,
+ // so after resuming it was refused GitHub tokens for 70 minutes.
+ it('gives a task resumed after a usage limit a fresh token, while the one from before the loss stays revoked', async () => {
+ const env = await fresh()
+ const { tab, group, worker, assignmentId } = await working(env)
+ const before = await ask(env, tab, worker)
+ expect(before.statusCode, before.body).toBe(200)
+ const resetAt = new Date(Date.now() + 1500).toISOString()
+ await env.run(tab, { type: 'agent.alert', agentId: worker, alert: 'limit', active: true, resetAt } as Command, host, worker)
+ await env.settled()
+ expect(env.github.revoked).toContain(before.json().data.token)
+ const lostAt = (await env.store.read(owner, tab)).state.conversations.find(c => c.id === group)!.assignment!.lost!.at
+ await new Promise(done => setTimeout(done, Date.parse(resetAt) - Date.now() + 50))
+ await env.run(tab, { type: 'work.resume', conversationId: group, assignmentId, lostAt } as Command, host, worker)
+ await env.settled()
+ const after = await ask(env, tab, worker)
+ expect(after.statusCode, after.body).toBe(200)
+ expect(after.json().data.token).not.toBe(before.json().data.token)
+ expect(env.github.issued.has(before.json().data.token)).toBe(false)
+ })
+
it('says when the server cannot approve, and refuses a project not on GitHub', async () => {
const env = await fresh({ approveAll: false })
const { tab } = await queued(env)
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index 9ca8e4064..0d7588b10 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -461,7 +461,8 @@ describe('a teammate\'s work and the machines that take it', () => {
describe('a project\'s repository, for its GitHub access', () => {
it('is read by those who may open the project, and by nobody else', async () => {
const f = await fixture()
- expect(await store.projectRepository(owner, f.tab, 'lead')).toEqual({ repositoryUrl: null, approvalRequired: false })
+ expect(await store.projectRepository(owner, f.tab, 'lead')).toEqual({ repositoryUrl: null, approvalRequired: false, name: expect.any(String),
+ others: [{ id: expect.any(String), name: 'Own' }] })
await run(f.tab, { type: 'tab.project', machineId: 'owner-host', project: { cwd: '/work', repositoryUrl: 'https://github.com/acme/app' } })
expect(await store.projectRepository(owner, f.tab, 'lead')).toMatchObject({ repositoryUrl: 'https://github.com/acme/app' })
expect(await store.projectRepository(person, f.tab, 'lead')).toMatchObject({ repositoryUrl: 'https://github.com/acme/app' })
diff --git a/backend/src/github/approvals.ts b/backend/src/github/approvals.ts
index ba68070a0..5eb5a52f1 100644
--- a/backend/src/github/approvals.ts
+++ b/backend/src/github/approvals.ts
@@ -113,6 +113,8 @@ export function githubSignIn(env: { GITHUB_APP_CLIENT_ID: string; GITHUB_APP_CLI
export interface Approvals {
approved(autonomousEnv: string, tabId: string, projectId: string, repository: string): Promise<boolean>
approve(request: ApprovalRequest, githubLogin: string): Promise<void>
+ /** The projects of [tabId] [repository] is approved for one by one (not those approved for the whole Swarm). */
+ approvedProjects(autonomousEnv: string, tabId: string, repository: string): Promise<string[]>
}
export class PrismaApprovals implements Approvals {
@@ -123,6 +125,12 @@ export class PrismaApprovals implements Approvals {
projectId: { in: [projectId, WHOLE_SWARM] } }, select: { id: true } })
}
+ async approvedProjects(autonomousEnv: string, tabId: string, repository: string): Promise<string[]> {
+ const rows = await this.db.gitHubRepositoryApproval.findMany({ where: { autonomousEnv, tabId, repository: repository.toLowerCase(),
+ projectId: { not: WHOLE_SWARM } }, select: { projectId: true } })
+ return rows.map(r => r.projectId)
+ }
+
async approve(request: ApprovalRequest, githubLogin: string): Promise<void> {
const projectId = request.scope === 'swarm' ? WHOLE_SWARM : request.projectId
const where = { autonomousEnv_tabId_repository_projectId: { autonomousEnv: request.autonomousEnv, tabId: request.tabId,
diff --git a/backend/src/github/holds.ts b/backend/src/github/holds.ts
index e9452cf4d..c6be656d4 100644
--- a/backend/src/github/holds.ts
+++ b/backend/src/github/holds.ts
@@ -16,6 +16,13 @@ export function workHolds(state: Pick<SuperTabState, 'agents' | 'conversations'>
})
}
+/** The holds [after] has that [before] did not: a task newly in progress, or one in progress again (resumed after a
+ * usage limit lost it, under the same id). */
+export function startedHolds(before: Pick<SuperTabState, 'agents' | 'conversations'>, after: Pick<SuperTabState, 'agents' | 'conversations'>): WorkHold[] {
+ const was = new Set(workHolds(before).map(hold => `${hold.agentId}:${hold.assignmentId}`))
+ return workHolds(after).filter(hold => !was.has(`${hold.agentId}:${hold.assignmentId}`))
+}
+
/** The holds in [before] that [after] no longer has: the task ended, went to another agent or attempt, or its agent left. */
export function endedHolds(before: Pick<SuperTabState, 'agents' | 'conversations'>, after: Pick<SuperTabState, 'agents' | 'conversations'>): WorkHold[] {
const still = new Set(workHolds(after).map(hold => `${hold.agentId}:${hold.assignmentId}`))
diff --git a/backend/src/github/projectAccess.ts b/backend/src/github/projectAccess.ts
index 88a6fd588..663080eaa 100644
--- a/backend/src/github/projectAccess.ts
+++ b/backend/src/github/projectAccess.ts
@@ -12,14 +12,15 @@ export type ProjectGitHubAccess =
| { state: 'not-github'; repositoryUrl: string }
| { state: 'covered'; repository: string }
| { state: 'not-installed'; repository: string; installUrl: string | null; canApprove: boolean }
- | { state: 'not-approved'; repository: string; canApprove: boolean }
+ | { state: 'not-approved'; repository: string; canApprove: boolean; approvedFor?: string[] }
| { state: 'unknown'; repository: string }
/** [app]: this server's GitHub App, null when it has none. [approved]: whether someone who can push to the repository
* approved it for this project (github/approvals.ts). [canApprove]: this server has the app's sign-in to approve with.
* [refresh]: a person asked to check again. */
export async function projectGitHubAccess(app: Pick<GitHubApp, 'resolve' | 'forget' | 'installUrl' | 'currentFullName'> | null, repositoryUrl: string | null,
- approval: { approved: (repository: string) => Promise<boolean>; canApprove: boolean }, refresh = false): Promise<ProjectGitHubAccess> {
+ approval: { approved: (repository: string) => Promise<boolean>; canApprove: boolean; approvedFor?: (repository: string) => Promise<string[]> },
+ refresh = false): Promise<ProjectGitHubAccess> {
if (!app) return { state: 'unavailable' }
if (!repositoryUrl) return { state: 'no-repository' }
const repository = githubRepository(repositoryUrl)
@@ -32,8 +33,10 @@ export async function projectGitHubAccess(app: Pick<GitHubApp, 'resolve' | 'forg
}
// Shown by its name now; approvals stay with the address the project names.
const shown = resolved.repository.fullName !== repository.fullName ? resolved.repository.fullName : await app.currentFullName(repository)
- return await approval.approved(repository.fullName.toLowerCase()) ? { state: 'covered', repository: shown }
- : { state: 'not-approved', repository: shown, canApprove: approval.canApprove }
+ if (await approval.approved(repository.fullName.toLowerCase())) return { state: 'covered', repository: shown }
+ // The reader's other projects it is approved for: approving is per project, so a second one asks again (2026-10-28).
+ const approvedFor = await approval.approvedFor?.(repository.fullName.toLowerCase()) ?? []
+ return { state: 'not-approved', repository: shown, canApprove: approval.canApprove, ...(approvedFor.length ? { approvedFor } : {}) }
} catch (error) {
// Wrong app credentials are the server's to fix and say so; GitHub not answering is never read as covered.
if (error instanceof GitHubAppError && error.code === 'GITHUB_APP_MISCONFIGURED') throw error
diff --git a/backend/src/github/tokens.test.ts b/backend/src/github/tokens.test.ts
index d43f5ddc6..59b60d7ad 100644
--- a/backend/src/github/tokens.test.ts
+++ b/backend/src/github/tokens.test.ts
@@ -110,25 +110,31 @@ describe('agent tokens', () => {
it('keeps tokens apart per agent and seals them in the cache', async () => {
const stored: string[] = []
const memory = new MemoryTokenCache()
- const spy: TokenCache = { get: k => memory.get(k), delete: k => memory.delete(k),
- set: async (k, v, ttl) => { stored.push(v); await memory.set(k, v, ttl) } }
+ const spy: TokenCache = { get: k => memory.get(k), delete: k => memory.delete(k), take: k => memory.take(k),
+ set: async (k, v, ttl) => { stored.push(v); await memory.set(k, v, ttl) },
+ add: async (k, v, ttl) => { stored.push(v); await memory.add(k, v, ttl) } }
const { tokens } = setup(spy)
const one = await tokens.issue(request('attempt-1', 'agent-1'))
const two = await tokens.issue(request('attempt-2', 'agent-2'))
expect(one.token).not.toBe(two.token)
- expect(stored).toHaveLength(2)
+ // Each token twice, as the agent's entry and among its task's minted tokens, both sealed.
+ expect(stored).toHaveLength(4)
for (const value of stored) {
expect(value).not.toContain('ghs_')
expect(value).not.toContain('attempt')
}
})
- it('revokes a token cached for an earlier task before minting for the new one', async () => {
+ it('mints apart for the agent\'s next task, and leaves the earlier task\'s token to that task\'s own end', async () => {
const { tokens, github } = setup()
const first = await tokens.issue(request('attempt-1'))
const second = await tokens.issue(request('attempt-2'))
expect(second.token).not.toBe(first.token)
+ // A request ends only its own task (third security review of #1976); the store ends the earlier one (workEnded).
+ expect(github.revoked).toEqual([])
+ await tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
expect(github.revoked).toEqual([first.token])
+ expect((await tokens.issue(request('attempt-2'))).token).toBe(second.token)
})
it('refuses a repository the app is not installed on, with the install link', async () => {
@@ -140,7 +146,8 @@ describe('agent tokens', () => {
it('still answers when the cache is away, and logs that without the token', async () => {
const broken: TokenCache = { get: async () => { throw new Error('redis down') }, set: async () => { throw new Error('redis down') },
- delete: async () => { throw new Error('redis down') } }
+ delete: async () => { throw new Error('redis down') }, add: async () => { throw new Error('redis down') },
+ take: async () => { throw new Error('redis down') } }
const { tokens, log } = setup(broken)
const issued = await tokens.issue(request())
expect(issued.token).toBe('ghs_fixture_1')
@@ -151,7 +158,8 @@ describe('agent tokens', () => {
it('ignores a cache entry it cannot open', async () => {
const memory = new MemoryTokenCache()
- const { tokens } = setup({ get: async () => 'garbage.value', set: (k, v, t) => memory.set(k, v, t), delete: k => memory.delete(k) })
+ const { tokens } = setup({ get: async () => 'garbage.value', set: (k, v, t) => memory.set(k, v, t), delete: k => memory.delete(k),
+ add: (k, v, t) => memory.add(k, v, t), take: async () => ['garbage.value'] })
expect((await tokens.issue(request())).token).toBe('ghs_fixture_1')
})
})
@@ -164,11 +172,148 @@ describe('revoking when a task ends', () => {
await tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }, { agentId: 'agent-2', assignmentId: 'older-attempt' },
{ agentId: 'agent-3', assignmentId: 'attempt-3' }])
expect(github.revoked).toEqual([one.token])
- // Forgotten: the next request for the same task mints a fresh token, and agent-2 keeps its own.
- expect((await tokens.issue(request('attempt-1', 'agent-1'))).token).not.toBe(one.token)
+ // Forgotten, and the ended task gets no token again; agent-2 keeps its own.
+ await expect(tokens.issue(request('attempt-1', 'agent-1'))).rejects.toMatchObject({ code: 'NO_ASSIGNMENT' })
expect((await tokens.issue(request('attempt-2', 'agent-2'))).token).toBe(two.token)
})
+ // Lead, 2026-10-28 (local Team account run): a renewal leaves the replaced token to its last ten minutes so a push in
+ // progress is not broken, but the task's end takes every token it held, replaced ones too.
+ it('revokes the replaced tokens of a renewed task with its current one when the task ends', async () => {
+ const { tokens, github, advance } = setup()
+ const first = await tokens.issue(request())
+ advance(60 * 60_000 - REUSE_MARGIN_MS + 1000)
+ const second = await tokens.issue(request())
+ advance(60 * 60_000 - REUSE_MARGIN_MS + 1000)
+ const third = await tokens.issue(request())
+ expect(github.revoked).toEqual([])
+ await tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ // The first had expired by then: GitHub is not asked about it.
+ expect(github.revoked.sort()).toEqual([second.token, third.token].sort())
+ expect(github.revoked).not.toContain(first.token)
+ })
+
+ it('revokes a renewed task\'s replaced token too when it ends after another task took the agent', async () => {
+ const { tokens, github, advance } = setup()
+ const first = await tokens.issue(request('attempt-1'))
+ advance(60 * 60_000 - REUSE_MARGIN_MS + 1000)
+ const second = await tokens.issue(request('attempt-1'))
+ await tokens.issue(request('attempt-2'))
+ await tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ expect(github.revoked.sort()).toEqual([first.token, second.token].sort())
+ })
+
+ // Security review of #1976: two backend instances share the cache. One ended the task and revoked the old token while the
+ // other was renewing it; the renewal then stored a new token, good for an hour, that nothing would revoke.
+ it('revokes and keeps no token minted for a task that another instance ended meanwhile', async () => {
+ let t = Date.parse('2026-10-24T12:00:00Z')
+ const now = () => t
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242', now })
+ github.installed.set('acme/app', 77)
+ const cache = new MemoryTokenCache(now), secret = randomBytes(32)
+ const instance = () => new GitHubTokens(fakeApp(key.privateKey, github, { now }), cache, { now, log: { warn: vi.fn() }, secret })
+ const ending = instance(), renewing = instance()
+ await renewing.issue(request())
+ t += 60 * 60_000 - REUSE_MARGIN_MS + 1000
+ // GitHub's answer to the renewal is held until the other instance has ended the task.
+ let answer!: () => void
+ const held = new Promise<void>(resolve => { answer = resolve })
+ const create = renewing.app.createToken.bind(renewing.app)
+ const minting = vi.spyOn(renewing.app, 'createToken').mockImplementation(async (...args) => { await held; return create(...args) })
+ const renewal = renewing.issue(request())
+ await vi.waitFor(() => expect(minting).toHaveBeenCalled())
+ await ending.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ answer()
+ await expect(renewal).rejects.toMatchObject({ code: 'NO_ASSIGNMENT' })
+ // Both tokens revoked, none kept: the ended task gets no token again on either instance.
+ expect(github.issued.size).toBe(0)
+ expect(github.revoked).toHaveLength(2)
+ await expect(ending.issue(request())).rejects.toMatchObject({ code: 'NO_ASSIGNMENT' })
+ await expect(renewing.issue(request())).rejects.toMatchObject({ code: 'NO_ASSIGNMENT' })
+ })
+
+ // Second security review of #1976: two instances renewing the same live task at once each minted a token, the second's
+ // cache write replaced the first's, and the task's end revoked only the one cached; the other stayed good for an hour.
+ it('revokes every token minted for a task when it ends, also two renewals that ran at once on two instances', async () => {
+ let t = Date.parse('2026-10-24T12:00:00Z')
+ const now = () => t
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242', now })
+ github.installed.set('acme/app', 77)
+ const cache = new MemoryTokenCache(now), secret = randomBytes(32)
+ const instance = () => new GitHubTokens(fakeApp(key.privateKey, github, { now }), cache, { now, log: { warn: vi.fn() }, secret })
+ const one = instance(), two = instance()
+ await one.issue(request())
+ t += 60 * 60_000 - REUSE_MARGIN_MS + 1000
+ // Both instances read the cache before either has minted: GitHub's answers are held until both are asking.
+ let answer!: () => void
+ const held = new Promise<void>(resolve => { answer = resolve })
+ const hold = (tokens: GitHubTokens) => {
+ const create = tokens.app.createToken.bind(tokens.app)
+ return vi.spyOn(tokens.app, 'createToken').mockImplementation(async (...args) => { await held; return create(...args) })
+ }
+ const asked = [hold(one), hold(two)]
+ const renewals = [one.issue(request()), two.issue(request())]
+ await vi.waitFor(() => { for (const spy of asked) expect(spy).toHaveBeenCalled() })
+ answer()
+ const [a, b] = await Promise.all(renewals)
+ expect(a!.token).not.toBe(b!.token)
+ await one.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ // The first token and both renewals: none left valid.
+ expect(github.issued.size).toBe(0)
+ })
+
+ // Third security review of #1976: an old task's request paused after its end check; the task ended and the agent's next
+ // task got a token; the old request then read the new task's entry, took it for an ended one, revoked its token and
+ // marked it ended, so the live task was refused for 70 minutes. A request ends only the task it was made for.
+ it('a stale request for an ended task leaves the agent\'s next task and its token alone', async () => {
+ const t = Date.parse('2026-10-24T12:00:00Z')
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242', now: () => t })
+ github.installed.set('acme/app', 77)
+ const memory = new MemoryTokenCache(() => t), secret = randomBytes(32)
+ // The stale instance's first read of the agent's entry waits until the next task has its token.
+ let resume!: () => void
+ const resumed = new Promise<void>(done => { resume = done })
+ let paused = false
+ const gated: TokenCache = { set: (k, v, ttl) => memory.set(k, v, ttl), delete: k => memory.delete(k), add: (k, v, ttl) => memory.add(k, v, ttl),
+ take: k => memory.take(k), get: async k => {
+ if (!paused && k === 'harness:github-token:v1:tab-1:agent-1') { paused = true; await resumed }
+ return memory.get(k)
+ } }
+ const make = (cache: TokenCache) => new GitHubTokens(fakeApp(key.privateKey, github, { now: () => t }), cache, { now: () => t, log: { warn: vi.fn() }, secret })
+ const stale = make(gated), fresh = make(memory)
+ const old = stale.issue(request('attempt-1'))
+ await vi.waitFor(() => expect(paused).toBe(true))
+ await fresh.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ const next = await fresh.issue(request('attempt-2'))
+ resume()
+ await expect(old).rejects.toMatchObject({ code: 'NO_ASSIGNMENT' })
+ // The next task's token is still good, and the next task still gets one.
+ expect(github.issued.has(next.token)).toBe(true)
+ await expect(fresh.issue(request('attempt-2'))).resolves.toMatchObject({ repository: 'acme/app' })
+ // The old request's own token went with its task; the next task's end takes every one of its own.
+ await fresh.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-2' }])
+ expect(github.issued.size).toBe(0)
+ })
+
+ // Security re-check of #1976: a task lost to a usage limit resumes under the same id. Its end and its resumption are
+ // handled in the order the store reported them, so a slow end never marks the resumed task ended again.
+ it('forgets a task\'s end when it resumes, even when the end was still being recorded', async () => {
+ const memory = new MemoryTokenCache()
+ let slow: (() => void) | null = null
+ const cache: TokenCache = { get: k => memory.get(k), delete: k => memory.delete(k), add: (k, v, t) => memory.add(k, v, t), take: k => memory.take(k),
+ set: async (k, v, t) => { if (k.includes(':released:')) await new Promise<void>(done => { slow = done }); await memory.set(k, v, t) } }
+ const { tokens, github } = setup(cache)
+ const before = await tokens.issue(request())
+ const ended = tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ const resumed = tokens.resume('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ await vi.waitFor(() => expect(slow).not.toBeNull())
+ slow!()
+ await Promise.all([ended, resumed])
+ expect(github.revoked).toEqual([before.token])
+ const after = await tokens.issue(request())
+ expect(after.token).not.toBe(before.token)
+ })
+
it('logs a failed revoke without the token, drops it anyway and never throws', async () => {
const { tokens, github, log } = setup()
const issued = await tokens.issue(request())
@@ -178,7 +323,8 @@ describe('revoking when a task ends', () => {
why: 'task ended', code: 'GITHUB_UNAVAILABLE' })
expect(JSON.stringify(log.warn.mock.calls)).not.toContain(issued.token)
github.control.revokeStatus = 204
- expect((await tokens.issue(request())).token).not.toBe(issued.token)
+ // Dropped: the agent's next task gets a token of its own, not this one.
+ expect((await tokens.issue(request('attempt-2'))).token).not.toBe(issued.token)
})
it('refuses a sealing key of the wrong size', () => {
@@ -188,6 +334,32 @@ describe('revoking when a task ends', () => {
})
describe('token caches', () => {
+ it('adds to a set and takes it whole, in memory and in one Redis transaction each', async () => {
+ let t = 0
+ const memory = new MemoryTokenCache(() => t)
+ await memory.add('s', 'a', 1000)
+ await memory.add('s', 'b', 1000)
+ expect((await memory.take('s')).sort()).toEqual(['a', 'b'])
+ expect(await memory.take('s')).toEqual([])
+ await memory.add('s', 'a', 1000)
+ t = 1000
+ expect(await memory.take('s')).toEqual([])
+ const queued: unknown[][] = []
+ const results: Array<[Error | null, unknown]>[] = [[[null, 1], [null, 1]], [[null, ['x', 'y']], [null, 1]], [[new Error('READONLY'), null]]]
+ const multi = () => {
+ const chain = { sadd: (...a: unknown[]) => (queued.push(['sadd', ...a]), chain), pexpire: (...a: unknown[]) => (queued.push(['pexpire', ...a]), chain),
+ smembers: (...a: unknown[]) => (queued.push(['smembers', ...a]), chain), del: (...a: unknown[]) => (queued.push(['del', ...a]), chain),
+ exec: async () => results.shift() ?? null }
+ return chain
+ }
+ const redis = new RedisTokenCache({ multi } as never)
+ await redis.add('s', 'm', 1234.7)
+ expect(await redis.take('s')).toEqual(['x', 'y'])
+ expect(queued).toEqual([['sadd', 's', 'm'], ['pexpire', 's', 1234], ['smembers', 's'], ['del', 's']])
+ await expect(redis.take('s')).rejects.toThrow('READONLY')
+ await expect(redis.take('s')).rejects.toThrow('discarded')
+ })
+
it('expires memory entries', async () => {
let t = 0
const cache = new MemoryTokenCache(() => t)
diff --git a/backend/src/github/tokens.ts b/backend/src/github/tokens.ts
index 2c28f8e89..9790894cd 100644
--- a/backend/src/github/tokens.ts
+++ b/backend/src/github/tokens.ts
@@ -17,11 +17,16 @@ export interface TokenCache {
get(key: string): Promise<string | null>
set(key: string, value: string, ttlMs: number): Promise<void>
delete(key: string): Promise<void>
+ /** Adds [member] to the set at [key] in one step, and keeps the set [ttlMs] from now. */
+ add(key: string, member: string, ttlMs: number): Promise<void>
+ /** Takes the set at [key] whole, removing it in the same step: two callers never both get a member. */
+ take(key: string): Promise<string[]>
}
/** One process's cache, for tests and a backend without Redis. */
export class MemoryTokenCache implements TokenCache {
private readonly entries = new Map<string, { value: string; until: number }>()
+ private readonly sets = new Map<string, { members: Set<string>; until: number }>()
constructor(private readonly now: () => number = Date.now) {}
async get(key: string) {
const entry = this.entries.get(key)
@@ -30,14 +35,39 @@ export class MemoryTokenCache implements TokenCache {
}
async set(key: string, value: string, ttlMs: number) { this.entries.set(key, { value, until: this.now() + ttlMs }) }
async delete(key: string) { this.entries.delete(key) }
+ async add(key: string, member: string, ttlMs: number) {
+ const set = this.sets.get(key)
+ const members = set && set.until > this.now() ? set.members : new Set<string>()
+ this.sets.set(key, { members: members.add(member), until: this.now() + ttlMs })
+ }
+ async take(key: string) {
+ const set = this.sets.get(key)
+ this.sets.delete(key)
+ return set && set.until > this.now() ? [...set.members] : []
+ }
}
/** The backend's shared Redis (lib/bus.ts `pub`), which fails fast rather than queueing while Redis is away. */
export class RedisTokenCache implements TokenCache {
- constructor(private readonly redis: Pick<Redis, 'get' | 'set' | 'del'>) {}
+ constructor(private readonly redis: Pick<Redis, 'get' | 'set' | 'del' | 'multi'>) {}
async get(key: string) { return this.redis.get(key) }
async set(key: string, value: string, ttlMs: number) { await this.redis.set(key, value, 'PX', Math.max(1, Math.floor(ttlMs))) }
async delete(key: string) { await this.redis.del(key) }
+ async add(key: string, member: string, ttlMs: number) {
+ failed(await this.redis.multi().sadd(key, member).pexpire(key, Math.max(1, Math.floor(ttlMs))).exec())
+ }
+ async take(key: string) {
+ // SMEMBERS and DEL in one transaction: no other instance reads or adds between them.
+ const members = failed(await this.redis.multi().smembers(key).del(key).exec())[0]
+ return Array.isArray(members) ? members.filter((m): m is string => typeof m === 'string') : []
+ }
+}
+
+/** A Redis transaction's results, or its first error thrown. */
+function failed(results: Array<[Error | null, unknown]> | null): unknown[] {
+ if (!results) throw new Error('The Redis transaction was discarded.')
+ for (const [error] of results) if (error) throw error
+ return results.map(([, value]) => value)
}
/** What one agent's task may use. */
@@ -57,6 +87,9 @@ interface Entry { token: string; expiresAt: string; repository: string; assignme
/** A token is handed out again until this long before it expires, so whoever holds it has at least that long. */
export const REUSE_MARGIN_MS = 10 * 60_000
const KEY_PREFIX = 'harness:github-token:v1'
+/** How long a task's end is remembered: longer than any token GitHub gives (an hour), so no mint outlives it unseen. */
+const RELEASED_MS = 70 * 60_000
+const RELEASED = 'released'
export interface GitHubTokensOptions {
now?: () => number
@@ -70,6 +103,8 @@ export class GitHubTokens {
private readonly log: Pick<typeof logger, 'warn'>
private readonly secret: Buffer
private readonly flights = new Map<string, Promise<IssuedToken>>()
+ /** Each task's end and resumption, in the order the store reported them on this instance. */
+ private readonly lifecycle = new Map<string, Promise<void>>()
constructor(readonly app: GitHubApp, private readonly cache: TokenCache, options: GitHubTokensOptions) {
this.now = options.now ?? Date.now
@@ -79,26 +114,42 @@ export class GitHubTokens {
}
private key(tabId: string, agentId: string) { return `${KEY_PREFIX}:${tabId}:${agentId}` }
+ /** Every token minted for one task, sealed, in one shared set: what the task's end revokes (security review of #1976: two
+ * instances renewing at once each minted one, and the cached entry kept only the last). */
+ private mintedKey(tabId: string, agentId: string, assignmentId: string) { return `${KEY_PREFIX}:minted:${tabId}:${agentId}:${assignmentId}` }
+ private releasedKey(tabId: string, agentId: string, assignmentId: string) { return `${KEY_PREFIX}:released:${tabId}:${agentId}:${assignmentId}` }
+
+ /** Whether the task's end was recorded (release). A cache that cannot say is read as not ended, as before. */
+ private async released(request: TokenRequest): Promise<boolean> {
+ try { return await this.cache.get(this.releasedKey(request.tabId, request.agentId, request.assignmentId)) === RELEASED } catch { return false }
+ }
- private seal(entry: Entry): string {
+ private ended(): GitHubAppError { return new GitHubAppError('NO_ASSIGNMENT', 'This agent has no task in progress.', 409) }
+
+ private seal(value: unknown): string {
const iv = randomBytes(12)
const cipher = createCipheriv('aes-256-gcm', this.secret, iv)
- const body = Buffer.concat([cipher.update(JSON.stringify(entry), 'utf8'), cipher.final()])
+ const body = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()])
return [iv, cipher.getAuthTag(), body].map(part => part.toString('base64url')).join('.')
}
- private open(value: string | null): Entry | null {
+ private unseal(value: string | null): Record<string, unknown> | null {
if (!value) return null
try {
const [iv, tag, body] = value.split('.').map(part => Buffer.from(part, 'base64url'))
const decipher = createDecipheriv('aes-256-gcm', this.secret, iv!)
decipher.setAuthTag(tag!)
- const entry = JSON.parse(Buffer.concat([decipher.update(body!), decipher.final()]).toString('utf8')) as Entry
- return typeof entry.token === 'string' && typeof entry.expiresAt === 'string' && typeof entry.assignmentId === 'string'
- && typeof entry.repository === 'string' ? entry : null
+ const opened = JSON.parse(Buffer.concat([decipher.update(body!), decipher.final()]).toString('utf8')) as unknown
+ return opened && typeof opened === 'object' ? opened as Record<string, unknown> : null
} catch { return null }
}
+ private open(value: string | null): Entry | null {
+ const entry = this.unseal(value)
+ return entry && typeof entry.token === 'string' && typeof entry.expiresAt === 'string' && typeof entry.assignmentId === 'string'
+ && typeof entry.repository === 'string' ? entry as unknown as Entry : null
+ }
+
private async read(key: string): Promise<Entry | null> {
try { return this.open(await this.cache.get(key)) } catch (error) {
this.log.warn('[github] token cache unreadable', { error: error instanceof Error ? error.message : String(error) })
@@ -120,16 +171,21 @@ export class GitHubTokens {
private async mint(key: string, request: TokenRequest): Promise<IssuedToken> {
const repository = request.repository.fullName
+ if (await this.released(request)) throw this.ended()
let actual = request.repository
const cached = await this.read(key)
let entry: Entry | null = null
if (cached && cached.assignmentId === request.assignmentId && cached.repository === repository) {
+ // Close to its end, it is left to expire: the agent may still be using it, in a push that took it before this renewal.
+ // It stays among the task's minted tokens, so the task's end revokes it too (Lead, 2026-10-28).
if (Date.parse(cached.expiresAt) - this.now() > REUSE_MARGIN_MS) entry = cached
- // Close to its end, it is left to expire: the agent may still be using it.
- } else if (cached) {
- await this.revoke(request.tabId, request.agentId, cached, 'replaced')
- await this.forget(key)
+ } else if (cached?.assignmentId === request.assignmentId) {
+ // This task's, for another repository (the project's address changed): every token minted for it goes now.
+ await this.revokeTask(request.tabId, request.agentId, cached.assignmentId, 'replaced', false, cached)
}
+ // Another task's entry is not this request's to end: a request may have waited across its own task's end and the
+ // agent's next task, and ending what it found there revoked the live task's token and refused it (third security review
+ // of #1976). That task's own end (release) takes every token minted for it, whichever entry is cached then.
if (!entry) {
// Under the name GitHub knows it by now (app.ts `resolve`); the agent's checkout keeps the name it was given, which
// GitHub still answers for git.
@@ -138,6 +194,11 @@ export class GitHubTokens {
actual = resolved.repository
const minted = await this.app.createToken(resolved.installation, actual)
entry = { ...minted, repository, assignmentId: request.assignmentId }
+ // Registered before anything else: the task's end takes this set whole, whichever instance minted what.
+ try { await this.cache.add(this.mintedKey(request.tabId, request.agentId, request.assignmentId), this.seal({ token: entry.token, expiresAt: entry.expiresAt }), RELEASED_MS) } catch (error) {
+ this.log.warn('[github] token not registered', { tabId: request.tabId, agentId: request.agentId, repository,
+ error: error instanceof Error ? error.message : String(error) })
+ }
const ttl = Date.parse(minted.expiresAt) - this.now()
if (ttl > 0) {
try { await this.cache.set(key, this.seal(entry), ttl) } catch (error) {
@@ -146,6 +207,14 @@ export class GitHubTokens {
error: error instanceof Error ? error.message : String(error) })
}
}
+ // Stored first, then checked: a task ended on another instance meanwhile (release marks it, then revokes what is
+ // stored) either finds this token there or is seen here, so a token minted for an ended task never stays valid
+ // (security review of #1976: a renewal in flight across that end kept a token good for an hour).
+ if (await this.released(request)) {
+ await this.revokeTokens(request.tabId, request.agentId, repository, [entry.token], 'task ended while minting')
+ if ((await this.read(key))?.token === entry.token) await this.forget(key)
+ throw this.ended()
+ }
}
const branch = await this.app.defaultBranch(actual, entry.token)
return { token: entry.token, expiresAt: entry.expiresAt, repository, defaultBranch: branch.branch,
@@ -164,11 +233,35 @@ export class GitHubTokens {
return { ...minted, repository: repository.fullName }
}
- private async revoke(tabId: string, agentId: string, entry: Entry, why: string): Promise<void> {
- try { await this.app.revoke(entry.token) } catch (error) {
- this.log.warn('[github] token revoke failed', { tabId, agentId, repository: entry.repository, why,
- code: error instanceof GitHubAppError ? error.code : 'ERROR' })
+ private async revokeTokens(tabId: string, agentId: string, repository: string, tokens: readonly string[], why: string): Promise<void> {
+ for (const token of new Set(tokens)) {
+ try { await this.app.revoke(token) } catch (error) {
+ this.log.warn('[github] token revoke failed', { tabId, agentId, repository, why, code: error instanceof GitHubAppError ? error.code : 'ERROR' })
+ }
+ }
+ }
+
+ /**
+ * Revokes every unexpired token minted for one task, taken whole from the shared set, and the cached one ([entry], also
+ * from before that set), and forgets the cached one. [ended]: the task is over, so it is marked first: a mint finishing
+ * on another instance after the mark revokes its own token (mint).
+ */
+ private async revokeTask(tabId: string, agentId: string, assignmentId: string, why: string, ended: boolean, entry: Entry | null): Promise<void> {
+ if (ended) {
+ try { await this.cache.set(this.releasedKey(tabId, agentId, assignmentId), RELEASED, RELEASED_MS) } catch (error) {
+ this.log.warn('[github] task end not recorded', { tabId, agentId, error: error instanceof Error ? error.message : String(error) })
+ }
}
+ let minted: string[] = []
+ try { minted = await this.cache.take(this.mintedKey(tabId, agentId, assignmentId)) } catch (error) {
+ this.log.warn('[github] minted tokens unreadable', { tabId, agentId, error: error instanceof Error ? error.message : String(error) })
+ }
+ const live = minted.map(value => this.unseal(value))
+ .filter((t): t is { token: string; expiresAt: string } => typeof t?.token === 'string' && typeof t.expiresAt === 'string')
+ .filter(t => Date.parse(t.expiresAt) > this.now()).map(t => t.token)
+ const cached = entry?.assignmentId === assignmentId ? [entry.token] : []
+ await this.revokeTokens(tabId, agentId, entry?.repository ?? '', [...cached, ...live], why)
+ if (entry) await this.forget(this.key(tabId, agentId))
}
private async forget(key: string): Promise<void> {
@@ -180,13 +273,32 @@ export class GitHubTokens {
/** The tasks that ended in [tabId] (done, cancelled, stopped, reassigned, or the agent removed): each one's cached token is
* revoked and forgotten. Never throws; a failed revoke is logged without the token and leaves the token to expire. */
async release(tabId: string, ended: readonly WorkHold[]): Promise<void> {
- for (const hold of ended) {
- const key = this.key(tabId, hold.agentId)
- const entry = await this.read(key)
- if (!entry || entry.assignmentId !== hold.assignmentId) continue
- await this.revoke(tabId, hold.agentId, entry, 'task ended')
- await this.forget(key)
- }
+ await Promise.all(ended.map(hold => this.inOrder(tabId, hold, async () => {
+ const entry = await this.read(this.key(tabId, hold.agentId))
+ await this.revokeTask(tabId, hold.agentId, hold.assignmentId, 'task ended', true, entry?.assignmentId === hold.assignmentId ? entry : null)
+ })))
+ }
+
+ /** Tasks in progress again under the same id (resumed after a usage limit lost them): their end is forgotten, so they get
+ * tokens again. Every token from before the loss stays revoked; nothing minted before it is handed out again (security
+ * re-check of #1976: a resumed task was refused tokens for 70 minutes). Never throws. */
+ async resume(tabId: string, started: readonly WorkHold[]): Promise<void> {
+ await Promise.all(started.map(hold => this.inOrder(tabId, hold, async () => {
+ try { await this.cache.delete(this.releasedKey(tabId, hold.agentId, hold.assignmentId)) } catch (error) {
+ this.log.warn('[github] task resumption not recorded', { tabId, agentId: hold.agentId, error: error instanceof Error ? error.message : String(error) })
+ }
+ })))
+ }
+
+ /** Runs [work] after this task's earlier end or resumption on this instance: a loss and the resumption after it are
+ * reported in that order, and the end's mark must not land after the resumption cleared it. */
+ private inOrder(tabId: string, hold: WorkHold, work: () => Promise<void>): Promise<void> {
+ const key = `${tabId}:${hold.agentId}:${hold.assignmentId}`
+ const next = (this.lifecycle.get(key) ?? Promise.resolve()).then(work, work)
+ const settled = next.catch(() => undefined)
+ this.lifecycle.set(key, settled)
+ void settled.then(() => { if (this.lifecycle.get(key) === settled) this.lifecycle.delete(key) })
+ return next
}
}
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 881e314ac..1ae45b079 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -138,6 +138,7 @@ async function productionStore(github: GitHubTokens | null): Promise<SuperTabSto
return new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),
// A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.
{ workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) },
+ workStarted: (tabId, started) => { void github?.resume(tabId, started).catch(error => logger.warn('[github] resume failed', { tabId, error: String(error) })) },
// A team account has no git login of its own: without the app it takes no teammates' work.
teamAccountsIdle: !github,
// Every server answers the quiet delivery poll from any server's full one, and tells the agent's machine of new work
@@ -218,7 +219,11 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
(req, reply) => respond(reply, async () => {
const project = await store.projectRepository(req.user!, req.params.tabId, req.params.projectId)
return projectGitHubAccess(github?.app ?? null, project.repositoryUrl, { canApprove: !!signIn,
- approved: async repository => !project.approvalRequired || approvals.approved(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository) },
+ approved: async repository => !project.approvalRequired || approvals.approved(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository),
+ approvedFor: async repository => {
+ const ids = await approvals.approvedProjects(req.user!.autonomousEnv, req.params.tabId, repository)
+ return project.others.filter(other => ids.includes(other.id)).map(other => other.name)
+ } },
req.query.refresh === '1')
}))
// Approving a project's repository: the person signs in to GitHub through the app (or installs it, which signs them in
@@ -251,8 +256,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
return page(`You can't push to ${named.fullName}`, 'So you can\'t approve it for this Swarm. Someone who can push to it can.', 403)
}
await approvals.approve(request, seen.login)
- return page(`${named.fullName} approved`, request.scope === 'swarm'
- ? 'Every project in this Swarm can now use it. You can go back to Harness.' : 'This project can now use it. You can go back to Harness.')
+ // Named, so the person knows which project it was for (local Team account run, 2026-10-28: 'This project can now use it').
+ const where = request.scope === 'swarm' ? 'every project in this Swarm'
+ : await store.projectNameFor(request.userId, request.autonomousEnv as AuthUser['autonomousEnv'], request.tabId, request.projectId).catch(() => null) ?? 'this project'
+ return page(`${named.fullName} approved`, `Teammates' agents in ${where} can now push to it. You can go back to Harness.`)
})
app.get<{ Params: z.infer<typeof machineParams> }>('/api/super-tabs/:tabId/machines/:machineId/removal', { preHandler: validateParams(machineParams) },
(req, reply) => respond(reply, () => store.machineRemoval(req.user!, req.params.tabId, req.params.machineId)))
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 9d28d1ee5..b968c9db0 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -39,7 +39,7 @@ import {
import type { HoldReason } from './holdReason.js'
import { stuck } from './deliverySettle.js'
import { agentDisplayName } from './agentNames.js'
-import { endedHolds, HOLDING, type WorkHold } from '../github/holds.js'
+import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'
import { accrueLent } from './leaderboard/lent.js'
import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, TERMINAL_RECHECK_MS, type TerminalEffect } from './terminal.js'
import { closeAssignment, closeUnassignedStart, readDecision, recentDecisions, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
@@ -223,6 +223,9 @@ export interface SuperTabStoreHooks {
/** Tasks that stopped being in an agent's hands with this write (github/holds.ts): done, cancelled, stopped, given to
* another attempt, or their agent removed. Called after the write commits; it must not throw. */
workEnded?: (tabId: string, ended: WorkHold[]) => void
+ /** Tasks newly in progress, or in progress again under the same id (resumed after a usage limit): GitHub tokens forget
+ * that such a task ended (github/tokens.ts resume). */
+ workStarted?: (tabId: string, started: WorkHold[]) => void
/** No Harness GitHub App on this server: a Mac's Harness Team account joins no Swarm and takes no teammates' work, since
* it has no git login to fetch or push with (commands.ts `teamAccountsIdle`). */
teamAccountsIdle?: boolean
@@ -827,10 +830,11 @@ export class SuperTabStore {
private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
workspaceLeave = false) {
const { operationId, command } = operationSchema.parse(input)
- let ended: WorkHold[] = []
+ let ended: WorkHold[] = [], started: WorkHold[] = []
const done = await transaction(this.db, async tx => {
- // A retried attempt starts again: only the attempt that commits says which tasks ended.
+ // A retried attempt starts again: only the attempt that commits says which tasks ended or started.
ended = []
+ started = []
const stamp = clock.next()
const first = await this.load(tx, user, tabId, namedFor(command))
const loaded = await this.ensure(tx, first, await this.moreNamed(tx, tabId, first.state, command))
@@ -1136,6 +1140,7 @@ export class SuperTabStore {
}
}
ended = endedHolds(original, effects.state)
+ started = startedHolds(original, effects.state)
await writeRouteEffects(tx, tabId, effects.routeDecisions, context.now)
if (command.type === 'agent.startFailed') {
const start = original.starts?.find(s => s.id === command.startId)
@@ -1224,9 +1229,17 @@ export class SuperTabStore {
return { result: effects.result, parts: committed.written, lastChangedAt: stamp }
})
this.endWork(tabId, ended)
+ this.startWork(tabId, started)
return done
}
+ private startWork(tabId: string, started: WorkHold[]): void {
+ if (!started.length || !this.hooks.workStarted) return
+ try { this.hooks.workStarted(tabId, started) } catch (error) {
+ logger.warn('[super-tab] work-started hook failed', { tabId, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+
private endWork(tabId: string, ended: WorkHold[]): void {
if (!ended.length || !this.hooks.workEnded) return
try { this.hooks.workEnded(tabId, ended) } catch (error) {
@@ -1766,16 +1779,29 @@ export class SuperTabStore {
* a private project's members only. Null when it has none yet. [approvalRequired]: whether this Swarm's projects need a
* repository approved before the app gives them tokens, rolled out with the team account (machines.ts
* `teamAccountRequired`). */
- async projectRepository(user: AuthUser, tabId: string, projectId: string): Promise<{ repositoryUrl: string | null; approvalRequired: boolean }> {
+ /** `name`: the project's own, for the page after approving its repository (routes/superTabs.ts). `others`: the reader's
+ * other projects in the Swarm, those they may open, to name the ones its repository is approved for. */
+ async projectRepository(user: AuthUser, tabId: string, projectId: string):
+ Promise<{ repositoryUrl: string | null; approvalRequired: boolean; name: string; others: Array<{ id: string; name: string }> }> {
return transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId)
const actor = await this.actor(tx, user, state)
- const project = visibleState(state, actor, this.now()).projects?.find(p => p.id === projectId)
- ?? fail('NOT_FOUND', 'This project is unavailable.', 404)
- return { repositoryUrl: project.repository?.repositoryUrl ?? null, approvalRequired: teamAccountRequired(state) }
+ const projects = visibleState(state, actor, this.now()).projects ?? []
+ const project = projects.find(p => p.id === projectId) ?? fail('NOT_FOUND', 'This project is unavailable.', 404)
+ return { repositoryUrl: project.repository?.repositoryUrl ?? null, approvalRequired: teamAccountRequired(state), name: project.name,
+ others: projects.filter(p => p.id !== projectId).map(p => ({ id: p.id, name: p.name })) }
})
}
+ /** A project's name as [userId] may see it now, for the page GitHub sends them back to after approving its repository
+ * (routes/superTabs.ts). Read here, not carried in the sign-in's state, which GitHub's addresses expose (privacy review of
+ * #1980). Null when they may not see it any more, or it is gone. */
+ async projectNameFor(userId: string, autonomousEnv: AuthUser['autonomousEnv'], tabId: string, projectId: string): Promise<string | null> {
+ const person = await this.db.user.findUnique({ where: { id: userId }, select: { email: true } })
+ if (!person) return null
+ try { return (await this.projectRepository({ sub: userId, email: person.email, role: 'user', autonomousEnv }, tabId, projectId)).name } catch { return null }
+ }
+
async machineRemoval(user: AuthUser, tabId: string, machineId: string) {
return transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId)
diff --git a/cli/src/lib/swarmGitHub.spec.ts b/cli/src/lib/swarmGitHub.spec.ts
index 8a7754b6d..f53b5eb3a 100644
--- a/cli/src/lib/swarmGitHub.spec.ts
+++ b/cli/src/lib/swarmGitHub.spec.ts
@@ -1,9 +1,9 @@
import { spawnSync } from 'node:child_process'
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
-import { GIT_HOOK_NAMES, gitConfigParameters, shellWord, swarmGitHubLaunch, swarmGitHubSessionDir, swarmGitPrepareEnv, writeSessionGitHub, writeSwarmGitHubTools } from './swarmGitHub.js'
+import { GIT_HOOK_NAMES, gitConfigParameters, revokeGitHubToken, shellWord, swarmGitHubLaunch, swarmGitHubSessionDir, swarmGitPrepareEnv, writeSessionGitHub, writeSwarmGitHubTools } from './swarmGitHub.js'
// Real git against folders made here, with a home of its own and no system config: never this machine's git settings,
// and nothing reaches github.com (only `git credential fill` and `git ls-remote --get-url`, which make no connection).
@@ -239,3 +239,38 @@ describe('a Swarm session\'s launch', () => {
expect(existsSync(join(dataDir, 'swarm-github'))).toBe(false)
})
})
+
+// Review of #1998: a start held between its launch preparation and its session's registration could look untouched for 15
+// minutes and lose its folder (superTabs/github.ts emptyStopped). Each launch preparation marks the folder as just used.
+describe('a session\'s GitHub folder at launch', () => {
+ it('is marked as just used every time a launch is prepared', () => {
+ const dataDir = mkdtempSync(join(tmpdir(), 'swarm-github-launch-'))
+ try {
+ const tools = { dataDir, command: 'harness', port: 18473, machineId: 'm1' }
+ expect(swarmGitHubLaunch('harness-codex-held', tools, 'darwin')).not.toBeNull()
+ const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-held')!
+ const old = new Date(Date.now() - 20 * 60_000)
+ utimesSync(dir, old, old)
+ swarmGitHubLaunch('harness-codex-held', tools, 'darwin')
+ expect(Date.now() - statSync(dir).mtimeMs).toBeLessThan(60_000)
+ } finally { rmSync(dataDir, { recursive: true, force: true }) }
+ })
+})
+
+describe('revoking a Harness GitHub App token', () => {
+ const token = `ghs_${'a'.repeat(36)}`
+ it('asks GitHub to revoke it with the token itself, and takes a token already gone as revoked', async () => {
+ const sent: Array<[string, RequestInit]> = []
+ const answer = (status: number) => (async (url: string | URL | Request, init?: RequestInit) => {
+ sent.push([String(url), init!]); return new Response(null, { status })
+ }) as typeof fetch
+ await revokeGitHubToken(token, answer(204))
+ expect(sent[0]![0]).toBe('https://api.github.com/installation/token')
+ expect(sent[0]![1]).toMatchObject({ method: 'DELETE', headers: expect.objectContaining({ Authorization: `Bearer ${token}` }) })
+ await revokeGitHubToken(token, answer(401))
+ await expect(revokeGitHubToken(token, answer(500))).rejects.toThrow('GitHub answered 500')
+ // Nothing that is not a token is sent anywhere.
+ await revokeGitHubToken('not a token', answer(204))
+ expect(sent).toHaveLength(3)
+ })
+})
diff --git a/cli/src/lib/swarmGitHub.ts b/cli/src/lib/swarmGitHub.ts
index f8114e885..3282012c5 100644
--- a/cli/src/lib/swarmGitHub.ts
+++ b/cli/src/lib/swarmGitHub.ts
@@ -16,7 +16,7 @@
*
* The variable `GIT_CONFIG_KEY_n` is not used: Codex leaves out of its commands every variable whose name contains KEY.
*/
-import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { env } from '../config/env.js'
import { daemonCommand } from './daemonCommand.js'
@@ -170,6 +170,18 @@ const TOKEN = /^[A-Za-z0-9_][A-Za-z0-9_.-]{19,4095}$/
const COMMIT_NAME = /^[a-z0-9][a-z0-9-]{0,99}\[bot\]$/
const COMMIT_EMAIL = /^[0-9]{1,20}\+[a-z0-9][a-z0-9-]{0,99}\[bot\]@users\.noreply\.github\.com$/
+/**
+ * Revoke a Harness GitHub App installation token with the token itself (GitHub's `DELETE /installation/token`): the
+ * read-only one a machine cloned a teammate's project with, done with once the clone and the fetch are (local Team account
+ * run, 2026-10-28: it stayed good for its hour). Best effort: a token GitHub does not revoke still expires within the hour.
+ */
+export async function revokeGitHubToken(token: string, send: typeof fetch = fetch): Promise<void> {
+ if (!TOKEN.test(token)) return
+ const answer = await send('https://api.github.com/installation/token', { method: 'DELETE', signal: AbortSignal.timeout(10_000),
+ headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'harness' } })
+ if (answer.status !== 204 && answer.status !== 401) throw new Error(`GitHub answered ${answer.status} to revoking the token`)
+}
+
/** The session's gh login: [token] for github.com, or none. And, when given, the trailers its commits get and who they are
* by ([commitAs]: the app's bot account, which the server gives a Harness Team account, as it has no git identity of its
* own: its commits read "Harness Team <harnessteam@<host>.local>" before, PR #1934). Without one, git's own stands. */
@@ -205,6 +217,10 @@ export function swarmGitHubLaunch(key: string, tools: SwarmGitHubTools = default
if (platform === 'win32' || !dir) return null
const { helper, hooks } = writeSwarmGitHubTools(tools)
if (!existsSync(join(dir, 'gh', 'hosts.yml'))) writeSessionGitHub(dir, null)
+ // Marked as just used: a start held before its session is registered must not look like a folder left behind
+ // (superTabs/github.ts removes those once untouched for 15 minutes; review of #1998).
+ const now = new Date()
+ utimesSync(dir, now, now)
return {
env: {
GIT_CONFIG_PARAMETERS: gitConfigParameters(helper, hooks, join(dir, 'gitconfig')),
diff --git a/cli/src/superTabs/github.spec.ts b/cli/src/superTabs/github.spec.ts
index 957eb52a6..57a98b11f 100644
--- a/cli/src/superTabs/github.spec.ts
+++ b/cli/src/superTabs/github.spec.ts
@@ -1,10 +1,10 @@
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { afterAll, describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import type { RegisteredSession } from '../lib/registry.js'
-import { swarmGitHubSessionDir } from '../lib/swarmGitHub.js'
+import { swarmGitHubLaunch, swarmGitHubSessionDir, writeSessionGitHub } from '../lib/swarmGitHub.js'
import { GitHubTokenRefresher, githubToken, RENEW_BELOW_MS } from './github.js'
import { hostForm } from './fixtures/read/index.js'
import { HostFeed } from './hostFeed.js'
@@ -25,16 +25,28 @@ const row = (tabId: string, agentId: string, harnessId = 'harness-1', extra: Rec
/** The machine's host form and Swarm reads, as the service hands them over. */
const sourcesOf = (core: CoreApi, now?: () => number) => { const held = { feed: new HostFeed(core, 'machine-1', { now }), reads: new SwarmReads(core) }; return () => held }
const HOST = '/api/super-tabs/hosts/machine-1/changes'
+/** Makes [dir] and everything in it look untouched for [ms]. */
+const age = (dir: string, ms: number) => {
+ const then = new Date(Date.now() - ms)
+ for (const path of [dir, join(dir, 'gh'), join(dir, 'gh', 'hosts.yml'), join(dir, 'gh', 'config.yml'), join(dir, 'gitconfig'), join(dir, 'trailers')]) {
+ if (existsSync(path)) utimesSync(path, then, then)
+ }
+}
/** A core whose backend answers by path; one session per harness id, started to use the app unless `plain`. */
function setup(routes: (method: string, path: string, body: unknown) => Reply, sessions: Array<{ id: string; plain?: boolean }> = [{ id: 'harness-1' }]) {
const dataDir = join(root, `data-${made++}`)
- const live = sessions.map(s => ({ agentId: s.id, swarmSkill: { role: 'dev', key: `harness-codex-${s.id}`, ...(s.plain ? {} : { github: true }) } }) as unknown as RegisteredSession)
+ const session = (s: { id: string; plain?: boolean }) =>
+ ({ agentId: s.id, swarmSkill: { role: 'dev', key: `harness-codex-${s.id}`, ...(s.plain ? {} : { github: true }) } }) as unknown as RegisteredSession
+ const live = sessions.map(session)
+ /** Sessions stopped but still on this machine, which may run again. */
+ const stopped: RegisteredSession[] = []
const backend = vi.fn(async (method: string, path: string, body?: unknown) => routes(method, path, body))
- const core = fakeCore({ dataDir, account: { backend }, agents: { live: vi.fn(() => live), byAgent: vi.fn((id: string) => live.find(s => s.agentId === id)) } })
+ const core = fakeCore({ dataDir, account: { backend }, agents: { live: vi.fn(() => live), all: vi.fn(() => [...live, ...stopped]),
+ byAgent: vi.fn((id: string) => live.find(s => s.agentId === id)) } })
const hosts = (id = 'harness-1') => readFileSync(join(swarmGitHubSessionDir(dataDir, `harness-codex-${id}`)!, 'gh', 'hosts.yml'), 'utf8')
const trailers = (id = 'harness-1') => readFileSync(join(swarmGitHubSessionDir(dataDir, `harness-codex-${id}`)!, 'trailers'), 'utf8')
- return { core, backend, hosts, trailers }
+ return { core, backend, hosts, trailers, live, stopped, session, dataDir }
}
describe('a local agent\'s GitHub token', () => {
@@ -127,6 +139,94 @@ describe('keeping gh\'s token fresh', () => {
expect(asked()).toBe(3)
})
+ // Local Team account run, 2026-10-28: a task cancelled as its agent stopped left the last token in that session's gh login,
+ // since the refresher looks only at running sessions.
+ it('empties the gh login of a session that stopped, also one left from before the daemon started', async () => {
+ const { core, hosts, live, stopped, dataDir } = setup(method => method === 'GET'
+ ? ok(hostForm([row('tab-1', 'agent-1')], { assignments: [{ tabId: 'tab-1', assignmentId: 'attempt-1', harnessId: 'harness-1' }] }))
+ : issued('ghs_fixtureToken0000007'))
+ const refresher = new GitHubTokenRefresher(core, sourcesOf(core))
+ await refresher.tick()
+ expect(hosts()).toContain('ghs_fixtureToken0000007')
+ stopped.push(...live.splice(0))
+ await refresher.tick()
+ expect(hosts()).toBe('{}\n')
+ // A session that stopped while no daemon ran, and is gone from this machine since: its folder is removed.
+ const old = swarmGitHubSessionDir(dataDir, 'harness-codex-old')!
+ writeSessionGitHub(old, 'ghs_fixtureToken0000008')
+ age(old, 16 * 60_000)
+ await new GitHubTokenRefresher(core, sourcesOf(core)).tick()
+ expect(existsSync(old)).toBe(false)
+ })
+
+ // Security review of #1978, Minor: a pass read every stopped session's folder, so passes grew with every session ever run.
+ it('keeps the folder of a stopped session that may run again, emptied, and removes one whose session is gone', async () => {
+ const { core, live, stopped, session, dataDir } = setup(() => ok(hostForm([])))
+ const kept = swarmGitHubSessionDir(dataDir, 'harness-codex-harness-1')!, gone = swarmGitHubSessionDir(dataDir, 'harness-codex-old')!
+ writeSessionGitHub(kept, 'ghs_fixtureToken0000003', ['Harness-Agent: Atlas'])
+ writeSessionGitHub(gone, 'ghs_fixtureToken0000002')
+ age(gone, 16 * 60_000)
+ live.length = 0
+ stopped.push(session({ id: 'harness-1' }))
+ await new GitHubTokenRefresher(core, sourcesOf(core)).tick()
+ expect(readFileSync(join(kept, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')
+ expect(readFileSync(join(kept, 'trailers'), 'utf8')).toBe('Harness-Agent: Atlas\n')
+ expect(existsSync(gone)).toBe(false)
+ })
+
+ // Review of #1998: a start writes its session's folder before the session is registered (core/agents/create.ts), and a
+ // pass in that gap removed it. Only a folder untouched for 15 minutes, longer than any start waits, goes.
+ it('keeps the folder of a session still starting, and of one not read just now, until it is 15 minutes untouched', async () => {
+ const dataDir = mkdtempSync(join(root, 'starting-'))
+ const core = fakeCore({ dataDir, agents: { live: vi.fn(() => []), all: vi.fn(() => []), byAgent: vi.fn(() => undefined) } })
+ swarmGitHubLaunch('harness-codex-starting', { dataDir, command: '/bin/true', port: 1, machineId: 'machine-1' }, 'darwin')
+ const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-starting')!
+ expect(existsSync(dir)).toBe(true)
+ await new GitHubTokenRefresher(core, () => ({}) as never).tick()
+ expect(existsSync(dir), 'folder of a session still starting').toBe(true)
+ // A token in a young folder of no known session is still taken out.
+ writeSessionGitHub(dir, 'ghs_fixtureToken0000001')
+ await new GitHubTokenRefresher(core, () => ({}) as never).tick()
+ expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')
+ age(dir, 14 * 60_000)
+ await new GitHubTokenRefresher(core, () => ({}) as never).tick()
+ expect(existsSync(dir)).toBe(true)
+ age(dir, 16 * 60_000)
+ await new GitHubTokenRefresher(core, () => ({}) as never).tick()
+ expect(existsSync(dir)).toBe(false)
+ })
+
+ // Security review of #1978: a token fetch still in flight as its session stopped wrote the token after the folder was
+ // emptied, and the folder was not looked at again until the daemon restarted.
+ it('empties a stopped session\'s gh login again when a late write puts a token back', async () => {
+ const { core, hosts, live, stopped, dataDir } = setup(() => ok(hostForm([])))
+ stopped.push(...live.splice(0))
+ const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-harness-1')!
+ writeSessionGitHub(dir, 'ghs_fixtureToken0000005')
+ const refresher = new GitHubTokenRefresher(core, sourcesOf(core))
+ await refresher.tick()
+ expect(hosts()).toBe('{}\n')
+ writeSessionGitHub(dir, 'ghs_fixtureToken0000006')
+ await refresher.tick()
+ expect(hosts()).toBe('{}\n')
+ })
+
+ // Security review of #1978: a file with a session's name in the sessions folder failed every look, and no token was renewed.
+ it('skips anything in the sessions folder that is not a session\'s folder, and renews as before', async () => {
+ const { core, hosts, dataDir } = setup(method => method === 'GET'
+ ? ok(hostForm([row('tab-1', 'agent-1')], { assignments: [{ tabId: 'tab-1', assignmentId: 'attempt-1', harnessId: 'harness-1' }] }))
+ : issued('ghs_fixtureToken0000004'))
+ const sessions = dirname(swarmGitHubSessionDir(dataDir, 'harness-codex-stray')!)
+ mkdirSync(sessions, { recursive: true })
+ writeFileSync(join(sessions, 'harness-codex-stray'), 'not a folder')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ await new GitHubTokenRefresher(core, sourcesOf(core)).tick()
+ expect(warn).not.toHaveBeenCalled()
+ } finally { warn.mockRestore() }
+ expect(hosts()).toContain('ghs_fixtureToken0000004')
+ })
+
it('reads nothing from the backend while no session uses the app, and leaves tokens be while it is away', async () => {
const quiet = setup(() => ok(hostForm([])), [{ id: 'harness-1', plain: true }])
await new GitHubTokenRefresher(quiet.core, sourcesOf(quiet.core)).tick()
diff --git a/cli/src/superTabs/github.ts b/cli/src/superTabs/github.ts
index c9913889e..0c5be5497 100644
--- a/cli/src/superTabs/github.ts
+++ b/cli/src/superTabs/github.ts
@@ -6,8 +6,10 @@
* The token goes to git through `harness git-credential` (superTabs/gitCredential.ts), which asks here over the local
* socket, and to gh through the session's own `hosts.yml`. Nothing here logs a token.
*/
+import { readdirSync, readFileSync, rmSync, statSync, type Dirent } from 'node:fs'
+import { join } from 'node:path'
import type { CoreApi } from '../core/api.js'
-import { swarmGitHubSessionDir, writeSessionGitHub } from '../lib/swarmGitHub.js'
+import { swarmGitHubRoot, swarmGitHubSessionDir, writeSessionGitHub } from '../lib/swarmGitHub.js'
import { backend, identifier, object, SuperTabHostError } from './wire.js'
import type { SwarmSources } from './host.js'
@@ -74,6 +76,9 @@ export async function githubToken(core: CoreApi, harnessId: string, sources: Swa
/** How often the daemon looks at its sessions' tasks. A token is renewed once it has this much left or less. */
export const REFRESH_INTERVAL_MS = 60_000
export const RENEW_BELOW_MS = 10 * 60_000
+/** How long a session's folder with no session registered for it stays: longer than any start waits to launch, since a
+ * start writes the folder before its session is registered (core/agents/create.ts; review of #1998). */
+export const UNREGISTERED_FOLDER_MS = 15 * 60_000
/**
* Keeps each local session started to use the app holding a token for its task while the task lasts: renewed before it
@@ -114,12 +119,54 @@ export class GitHubTokenRefresher {
return this.running
}
+ /**
+ * A session that stopped takes its token with it: its folder's gh login is emptied. A task ended as its agent stopped left
+ * the last token there, since only running sessions are looked at (local Team account run, 2026-10-28); so did a session
+ * that stopped while no daemon ran. Looked at on every pass, not once: a token fetch still in flight as its session stopped
+ * writes the token after the folder was emptied (security review of #1978). One small read per stopped session's folder a
+ * minute, while the refresher runs. Anything that is not a session's folder is skipped, and one that cannot be read or
+ * written is logged and passed over, so no folder stops the renewals below. A folder whose session is gone from this
+ * machine is removed, so passes do not grow with every session ever run (security review of #1978); one whose session
+ * stopped but may run again ([known]) keeps its commit identity and trailers for then. Removed only once untouched for
+ * UNREGISTERED_FOLDER_MS: a session still starting has its folder before its record, and a record may not be read just
+ * now (review of #1998).
+ */
+ private emptyStopped(running: ReadonlySet<string>, known: ReadonlySet<string>): void {
+ const sessions = join(swarmGitHubRoot(this.core.dataDir), 'sessions')
+ let entries: Dirent[]
+ try { entries = readdirSync(sessions, { withFileTypes: true }) } catch { return }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue
+ const dir = swarmGitHubSessionDir(this.core.dataDir, entry.name)
+ if (!dir || running.has(dir)) continue
+ try {
+ if (!known.has(dir) && this.now() - this.touched(dir) >= UNREGISTERED_FOLDER_MS) { rmSync(dir, { recursive: true, force: true }); continue }
+ let hosts: string
+ try { hosts = readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8') } catch { continue }
+ if (hosts !== '{}\n') writeSessionGitHub(dir, null)
+ } catch (error) {
+ console.warn(`[super-tab] could not empty a stopped session's gh login · ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
+ }
+
+ /** When anything in a session's folder last changed. */
+ private touched(dir: string): number {
+ let newest = 0
+ for (const path of [dir, join(dir, 'gh'), join(dir, 'gh', 'hosts.yml'), join(dir, 'gh', 'config.yml'), join(dir, 'gitconfig'), join(dir, 'trailers')]) {
+ try { newest = Math.max(newest, statSync(path).mtimeMs) } catch { /* not there */ }
+ }
+ return newest
+ }
+
private async look(): Promise<void> {
const sessions = this.core.agents.live().flatMap(session => {
const dir = githubDir(this.core, session)
return dir ? [{ session, dir }] : []
})
for (const id of this.primed.keys()) if (!sessions.some(s => s.session.agentId === id)) this.primed.delete(id)
+ this.emptyStopped(new Set(sessions.map(s => s.dir)),
+ new Set(this.core.agents.all().flatMap(session => githubDir(this.core, session) ?? [])))
if (!sessions.length) return
const machineId = this.core.daemon.machineId()
if (!identifier(machineId)) return
diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.ts
index 092b41bc7..3ce8cdc43 100644
--- a/cli/src/superTabs/projectFolder.spec.ts
+++ b/cli/src/superTabs/projectFolder.spec.ts
@@ -117,8 +117,9 @@ function hosted(answer: unknown = { github: true, token: TOKEN, repository: 'exa
return answer
})
const fetch = vi.fn(async (_cwd: string, _env: NodeJS.ProcessEnv) => true)
- return { ...f, row, start, backend, fetch,
- ready: (team = false) => prepareSwarmStart(f.core, row, start, { backend, team, prepare: f.prepare, fetch }) }
+ const revoke = vi.fn(async (_token: string) => {})
+ return { ...f, row, start, backend, fetch, revoke,
+ ready: (team = false) => prepareSwarmStart(f.core, row, start, { backend, team, prepare: f.prepare, fetch, revoke }) }
}
describe('preparing another person\'s start with the Harness GitHub App', () => {
@@ -177,6 +178,26 @@ describe('preparing another person\'s start with the Harness GitHub App', () =>
await expect(f.ready()).rejects.toThrow('taken')
})
+ // Local Team account run, 2026-10-28: the read-only token for the clone was never revoked and stayed good for its hour.
+ it('revokes the read-only token once the clone and the fetch are done, and when they fail', async () => {
+ const f = hosted()
+ f.fetch.mockImplementationOnce(async () => { expect(f.revoke).not.toHaveBeenCalled(); return true })
+ await f.ready(true)
+ expect(f.revoke.mock.calls).toEqual([[TOKEN]])
+ const failed = hosted()
+ failed.prepare.mockRejectedValueOnce(new RepositoryAccessError('CLONE_FAILED', 'Could not access this repository.'))
+ await expect(failed.ready(true)).rejects.toThrow('could not clone')
+ expect(failed.revoke.mock.calls).toEqual([[TOKEN]])
+ // A revocation GitHub refuses fails nothing: the token still expires within the hour.
+ const refused = hosted()
+ refused.revoke.mockRejectedValueOnce(new Error('GitHub did not answer'))
+ expect(await refused.ready(true)).toEqual({ requester: '[email protected]' })
+ // The owner's own login prepares the owner's own project: there is no token to revoke.
+ const own = hosted({ github: false })
+ await own.ready()
+ expect(own.revoke).not.toHaveBeenCalled()
+ })
+
it('fetches into a project already on this host, and into a contribution that is not a Swarm folder, with the token', async () => {
const f = hosted()
f.repository.machineId = f.core.daemon.machineId()
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
index 65c8997ea..45768c6a3 100644
--- a/cli/src/superTabs/projectFolder.ts
+++ b/cli/src/superTabs/projectFolder.ts
@@ -2,7 +2,7 @@ import { isAbsolute, join, resolve } from 'node:path'
import type { CoreApi } from '../core/api.js'
import { fetchDefaultBranch } from '../lib/gitProject.js'
import { otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'
-import { swarmGitPrepareEnv } from '../lib/swarmGitHub.js'
+import { revokeGitHubToken, swarmGitPrepareEnv } from '../lib/swarmGitHub.js'
import { identifier, object } from './wire.js'
import { repairSwarmCloneTrust, swarmCloneRoot } from './cloneTrust.js'
@@ -52,13 +52,19 @@ export async function startGitHub(core: CoreApi, row: Json, start: Json, deps: {
* core/agents/launches.ts). Returns whom the work is for, for the start; null when this machine's own login is right for it.
*/
export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,
- deps: { backend: Backend; team: boolean; prepare?: typeof prepareProjectFolder; fetch?: typeof fetchDefaultBranch }): Promise<{ requester: string } | null> {
+ deps: { backend: Backend; team: boolean; prepare?: typeof prepareProjectFolder; fetch?: typeof fetchDefaultBranch; revoke?: (token: string) => Promise<void> }):
+ Promise<{ requester: string } | null> {
const github = await startGitHub(core, row, start, deps)
const gitEnv = github ? swarmGitPrepareEnv(github.token) : undefined
- if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, gitEnv)
- const request = object(start.request)
- if (gitEnv && request.worktree === true && typeof request.cwd === 'string' && isAbsolute(request.cwd)) {
- await (deps.fetch ?? fetchDefaultBranch)(resolve(request.cwd), gitEnv)
+ try {
+ if (object(row.machine).scope === 'swarm') await prepareSwarmProject(core, row, start, deps.prepare, gitEnv)
+ const request = object(start.request)
+ if (gitEnv && request.worktree === true && typeof request.cwd === 'string' && isAbsolute(request.cwd)) {
+ await (deps.fetch ?? fetchDefaultBranch)(resolve(request.cwd), gitEnv)
+ }
+ } finally {
+ // The read-only token is done with: the agent gets a token of its own for its task (superTabs/github.ts).
+ if (github) await (deps.revoke ?? revokeGitHubToken)(github.token).catch(error => console.warn(`[super-tabs] could not revoke the clone token: ${(error as Error).message}`))
}
return github ? { requester: github.requester } : null
}
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index b66e9f2d2..87bf472fd 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -961,15 +961,23 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
(observedAt == null || sample.$2.isAfter(observedAt)));
final readingAt = direct ? sample?.$2 : observedAt;
final age = readingAt == null ? null : now.difference(readingAt);
- final status = superTabMachineStatus(
- age: age,
- // The Swarm cannot be read: a machine's silence is not known to be its own, so it is not offline.
- unreachable: !direct && c.backendUnreachable,
- refreshing: direct
- ? _awaiting.contains(readId)
- : _swarmReadsAtReturn != null && c.stateReads <= _swarmReadsAtReturn!,
- connected: direct ? connected : null,
- );
+ // A computer only running someone's agents, never added to the Swarm and not one this Desktop reads (a teammate's
+ // Lead computer): nothing reports it but its agents, so it is up while one of them is (group #646, item 5).
+ final agentsOnly = shared == null && team == null && state == null;
+ final status = agentsOnly
+ ? (agents.any((a) => a.downSince == null)
+ ? SuperTabMachineStatus.live
+ : SuperTabMachineStatus.offline)
+ : superTabMachineStatus(
+ age: age,
+ // The Swarm cannot be read: a machine's silence is not known to be its own, so it is not offline.
+ unreachable: !direct && c.backendUnreachable,
+ refreshing: direct
+ ? _awaiting.contains(readId)
+ : _swarmReadsAtReturn != null &&
+ c.stateReads <= _swarmReadsAtReturn!,
+ connected: direct ? connected : null,
+ );
// Cached samples remain available to the refresh logic, but stale numbers are not presented as current.
final dim =
status == SuperTabMachineStatus.offline ||
@@ -999,7 +1007,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
(given == null || given.isEmpty ? null : given) ??
shared?['name'] as String? ??
app?.stateOf(id)?.machine.displayName ??
- 'Unavailable machine';
+ // The Swarm knows no name for it, and sharing its own would be new data: it is named by its owner.
+ (agentsOnly && person != null
+ ? "${superTabPersonName(person.email)}'s computer"
+ : 'Unavailable machine');
final configured = (reading?['engines'] as List?)
?.whereType<String>()
.toList();
diff --git a/desktop/lib/super_tabs/project_github.dart b/desktop/lib/super_tabs/project_github.dart
index d1f41afd8..a9301c140 100644
--- a/desktop/lib/super_tabs/project_github.dart
+++ b/desktop/lib/super_tabs/project_github.dart
@@ -26,7 +26,11 @@ class SuperTabProjectGitHub {
installUrl = row['installUrl'] is String
? row['installUrl'] as String
: null,
- canApprove = row['canApprove'] == true;
+ canApprove = row['canApprove'] == true,
+ approvedFor = [
+ for (final name in row['approvedFor'] as List? ?? const [])
+ if (name is String) name,
+ ];
/// `covered`, `not-installed`, `not-approved` (installed, but nobody who can push to it approved it for this project:
/// backend github/approvals.ts), `not-github`, `no-repository`, `unknown` (GitHub did not answer), `unread` (this
@@ -38,6 +42,10 @@ class SuperTabProjectGitHub {
/// This server has the app's GitHub sign-in to approve a repository with.
final bool canApprove;
+ /// The reader's other projects the repository is approved for, when it is not approved for this one (backend
+ /// github/projectAccess.ts): approving is per project, so a second one asks again.
+ final List<String> approvedFor;
+
/// What stops teammates' agents here, in the sidebar's one line; null when nothing does or it cannot be said.
String? get problem => switch (state) {
'not-installed' || 'not-approved' => "Teammates can't push here yet",
@@ -46,6 +54,11 @@ class SuperTabProjectGitHub {
};
}
+/// Names in a sentence: "Notes", "Notes and Docs", "Notes, Docs and Site".
+String _names(List<String> names) => names.length < 2
+ ? names.join()
+ : '${names.sublist(0, names.length - 1).join(', ')} and ${names.last}';
+
/// The project's GitHub access in full, with what to do about it: Project details, and the dialog the sidebar line
/// opens. Read when shown; [SuperTabController.readGitHubAccess] keeps it at most 5 minutes.
class ProjectGitHubAccess extends StatefulWidget {
@@ -145,7 +158,11 @@ class _ProjectGitHubAccessState extends State<ProjectGitHubAccess>
"Teammates' agents can't push to $repository yet. Install Harness on GitHub there: "
"an owner of ${repository.split('/').first}, or the repository's owner, can.",
'not-approved' =>
- access.canApprove
+ access.canApprove && access.approvedFor.isNotEmpty
+ // Approving is per project: one approved for the reader's other projects says so (group #646, item 8).
+ ? "Teammates' agents can't use $repository in this project yet. It's approved for "
+ '${_names(access.approvedFor)}. Approve it here too?'
+ : access.canApprove
? "Teammates' agents can't use $repository in this project yet. Someone who can push to it "
'approves it, signing in to GitHub.'
: "Teammates' agents can't use $repository in this project yet. This Harness server can't approve "
@@ -244,11 +261,6 @@ class _ProjectGitHubAccessState extends State<ProjectGitHubAccess>
onPressed: _busy ? null : () => _approve('project'),
child: const Text('Approve for this project'),
),
- TextButton(
- key: const Key('super-project-github-approve-swarm'),
- onPressed: _busy ? null : () => _approve('swarm'),
- child: const Text('Approve for every project here'),
- ),
],
TextButton(
key: const Key('super-project-github-check'),
diff --git a/desktop/test/super_tab_project_github_test.dart b/desktop/test/super_tab_project_github_test.dart
index 207b4983e..946959b46 100644
--- a/desktop/test/super_tab_project_github_test.dart
+++ b/desktop/test/super_tab_project_github_test.dart
@@ -16,6 +16,22 @@ import 'package:harness/widgets/desktop_chrome.dart';
import 'support/super_tab_fixture.dart';
void main() {
+ // Local Team account run, 2026-10-28 (group #646, item 8): the server names the reader's other projects the
+ // repository is approved for; nothing else is read from it.
+ test('reads the other projects a repository is approved for', () {
+ final access = SuperTabProjectGitHub.fromJson({
+ 'state': 'not-approved',
+ 'repository': 'tuan-dev/notes-app',
+ 'canApprove': true,
+ 'approvedFor': ['Notes', 3, 'Docs'],
+ });
+ expect(access.approvedFor, ['Notes', 'Docs']);
+ expect(
+ SuperTabProjectGitHub.fromJson({'state': 'covered'}).approvedFor,
+ isEmpty,
+ );
+ });
+
late ConversationServer server;
late List<String> asked;
late Map<String, dynamic> answer;
@@ -169,7 +185,9 @@ void main() {
expect(asked.last, endsWith('/github?refresh=1'));
// A check mark, the app's own, not a ✓ typed into the sentence (Ken, 2026-10-28).
expect(
- find.text("Teammates' agents can push and open pull requests on acme/app."),
+ find.text(
+ "Teammates' agents can push and open pull requests on acme/app.",
+ ),
findsOneWidget,
);
expect(find.textContaining('✓'), findsNothing);
@@ -233,11 +251,14 @@ void main() {
find.textContaining("can't use acme/app in this project yet"),
findsOneWidget,
);
- await tester.tap(
+ // Approved one project at a time: nothing widens it to every project in one click (Scholes, 2026-10-28).
+ expect(
find.byKey(const Key('super-project-github-approve-swarm')),
+ findsNothing,
);
+ await tester.tap(find.byKey(const Key('super-project-github-approve')));
await tester.pumpAndSettle();
- expect(asked.last, endsWith('/github/approve swarm'));
+ expect(asked.last, endsWith('/github/approve project'));
expect(launched.last, contains('/login/oauth/authorize'));
refuseApprove = true;
await tester.tap(find.byKey(const Key('super-project-github-approve')));
@@ -250,6 +271,48 @@ void main() {
},
);
+ // Local Team account run, 2026-10-28 (group #646, item 8): a second project on an approved repository asked again with
+ // no hint. It names the reader's other projects it is approved for, as the server says.
+ testWidgets(
+ 'names the other projects the repository is approved for, and asks to approve it here too',
+ (tester) async {
+ Future<void> reads(List<String> approvedFor, String line) async {
+ answer = {
+ 'state': 'not-approved',
+ 'repository': 'acme/app',
+ 'canApprove': true,
+ 'approvedFor': approvedFor,
+ };
+ final c = await mount(
+ tester,
+ (c, p) => ProjectGitHubAccess(controller: c, projectId: p.id),
+ );
+ expect(
+ find.text(
+ "Teammates' agents can't use acme/app in this project yet. $line",
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const Key('super-project-github-approve')),
+ findsOneWidget,
+ );
+ c.dispose();
+ }
+
+ await reads(['Notes'], "It's approved for Notes. Approve it here too?");
+ await reads([
+ 'Notes',
+ 'Docs',
+ ], "It's approved for Notes and Docs. Approve it here too?");
+ await reads([
+ 'Notes',
+ 'Docs',
+ 'Site',
+ ], "It's approved for Notes, Docs and Site. Approve it here too?");
+ },
+ );
+
testWidgets('says so when the server cannot approve, without the buttons', (
tester,
) async {
@@ -272,37 +335,47 @@ void main() {
// 2026-10-28, a new Swarm: Project details showed no GitHub access at all while it was read, and after an approval
// the sidebar kept saying teammates could not push for 5 minutes.
- testWidgets('says it is checking while it reads, and that it could not when it fails, asking again soon', (
- tester,
- ) async {
- hold = Completer<void>();
- final c = controllerFor();
- await c.refresh();
- final project = c.snapshot!.projects.first;
- await tester.pumpWidget(
- MaterialApp(
- home: Scaffold(
- body: ProjectGitHubAccess(controller: c, projectId: project.id),
+ testWidgets(
+ 'says it is checking while it reads, and that it could not when it fails, asking again soon',
+ (tester) async {
+ hold = Completer<void>();
+ final c = controllerFor();
+ await c.refresh();
+ final project = c.snapshot!.projects.first;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ProjectGitHubAccess(controller: c, projectId: project.id),
+ ),
),
- ),
- );
- await tester.pump();
- expect(find.text('Checking…'), findsOneWidget);
- failure = const SuperTabFailure('NETWORK', 'offline');
- hold!.complete();
- await tester.pumpAndSettle();
- expect(find.text("Couldn't check GitHub access just now."), findsOneWidget);
- expect(find.byKey(const Key('super-project-github-check')), findsOneWidget);
- // Asked again after 30 seconds, not 5 minutes.
- final before = asked.length;
- await c.readGitHubAccess(project.id);
- expect(asked, hasLength(before));
- failure = null;
- await tester.tap(find.byKey(const Key('super-project-github-check')));
- await tester.pumpAndSettle();
- expect(find.textContaining('Install Harness on GitHub there'), findsOneWidget);
- c.dispose();
- });
+ );
+ await tester.pump();
+ expect(find.text('Checking…'), findsOneWidget);
+ failure = const SuperTabFailure('NETWORK', 'offline');
+ hold!.complete();
+ await tester.pumpAndSettle();
+ expect(
+ find.text("Couldn't check GitHub access just now."),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const Key('super-project-github-check')),
+ findsOneWidget,
+ );
+ // Asked again after 30 seconds, not 5 minutes.
+ final before = asked.length;
+ await c.readGitHubAccess(project.id);
+ expect(asked, hasLength(before));
+ failure = null;
+ await tester.tap(find.byKey(const Key('super-project-github-check')));
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining('Install Harness on GitHub there'),
+ findsOneWidget,
+ );
+ c.dispose();
+ },
+ );
testWidgets('shows nothing on a server without the route', (tester) async {
failure = const SuperTabFailure('NOT_FOUND', 'Not found', statusCode: 404);
@@ -315,34 +388,48 @@ void main() {
c.dispose();
});
- testWidgets('says to finish in the browser, and the sidebar asks again when the person is back', (
- tester,
- ) async {
- answer = {'state': 'not-approved', 'repository': 'acme/app', 'canApprove': true};
- final c = await mount(
- tester,
- (c, p) => Column(
- children: [
- ProjectGitHubLine(controller: c, project: p),
- ProjectGitHubAccess(controller: c, projectId: p.id),
- ],
- ),
- );
- expect(find.byKey(const Key('super-project-github-waiting')), findsNothing);
- await tester.tap(find.byKey(const Key('super-project-github-approve')));
- await tester.pumpAndSettle();
- expect(find.byKey(const Key('super-project-github-waiting')), findsOneWidget);
- // Approved in the browser; back in the app, both ask again at once.
- answer = {'state': 'covered', 'repository': 'acme/app'};
- tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
- tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
- await tester.pumpAndSettle();
- expect(asked.last, endsWith('/github?refresh=1'));
- expect(find.text("Teammates can't push here yet"), findsNothing);
- expect(find.textContaining("Teammates' agents can push"), findsOneWidget);
- expect(find.byKey(const Key('super-project-github-waiting')), findsNothing);
- c.dispose();
- });
+ testWidgets(
+ 'says to finish in the browser, and the sidebar asks again when the person is back',
+ (tester) async {
+ answer = {
+ 'state': 'not-approved',
+ 'repository': 'acme/app',
+ 'canApprove': true,
+ };
+ final c = await mount(
+ tester,
+ (c, p) => Column(
+ children: [
+ ProjectGitHubLine(controller: c, project: p),
+ ProjectGitHubAccess(controller: c, projectId: p.id),
+ ],
+ ),
+ );
+ expect(
+ find.byKey(const Key('super-project-github-waiting')),
+ findsNothing,
+ );
+ await tester.tap(find.byKey(const Key('super-project-github-approve')));
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const Key('super-project-github-waiting')),
+ findsOneWidget,
+ );
+ // Approved in the browser; back in the app, both ask again at once.
+ answer = {'state': 'covered', 'repository': 'acme/app'};
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
+ await tester.pumpAndSettle();
+ expect(asked.last, endsWith('/github?refresh=1'));
+ expect(find.text("Teammates can't push here yet"), findsNothing);
+ expect(find.textContaining("Teammates' agents can push"), findsOneWidget);
+ expect(
+ find.byKey(const Key('super-project-github-waiting')),
+ findsNothing,
+ );
+ c.dispose();
+ },
+ );
testWidgets(
'Project details is titled by the project, with its repository, Product Manager and GitHub access in one column',
@@ -363,7 +450,10 @@ void main() {
final dialog = find.byType(SuperTabDetailDialog);
expect(dialog, findsOneWidget);
expect(
- find.descendant(of: find.byType(DesktopDialogHeader), matching: find.text(project.name)),
+ find.descendant(
+ of: find.byType(DesktopDialogHeader),
+ matching: find.text(project.name),
+ ),
findsOneWidget,
);
// An empty description is quiet, not an instruction.
@@ -383,7 +473,9 @@ void main() {
},
);
- testWidgets('Project details shows a written description as it is', (tester) async {
+ testWidgets('Project details shows a written description as it is', (
+ tester,
+ ) async {
answer = {'state': 'covered', 'repository': 'acme/app'};
final c = await mount(
tester,
diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dart
index 385ccd330..036964012 100644
--- a/desktop/test/super_tab_team_machine_test.dart
+++ b/desktop/test/super_tab_team_machine_test.dart
@@ -337,6 +337,32 @@ void main() {
},
);
+ // Local Team account run, 2026-10-28 (group #646, item 5): a teammate's Lead computer, never added to the Swarm, read
+ // "Unavailable machine" with an empty dot. Named by its owner, as the Swarm knows no name for it.
+ testWidgets(
+ 'another person\'s computer that only runs their agents is named by them, and live while an agent there is up',
+ (tester) async {
+ final server = _swarm();
+ server.state['machines'] = <Map<String, dynamic>>[];
+ server.state['agents'] = [_agent('a1', 'peer-air')];
+ var c = await _mount(tester, server);
+ expect(find.text("peer's computer"), findsOneWidget);
+ expect(find.text('Unavailable machine'), findsNothing);
+ expect(_state('peer-air', 'live'), findsOneWidget);
+ await _unmount(tester, c);
+ server.state['agents'] = [
+ {
+ ..._agent('a1', 'peer-air'),
+ 'downSince': DateTime.now().toUtc().toIso8601String(),
+ },
+ ];
+ c = await _mount(tester, server);
+ expect(find.text("peer's computer"), findsOneWidget);
+ expect(_state('peer-air', 'offline'), findsOneWidget);
+ await _unmount(tester, c);
+ },
+ );
+
testWidgets('the line stays away when it would say nothing new', (
tester,
) async {
diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.md
index 5800e4310..6ccceef5a 100644
--- a/docs/swarm-github-app.md
+++ b/docs/swarm-github-app.md
@@ -157,6 +157,8 @@ project it does this with the app too, never with its owner's git login:
config are not read, `[email protected]:` addresses go over HTTPS, and nothing prompts.
The token is in the git process's environment only.
3. The agent is created with `swarmGitHub`, and the daemon does not fetch again.
+4. The read-only token is revoked as soon as the clone and the fetch are done, or have failed. The agent gets a token of
+ its own for its task.
If the token cannot be had (the app is not installed on the repository, the project has
no GitHub address, or a team account's server has no app), the start fails with that
@@ -277,9 +279,14 @@ The endpoint refuses with these codes:
Each token is cached per agent and task, sealed with a key derived from the app's
private key, in the backend's shared Redis. The backend serves the cached token until
-ten minutes before it expires. The token is revoked (`DELETE /installation/token`)
-and dropped when the task is done, cancelled or stopped, when the agent is removed,
-or when the agent starts a new task. If a revocation fails, Harness logs it without
+ten minutes before it expires. Then it mints a new one and leaves the old one to its
+last ten minutes, so a push that took the old token before the renewal is not broken.
+That token is for the one repository and the task's own session. When the task is
+done, cancelled or stopped, goes to another agent or attempt, or its agent is removed,
+every token minted for the task is revoked (`DELETE /installation/token`) and dropped,
+replaced ones included, whichever backend instance minted them. A request only ever
+ends its own task: one that waited across its task's end leaves the agent's next task
+alone. If a revocation fails, Harness logs it without
the token and the task's change goes ahead. The token then expires within the hour.
The server never logs a token.