The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep Super Tab pull request links beyond loaded messages (#1622)
0xken15b00367e4c494
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 03e754061..5ec4ff997 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -72,6 +72,80 @@ afterAll(async () => {await replica?.stop()})+describe('durable group pull request links', () => {+ const pr = (number: number) => `https://github.com/example/project/pull/${number}`+ const links = async (tab: string, groupId = 'lead') => {+ const group = (await store.read(owner, tab)).state.conversations.find(c => c.id === groupId)!+ return (group as unknown as { pullRequestUrls?: string[] }).pullRequestUrls+ }++ it('keeps one link beyond the latest 100 messages and reconstructs an older group on read', async () => {+ const { tab } = await fixture()+ await run(tab, message(`Review ${pr(41)}`))+ await run(tab, message(`Same PR again: ${pr(41)}`))+ expect(await links(tab)).toEqual([pr(41)])+ await db.superTabMessage.createMany({ data: Array.from({ length: 101 }, (_, i) => ({+ id: randomUUID(), tabId: tab, conversationId: 'lead', sequence: 1000 + i,+ author: { kind: 'person', id: owner.sub, name: owner.email }, text: `Later note ${i}`,+ replyTo: null, recipientIds: [],+ })) })+ expect((await store.messages(owner, tab, 'lead', {})).messages).toHaveLength(100)+ expect((await store.messages(owner, tab, 'lead', {})).messages.some(row => row.text.includes(pr(41)))).toBe(false)+ expect(await links(tab)).toEqual([pr(41)])++ const stored = await db.superTab.findUniqueOrThrow({ where: { id: tab } })+ const state = stored.state as { conversations: Array<{ id: string; pullRequestUrls?: string[] }> }+ delete state.conversations.find(group => group.id === 'lead')!.pullRequestUrls+ await db.superTab.update({ where: { id: tab }, data: { state } })+ let historyScans = 0+ const observed = db.$extends({ query: { superTabMessage: { async findMany({ args, query }) {+ historyScans+++ return query(args)+ } } } })+ const observedStore = new SuperTabStore(observed as unknown as PrismaClient)+ expect((await observedStore.read(owner, tab)).state.conversations[0]!.pullRequestUrls).toEqual([pr(41)])+ expect(historyScans).toBe(1)+ const backfilled = (await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state as typeof state+ expect(backfilled.conversations.find(group => group.id === 'lead')!.pullRequestUrls).toEqual([pr(41)])+ expect((await observedStore.read(owner, tab)).state.conversations[0]!.pullRequestUrls).toEqual([pr(41)])+ expect(historyScans).toBe(1)+ await run(tab, message('One more note after the older link was found.'))+ const saved = (await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state as typeof state+ expect(saved.conversations.find(group => group.id === 'lead')!.pullRequestUrls).toEqual([pr(41)])+ })++ it('lists links from check evidence and a work result even when no message has those links', async () => {+ const { tab, lead } = await fixture()+ await run(tab, { type: 'work.define', conversationId: 'lead', brief: 'Record work',+ checks: [{ description: 'Reviewed', independent: false }] })+ const assignmentId = String((await run(tab, { type: 'work.assign', conversationId: 'lead', agentId: lead })).result.assignmentId)+ const checkId = (await store.read(owner, tab)).state.conversations[0]!.checks[0]!.id+ await run(tab, { type: 'work.check', conversationId: 'lead', assignmentId, checkId, passed: true,+ evidence: `Reviewed ${pr(42)} and ${pr(42)}` }, host, lead)+ expect((await store.messages(owner, tab, 'lead', {})).messages.some(row => row.text.includes(pr(42)))).toBe(false)+ await run(tab, { type: 'work.status', conversationId: 'lead', assignmentId, status: 'working', result: `Built ${pr(43)}` }, host, lead)+ expect(await links(tab)).toEqual([pr(42), pr(43)])++ await db.superTabMessage.deleteMany({ where: { tabId: tab, conversationId: 'lead', text: { contains: pr(43) } } })+ const stored = await db.superTab.findUniqueOrThrow({ where: { id: tab } })+ const state = stored.state as { conversations: Array<{ id: string; pullRequestUrls?: string[] }> }+ delete state.conversations.find(group => group.id === 'lead')!.pullRequestUrls+ await db.superTab.update({ where: { id: tab }, data: { state } })+ expect((await store.messages(owner, tab, 'lead', {})).messages.some(row => /github\.com/.test(row.text))).toBe(false)+ expect(await links(tab)).toEqual([pr(42), pr(43)])++ await run(tab, { type: 'work.status', conversationId: 'lead', assignmentId, status: 'done', result: `Built ${pr(43)}` }, host, lead)+ await run(tab, { type: 'work.define', conversationId: 'lead', brief: 'Next work',+ checks: [{ description: 'Next check', independent: false }] })+ await db.superTabMessage.deleteMany({ where: { tabId: tab, conversationId: 'lead', text: { contains: pr(43) } } })+ const old = await db.superTab.findUniqueOrThrow({ where: { id: tab } })+ const oldState = old.state as typeof state+ delete oldState.conversations.find(group => group.id === 'lead')!.pullRequestUrls+ await db.superTab.update({ where: { id: tab }, data: { state: oldState } })+ expect(await links(tab)).toEqual([pr(42), pr(43)])+ })+})+describe('native recording restart recovery', () => {async function recoveryFixture(status: 'working' | 'review' = 'working') {const { tab, lead } = await fixture()@@ -106,6 +180,37 @@ describe('native recording restart recovery', () => {return { tab, lead, group, worker, assignmentId, contextId, checkpoint, checkpointRow, gap, interruption, state, gapDeliveries, append }}+ it('keeps a PR link from a native message after that message leaves the latest page', async () => {+ const f = await recoveryFixture()+ const url = 'https://github.com/example/project/pull/44'+ await f.append({ turnId: 'saved_turn', kind: 'answer', previousEventId: f.checkpoint.eventId,+ text: `Opened ${url}`, truncated: false, interrupted: false })+ const group = () => store.read(owner, f.tab).then(row => row.state.conversations.find(c => c.id === f.group)!)+ expect((await group()).pullRequestUrls).toEqual([url])+ await db.superTabMessage.createMany({ data: Array.from({ length: 101 }, (_, i) => ({+ id: randomUUID(), tabId: f.tab, conversationId: f.group, sequence: 1000 + i,+ author: { kind: 'person', id: owner.sub, name: owner.email }, text: `Later note ${i}`,+ replyTo: null, recipientIds: [],+ })) })+ expect((await store.messages(owner, f.tab, f.group, {})).messages.some(row => row.text.includes(url))).toBe(false)+ expect((await group()).pullRequestUrls).toEqual([url])+ })++ it('keeps older links when a native message arrives before a legacy group is backfilled', async () => {+ const f = await recoveryFixture()+ const oldUrl = 'https://github.com/example/project/pull/45'+ const newUrl = 'https://github.com/example/project/pull/46'+ await run(f.tab, { type: 'message.send', conversationId: f.group, text: oldUrl, replyTo: null, recipientIds: [] })+ const stored = await db.superTab.findUniqueOrThrow({ where: { id: f.tab } })+ const state = stored.state as { conversations: Array<{ id: string; pullRequestUrls?: string[] }> }+ delete state.conversations.find(group => group.id === f.group)!.pullRequestUrls+ await db.superTab.update({ where: { id: f.tab }, data: { state } })+ await f.append({ turnId: 'saved_turn', kind: 'answer', previousEventId: f.checkpoint.eventId,+ text: newUrl, truncated: false, interrupted: false })+ const group = (await store.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!+ expect(group.pullRequestUrls).toEqual([oldUrl, newUrl])+ })+it.each(['recording_restarted', 'history_lost', 'agent_stopped'] as const)('wakes only the Lead and blocks working work for %s with a checkpoint time and no visible ids', async reason => {const f = await recoveryFixture(), event = f.interruption(reason)const result = await store.native.append(host, f.tab, f.contextId, event) as { eventId: string }diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex dc388297e..7b274a247 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -130,6 +130,19 @@ export interface Conversation {checks: Check[]assignment: Assignment | nulllastMessageSequence: number+ /** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */+ pullRequestUrls?: string[]+}++export function appendPullRequestUrls(group: Conversation, texts: Iterable<string | null | undefined>): void {+ const urls = new Set(group.pullRequestUrls ?? [])+ for (const text of texts) {+ if (!text) continue+ for (const match of text.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/([1-9][0-9]*)\b/g)) {+ if (Number(match[1]) <= Number.MAX_SAFE_INTEGER) urls.add(match[0])+ }+ }+ group.pullRequestUrls = [...urls]}export interface Invitation {id: stringdiff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.tsindex 6d4bf0b45..bd53fa073 100644--- a/backend/src/superTabs/native.ts+++ b/backend/src/superTabs/native.ts@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'import type { Prisma, SuperTab, SuperTabNativeContext } from '@prisma/client'import { z } from 'zod'import type { AuthUser } from '../lib/ssoAuth.js'-import { activeWork, agent, author, conversation, fail, isLeads, stableId, SuperTabError,+import { activeWork, agent, appendPullRequestUrls, author, conversation, fail, isLeads, stableId, SuperTabError,type Actor, type Agent, type Author, type Conversation, type SuperTabState } from './model.js'import { canReadProject, groupProject, readConversation } from './projects.js'import { noteProjectReports } from './projectUpdates.js'@@ -188,6 +188,8 @@ export class SuperTabNativeStore {const observedBy = author(state, { kind: 'agent', agentId: target.id, machineOwnerId: user.sub }, true)const text = recovery?.source.required ? recovery.text : event.kind === 'gap'? 'Some terminal activity could not be recorded. Check the native session for the full conversation.' : event.text+ // Leave a legacy group's list absent so the next read can recover its older links too.+ if (group.pullRequestUrls !== undefined) appendPullRequestUrls(group, [text])// Inform the coordinating lead without replaying this input into the agent// that already received it. Its resulting programmatic turn is not native input.const recipients = (event.kind !== 'gap' || recovery?.source.required) && group.leadId && group.leadId !== target.id ? [group.leadId] : []diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 18b1e759c..c2615e331 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -15,7 +15,7 @@ import { bindSession, makeProjectPrivate } from './sessionScope.js'import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'import { revokeNativeContexts, SuperTabNativeStore } from './native.js'import {- activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,+ activeWork, actorKey, agent, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,SuperTabError, isLeads, syncLeads, type Actor, type Agent, type Assignment, type Author, type MessageDraft, type SuperTabState,} from './model.js'import { holdNoticeText, type HoldReason } from './holdNotice.js'@@ -37,6 +37,29 @@ const stateOf = (row: SuperTab): SuperTabState => {syncLeads(state)return state}++/** Old groups have no link list. Reconstruct theirs from complete stored history once; current groups accumulate+ * links on write. */+async function restorePullRequestUrls(tx: Transaction, tabId: string, state: SuperTabState): Promise<void> {+ const missing = state.conversations.filter(group => group.pullRequestUrls === undefined)+ if (!missing.length) return+ const conversationIds = missing.map(group => group.id)+ const [messages, attempts] = await Promise.all([+ tx.superTabMessage.findMany({ where: { tabId, conversationId: { in: conversationIds }, text: { contains: 'https://github.com/' } },+ select: { conversationId: true, text: true }, orderBy: { sequence: 'asc' } }),+ tx.superTabAttempt.findMany({ where: { tabId, conversationId: { in: conversationIds } },+ select: { conversationId: true, snapshot: true }, orderBy: { createdAt: 'asc' } }),+ ])+ for (const group of missing) {+ const prior = attempts.filter(attempt => attempt.conversationId === group.id)+ .map(attempt => attempt.snapshot as unknown as { checks?: Array<{ evidence?: string | null }>; assignment?: { result?: string | null } })+ appendPullRequestUrls(group, [+ ...messages.filter(message => message.conversationId === group.id).map(message => message.text),+ ...prior.flatMap(attempt => [...(attempt.checks ?? []).map(check => check.evidence), attempt.assignment?.result]),+ ...group.checks.map(check => check.evidence), group.assignment?.result,+ ])+ }+}const indexes = (state: SuperTabState) => ({memberIds: state.people.map(p => p.id), invitedEmails: state.invitations.map(i => i.email),machineIds: [...new Set([...state.agents.map(a => a.machineId), ...(state.machines ?? []).map(m => m.machineId),@@ -288,6 +311,12 @@ export class SuperTabStore {const row = await this.row(tx, user, tabId)const state = stateOf(row)const actor = await this.actor(tx, user, state, asAgentId)+ if (state.conversations.some(group => group.pullRequestUrls === undefined)) {+ await restorePullRequestUrls(tx, tabId, state)+ // Keep the revision: this adds optional metadata and does not change work or messages. A concurrent+ // command with a newer revision owns the state; its write also reconstructs any missing link lists.+ await tx.superTab.updateMany({ where: { id: tabId, revision: row.revision }, data: { state: json(state) } })+ }const visible = visibleState(state, actor, this.now())return { revision: row.revision, state: { ...visible, machines: visible.machines?.map(pool => ({...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, state.machines!.find(m => m.machineId === pool.machineId)!)),@@ -442,7 +471,14 @@ export class SuperTabStore {// A dispatch reads its start's decision only to see whether a person chose this start by hand (rules.ts).const dispatched = command.type === 'agent.startDispatch' ? original.starts?.find(s => s.id === command.startId)?.routeDecisionId : undefinedif (dispatched) context.routeDecision = await readDecision(tx, tabId, dispatched) ?? undefined+ await restorePullRequestUrls(tx, tabId, original)const effects = applyCommand(original, actor, command, context)+ for (const group of effects.state.conversations) {+ appendPullRequestUrls(group, [+ ...effects.messages.filter(message => message.conversationId === group.id).map(message => message.text),+ ...group.checks.map(check => check.evidence), group.assignment?.result,+ ])+ }if (command.type === 'agent.rebind') {const target = agent(effects.state, command.agentId)// A terminal can already belong to a different project or Swarm on this host. The purediff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex d6930ed4a..6864aa452 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -83,6 +83,10 @@ class SuperTabConversation {row['checks'] ?? const [],(check) => Map<String, dynamic>.unmodifiable(check),),+ pullRequestUrls = List.unmodifiable(+ (row['pullRequestUrls'] as List?)?.whereType<String>() ??+ const <String>[],+ ),brief = _text(row, 'brief'),task = row['task'] is Map? SuperTabTask.fromJson(superTabMap(row['task']))@@ -99,6 +103,9 @@ class SuperTabConversation {final List<String> agentIds;final bool archived;final List<Map<String, dynamic>> checks;++ /// Persisted links may be absent on older backends; loaded messages still supply links.+ final List<String> pullRequestUrls;final int lastMessageSequence;final Map<String, dynamic>? assignment;}diff --git a/desktop/lib/super_tabs/pull_requests.dart b/desktop/lib/super_tabs/pull_requests.dartindex 5385ee29c..e2870d23b 100644--- a/desktop/lib/super_tabs/pull_requests.dart+++ b/desktop/lib/super_tabs/pull_requests.dart@@ -104,6 +104,11 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {}for (final group in _groups) {+ for (final stored in group.pullRequestUrls) {+ for (final link in superTabPullRequestLinks(stored)) {+ include(link, group.title);+ }+ }for (final message in c.messages(group.id)) {for (final link in superTabPullRequestLinks(message.text)) {include(link, group.title);diff --git a/desktop/test/super_tab_pull_requests_test.dart b/desktop/test/super_tab_pull_requests_test.dartindex c2031ad1f..dbe7b47a7 100644--- a/desktop/test/super_tab_pull_requests_test.dart+++ b/desktop/test/super_tab_pull_requests_test.dart@@ -232,6 +232,45 @@ void main() {await tester.pumpAndSettle();expect(find.text('Pull request 1'), findsOneWidget);});+ testWidgets(+ 'stored links merge with loaded messages without duplicate PR rows',+ (tester) async {+ final server = prServer([52, 51]);+ (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((group) => group['id'] == 'lead')['pullRequestUrls'] = [+ prUrl(51),+ prUrl(53),+ ];+ final asked = <List<String>>[];+ await mount(tester, server, (urls) async {+ asked.add(urls);+ return {+ 'rows': [prRow(51), prRow(52), prRow(53)],+ };+ });+ expect(asked.single.toSet(), {prUrl(51), prUrl(52), prUrl(53)});+ expect(asked.single, hasLength(3));+ for (final number in [51, 52, 53]) {+ expect(find.text('Pull request $number'), findsOneWidget);+ }+ expect(find.text('· 3'), findsOneWidget);+ },+ );+ testWidgets(+ 'older snapshots without stored links still use loaded messages',+ (tester) async {+ final asked = <List<String>>[];+ await mount(tester, prServer([54]), (urls) async {+ asked.add(urls);+ return {+ 'rows': [prRow(54)],+ };+ });+ expect(asked.single, [prUrl(54)]);+ expect(find.text('Pull request 54'), findsOneWidget);+ },+ );testWidgets('timeout keeps the last answer and says how old it is', (tester,) async {