From a12de91bb102184255c35563ee02e60986525a13 Mon Sep 17 00:00:00 2001 From: hejun01 Date: Fri, 20 Nov 2026 11:58:39 +0800 Subject: [PATCH] feat(panel): extract Swarm title, kill state, and parked status via pure RPC for SSH windows --- sidecars/panel/backend/local-scanner.mjs | 82 ++- .../panel/test/ssh-remote-endpoints.test.mjs | 631 ++++++++++++++++++ sidecars/panel/trajectory-metrics.mjs | 196 ++++++ 3 files changed, 900 insertions(+), 9 deletions(-) diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index e15aa67..45bf769 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -14,6 +14,7 @@ import { isDeepStrictEqual } from 'node:util'; import { extractLiveActivity, extractModelSteps, + extractSwarmMetaFromSteps, getMaxMeaningfulStepIndex, isParkedOnSwarmWait, parseIsoMs, @@ -1928,6 +1929,7 @@ export async function enumerateAndSyncConversations({ } const subagentRefs = extractSubagentRefsFromSteps(rawSteps); + const rpcSwarmMeta = extractSwarmMetaFromSteps(rawSteps); const ownSwarmManifest = !isRemote && !conv.isSubagent ? readSwarmManifestForCascade(cidLower) : null; if (ownSwarmManifest?.workerRefs?.length) { @@ -1938,9 +1940,12 @@ export async function enumerateAndSyncConversations({ subagentRefs.push(wRef); } } - if (!nonShortTitle(conv.title) && ownSwarmManifest.title) { - conv.title = ownSwarmManifest.title; - } + } + const resolvedSwarmTitle = !conv.isSubagent + ? String(ownSwarmManifest?.title || rpcSwarmMeta?.title || '').trim() + : ''; + if (!nonShortTitle(conv.title) && resolvedSwarmTitle) { + conv.title = resolvedSwarmTitle; } conv.subagentRefs = subagentRefs; @@ -1950,7 +1955,8 @@ export async function enumerateAndSyncConversations({ conv.stepCount = steps.length; const finalSig = buildConvSig(conv); - const effectiveIsRunning = isRunning && !isParkedOnSwarmWait(rawSteps); + const isParkedSwarm = isParkedOnSwarmWait(rawSteps); + const effectiveIsRunning = isRunning && !isParkedSwarm; if (!effectiveIsRunning && conv.status === 'CASCADE_RUN_STATUS_RUNNING') { conv.status = 'IDLE'; } @@ -1998,6 +2004,8 @@ export async function enumerateAndSyncConversations({ steps: stepsWithOwners, subagentRefs, }; + if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta; + if (isParkedSwarm) cacheEntry.parkedOnSwarmWait = true; if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig; if (conv.appSource && conv.appSource !== 'standalone') { cacheEntry.appSource = conv.appSource; @@ -2017,13 +2025,15 @@ export async function enumerateAndSyncConversations({ const metaChanged = !Array.isArray(prev?.subagentRefs) || JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) || + !isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) || + Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) || (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') || Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion); const stepsChanged = !prev || Boolean(prev.offlineTranscriptFallback) || prev.signature !== finalSig || - Boolean(prev.wasRunning) !== isRunning || + Boolean(prev.wasRunning) !== Boolean(cacheEntry.wasRunning) || !prev.contextLimitTelemetry || !prev.speedClearedTelemetry || !prev.turnRailTelemetry || @@ -2140,7 +2150,21 @@ export async function enumerateAndSyncConversations({ isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; activeCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); } - if (!isRunning) { + const tailStepsOnErr = + partialTailSteps.length > 0 + ? partialTailSteps + : isRemote + ? [] + : readTranscriptTailSteps(conv.cascadeId); + const parkedOnErr = + tailStepsOnErr.length > 0 + ? isParkedOnSwarmWait(tailStepsOnErr) + : Boolean(prev?.parkedOnSwarmWait) && prev.signature === sig; + if (!isRunning || (!offlineRecovered && parkedOnErr)) { + if (isRunning) { + conv.status = 'IDLE'; + conv.liveActivity = null; + } activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); } else { const fallbackLive = resolveBestLiveActivity( @@ -2531,8 +2555,13 @@ export async function enumerateAndSyncConversations({ for (const conv of rawConversations) { if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') { if (!conv.liveActivity) { + const cachedConv = getEntry(conv.cascadeId); + const parkedByCache = + Boolean(cachedConv?.parkedOnSwarmWait) && + cachedConv.signature === buildConvSig(conv); const tailSteps = isRemote ? [] : readTranscriptTailSteps(conv.cascadeId); - if (isParkedOnSwarmWait(tailSteps)) { + const isParked = tailSteps.length > 0 ? isParkedOnSwarmWait(tailSteps) : parkedByCache; + if (isParked) { conv.status = 'IDLE'; conv.liveActivity = null; activeLiveActivityMemo.delete(conv.cascadeId.toLowerCase()); @@ -2602,8 +2631,9 @@ export async function enumerateAndSyncConversations({ for (const rootConv of conversations) { const cid = rootConv.cascadeId.toLowerCase(); + const rootCached = getEntry(rootConv.cascadeId); const swarmManifest = isRemote ? null : readSwarmManifestForCascade(cid); - const swarmTitle = String(swarmManifest?.title || '').trim(); + const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim(); if (swarmTitle) { rootConv.swarmTitle = swarmTitle; const curTitle = String(rootConv.title || '').trim(); @@ -2617,6 +2647,24 @@ export async function enumerateAndSyncConversations({ } const subs = subagentsByRoot.get(cid) || []; + const rpcKilledByMember = new Map(); + const mergeRpcKilled = (killedMap) => { + if (!killedMap || typeof killedMap !== 'object') return; + for (const [memberKey, killMs] of Object.entries(killedMap)) { + const normMember = String(memberKey || '').trim().toLowerCase(); + if (!normMember) continue; + const numMs = Number(killMs || 0); + const prevMs = rpcKilledByMember.get(normMember); + if (prevMs === undefined || numMs > prevMs) { + rpcKilledByMember.set(normMember, numMs); + } + } + }; + mergeRpcKilled(rootCached?.swarmMeta?.killedMembers); + for (const s of subs) { + mergeRpcKilled(getEntry(s.cascadeId)?.swarmMeta?.killedMembers); + } + let swarmCount = 0; for (const s of subs) { const subLower = s.cascadeId.toLowerCase(); @@ -2635,7 +2683,23 @@ export async function enumerateAndSyncConversations({ s.isSwarmWorker = true; s.swarmMemberName = parsedSwarm.memberName; s.isSwarmAuxiliary = Boolean(parsedSwarm.isAuxiliary); - s.killed = Boolean(s.killed || mEntry?.killed); + const memberKey = String(parsedSwarm.memberName || '').trim().toLowerCase(); + const rpcKilledAtMs = + memberKey && rpcKilledByMember.has(memberKey) + ? rpcKilledByMember.get(memberKey) + : undefined; + const subCreatedMs = + s.createdTimeMs || subCached?.createdTimeMs || subCached?.steps?.[0]?.createdAtMs || 0; + const subLastStepMs = + subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0; + const killedByRpc = + rpcKilledAtMs !== undefined && + !( + rpcKilledAtMs > 0 && + ((subCreatedMs > 0 && subCreatedMs > rpcKilledAtMs) || + subLastStepMs > rpcKilledAtMs) + ); + s.killed = Boolean(s.killed || (mEntry ? mEntry.killed : killedByRpc)); if (s.killed) { s.status = 'IDLE'; s.liveActivity = null; diff --git a/sidecars/panel/test/ssh-remote-endpoints.test.mjs b/sidecars/panel/test/ssh-remote-endpoints.test.mjs index 1c566a8..eb15561 100644 --- a/sidecars/panel/test/ssh-remote-endpoints.test.mjs +++ b/sidecars/panel/test/ssh-remote-endpoints.test.mjs @@ -1634,4 +1634,635 @@ test('Fast snapshot invalidates when a remote endpoint is pruned and re-register assert.equal(afterReReg.consumption.account.totalTokens, 900); }); +test('extractSwarmMetaFromSteps parses pure-RPC swarm title & kill calls and ignores failed/canceled calls', async () => { + const { extractSwarmMetaFromSteps } = await import('../trajectory-metrics.mjs'); + + assert.equal(extractSwarmMetaFromSteps([]), null); + assert.equal( + extractSwarmMetaFromSteps([ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { toolCalls: [{ id: 't0', name: 'read_file', argumentsJson: '{}' }] }, + }, + ]), + null + ); + + const t1 = '2026-11-20T10:00:00Z'; + const t2 = '2026-11-20T10:01:00Z'; + const t3 = '2026-11-20T10:02:00Z'; + const t4 = '2026-11-20T10:03:00Z'; + const meta = extractSwarmMetaFromSteps([ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: t1 }, + plannerResponse: { + toolCalls: [ + { + id: 'call-title-1', + name: 'default_api:swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Initial Swarm' }), + }, + { + id: 'call-kill-fail', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '@survivor' }), + }, + ], + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_ERROR', + metadata: { + createdAt: t2, + toolCall: { + id: 'call-kill-fail', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '@survivor' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'call-title-2', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Final GPU Swarm' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t4, + toolCall: { + id: 'call-kill-ok', + name: 'default_api:swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '@Verifier-FE' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_CANCELED', + metadata: { + completedAt: t4, + toolCall: { + id: 'call-title-canceled', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Canceled Title' }), + }, + }, + }, + ]); + + assert.deepEqual(meta, { + title: 'Final GPU Swarm', + killedMembers: { + 'verifier-fe': Date.parse(t4), + }, + }); +}); + +test('SSH remote Swarm recovers swarmTitle, worker killed state (including helper kills & re-added names), and parked swarm_wait across transient RPC errors without remote disk access', async () => { + const baseMs = Date.parse('2026-11-20T10:00:00Z'); + const isoAt = (sec) => new Date(baseMs + sec * 1000).toISOString(); + + const rootCid = 'aaaa1111-1111-4111-8111-111111111111'; + const deadOldCid = 'bbbb2222-2222-4222-8222-222222222222'; + const respawnedCid = 'cccc3333-3333-4333-8333-333333333333'; + const parkedCid = 'dddd4444-4444-4444-8444-444444444444'; + const parentWorkerCid = 'eeee5555-5555-4555-8555-555555555555'; + const killedHelperCid = 'ffff6666-6666-4666-8666-666666666666'; + + const makeModelStep = (idx, sec, inTok, outTok) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: isoAt(sec), + completedAt: isoAt(sec + 1), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: String(inTok), + cacheReadTokens: '0', + outputTokens: String(outTok), + }, + }, + }); + + let failParkedFetch = false; + const h = backendHarness({ + clock: () => baseMs + 120_000, + userStatus: { email: 'ssh-swarm@example.com' }, + // Intentionally put conflicting local swarmMembers for the same rootCid to ensure SSH ignores local disk + swarmMembers: { + [rootCid]: { + title: 'LOCAL DISK SWARM MUST NOT BE READ', + members: {}, + }, + }, + }); + + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:64301', + baseUrl: 'https://127.0.0.1:64301', + csrfToken: '', + wsUrl: 'ws://127.0.0.1:9222/devtools/page/ssh-swarm', + label: 'gpu-swarm', + stableHostKey: 'gpu-swarm', + }); + + const remoteTrajectories = { + [rootCid]: { + trajectory: { + steps: [ + makeModelStep(0, 1, 500, 100), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(5), + toolCall: { + id: 'sw-title', + name: 'swarm', + argumentsJson: JSON.stringify({ + action: 'title', + title: 'Remote GPU Swarm Audit', + }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(30), + toolCall: { + id: 'sw-kill-dead', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'dead-bee' }), + }, + }, + }, + ], + }, + }, + [deadOldCid]: { + trajectory: { steps: [makeModelStep(0, 10, 300, 50)] }, + }, + [respawnedCid]: { + trajectory: { steps: [makeModelStep(0, 45, 400, 80)] }, + }, + [parkedCid]: { + trajectory: { + steps: [ + makeModelStep(0, 15, 250, 40), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(18), + toolCall: { name: 'swarm_wait', argumentsJson: '{"since":5}' }, + }, + }, + ], + }, + }, + [parentWorkerCid]: { + trajectory: { + steps: [ + makeModelStep(0, 12, 200, 30), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(35), + toolCall: { + id: 'sw-kill-helper', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'helper-bee' }), + }, + }, + }, + ], + }, + }, + [killedHelperCid]: { + trajectory: { steps: [makeModelStep(0, 20, 150, 20)] }, + }, + }; + + h.setRemoteWindowRpcInvoker(async (_ep, method, body) => { + if (method === 'GetUserStatus') return { userStatus: { email: 'ssh-swarm@example.com' } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + [rootCid]: { + annotations: { title: '' }, + stepCount: 3, + createdTime: isoAt(0), + lastModifiedTime: isoAt(30), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + [deadOldCid]: { + stepCount: 1, + createdTime: isoAt(10), + lastModifiedTime: isoAt(12), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (dead-bee)' }, + }, + }, + [respawnedCid]: { + stepCount: 1, + createdTime: isoAt(40), // Created AFTER kill at t=30 -> must stay alive + lastModifiedTime: isoAt(46), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (dead-bee)' }, + }, + }, + [parkedCid]: { + stepCount: 2, + createdTime: isoAt(14), + lastModifiedTime: isoAt(18), + status: 'CASCADE_RUN_STATUS_RUNNING', // Parked on swarm_wait -> must downgrade! + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (parked-bee)' }, + }, + }, + [parentWorkerCid]: { + stepCount: 2, + createdTime: isoAt(11), + lastModifiedTime: isoAt(35), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (lead-bee)' }, + }, + }, + [killedHelperCid]: { + stepCount: 1, + createdTime: isoAt(19), + lastModifiedTime: isoAt(21), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: parentWorkerCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (helper-bee)' }, + }, + }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + if (failParkedFetch && body?.cascadeId === parkedCid) { + throw new Error('transient SSH RPC timeout'); + } + return remoteTrajectories[body?.cascadeId] || {}; + } + return {}; + }); + + // Poll 1: Full RPC fetch recovers swarmTitle, killed states, and downgrades parked-bee + const res1 = await h.executeTelemetryAction( + { conversationId: rootCid, range: 'today' }, + { endpointId: ep.id } + ); + assert.equal(res1.status, 200); + const p1 = JSON.parse(res1.body); + assert.equal(p1.activeConversation.swarmTitle, 'Remote GPU Swarm Audit'); + assert.equal(p1.activeConversation.title, 'Remote GPU Swarm Audit'); + assert.equal(p1.runningConversations.length, 0); + + const byCid = new Map(p1.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid.get(deadOldCid)?.swarmState, 'killed'); + assert.equal(byCid.get(respawnedCid)?.swarmState, 'waiting'); + assert.equal(byCid.get(parkedCid)?.swarmState, 'waiting'); + assert.equal(byCid.get(parkedCid)?.isRunning, false); + assert.equal(byCid.get(killedHelperCid)?.swarmState, 'killed'); + + // Poll 2: Transient RPC failure on parked-bee with unchanged signature MUST NOT flicker it back to RUNNING + failParkedFetch = true; + const res2 = await h.executeTelemetryAction( + { conversationId: rootCid, range: 'today' }, + { endpointId: ep.id } + ); + assert.equal(res2.status, 200); + const p2 = JSON.parse(res2.body); + assert.equal(p2.runningConversations.length, 0); + const byCid2 = new Map(p2.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid2.get(parkedCid)?.swarmState, 'waiting'); + assert.equal(byCid2.get(parkedCid)?.isRunning, false); + assert.equal(byCid2.get(deadOldCid)?.swarmState, 'killed'); + + // Poll 3: Fast scope=conversation preserves RPC-derived swarmTitle & killed states + const convRes = await h.executeTelemetryAction( + { scope: 'conversation', conversationId: rootCid, range: 'today' }, + { endpointId: ep.id } + ); + const convPayload = JSON.parse(convRes.body); + assert.equal(convPayload.scope, 'conversation'); + assert.equal(convPayload.activeConversation.swarmTitle, 'Remote GPU Swarm Audit'); + const byCid3 = new Map(convPayload.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid3.get(deadOldCid)?.swarmState, 'killed'); + assert.equal(byCid3.get(killedHelperCid)?.swarmState, 'killed'); +}); + +test('extractSwarmMetaFromSteps guards prototype keys, non-string args, pending/waiting calls, and ID-less failed calls', async () => { + const { isDeepStrictEqual } = await import('node:util'); + const { extractSwarmMetaFromSteps } = await import('../trajectory-metrics.mjs'); + + const t1 = '2026-11-20T11:00:00Z'; + const t2 = '2026-11-20T11:01:00Z'; + const t3 = '2026-11-20T11:02:00Z'; + const meta = extractSwarmMetaFromSteps([ + // Non-string malformed fields must be ignored (never coerced to '[object Object]') + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t1, + toolCall: { + id: 'bad-args-1', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: { bad: 1 } }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t1, + toolCall: { + id: 'bad-args-2', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: ['not-a-string'] }), + }, + }, + }, + // Pending / waiting execution steps (both with ID and without ID) must NOT be applied + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: t1 }, + plannerResponse: { + toolCalls: [ + { + id: 'pending-id', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'still-running' }), + }, + { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'idless-failed' }), + }, + { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Pending Title' }), + }, + ], + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_WAITING', + metadata: { + createdAt: t2, + toolCall: { + id: 'pending-id', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'still-running' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_ERROR', + metadata: { + createdAt: t2, + toolCall: { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'idless-failed' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_RUNNING', + metadata: { + createdAt: t2, + toolCall: { + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'title', title: 'Pending Title' }), + }, + }, + }, + // Prototype-colliding member names ('constructor', 'toString', '__proto__') must work safely + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'proto-1', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'constructor' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'proto-2', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'toString' }), + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: t3, + toolCall: { + id: 'proto-3', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: '__proto__' }), + }, + }, + }, + ]); + + assert.ok(meta); + assert.equal(meta.title, undefined); + assert.equal(Object.getPrototypeOf(meta.killedMembers), Object.prototype); + assert.equal(meta.killedMembers.constructor, Date.parse(t3)); + assert.equal(meta.killedMembers.tostring, Date.parse(t3)); + assert.equal(Object.getOwnPropertyDescriptor(meta.killedMembers, '__proto__')?.value, Date.parse(t3)); + assert.equal(meta.killedMembers['still-running'], undefined); + assert.equal(meta.killedMembers['idless-failed'], undefined); + // JSON round-trip preserves exact structural equality (no NaN -> null corruption) + const roundTripped = JSON.parse(JSON.stringify(meta)); + assert.equal(isDeepStrictEqual(meta, roundTripped), true); +}); + +test('Local Swarm ground truth (members.json killed=false & live transcript.jsonl wakeup) takes precedence over RPC/cache fallbacks', async () => { + const baseMs = Date.parse('2026-11-20T12:00:00Z'); + const isoAt = (sec) => new Date(baseMs + sec * 1000).toISOString(); + + const rootCid = '10101010-1111-4111-8111-111111111111'; + const aliveCid = '20202020-2222-4222-8222-222222222222'; + const wakingCid = '30303030-3333-4333-8333-333333333333'; + + const makeModelStep = (idx, sec) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: isoAt(sec), + completedAt: isoAt(sec + 1), + sourceTrajectoryStepInfo: { stepIndex: idx }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: '200', + cacheReadTokens: '0', + outputTokens: '50', + }, + }, + }); + + const h = backendHarness({ + clock: () => baseMs + 120_000, + userStatus: { email: 'local-swarm@example.com' }, + swarmMembers: { + [rootCid]: { + title: 'Local Manifest Title', + members: { + 'reused-bee': { + conversation_id: aliveCid, + role: 'Swarm Worker (reused-bee)', + killed: false, + }, + 'waking-bee': { + conversation_id: wakingCid, + role: 'Swarm Worker (waking-bee)', + killed: false, + }, + }, + }, + }, + summaries: { + [rootCid]: { + stepCount: 2, + createdTime: isoAt(0), + lastModifiedTime: isoAt(30), + status: 'CASCADE_RUN_STATUS_IDLE', + }, + [aliveCid]: { + stepCount: 1, + // Intentionally omit createdTime & use earlier step time to test mEntry.killed=false precedence + lastModifiedTime: isoAt(10), + status: 'CASCADE_RUN_STATUS_IDLE', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (reused-bee)' }, + }, + }, + [wakingCid]: { + stepCount: 2, + createdTime: isoAt(12), + lastModifiedTime: isoAt(18), + status: 'CASCADE_RUN_STATUS_RUNNING', + trajectoryMetadata: { + parentConversationId: rootCid, + subagentSpec: { typeName: 'worker', role: 'Swarm Worker (waking-bee)' }, + }, + }, + }, + trajectories: { + [rootCid]: { + trajectory: { + steps: [ + makeModelStep(0, 1), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(30), + toolCall: { + id: 'kill-reused', + name: 'swarm', + argumentsJson: JSON.stringify({ action: 'kill', name: 'reused-bee' }), + }, + }, + }, + ], + }, + }, + [aliveCid]: { trajectory: { steps: [makeModelStep(0, 5)] } }, + [wakingCid]: { + trajectory: { + steps: [ + makeModelStep(0, 15), + { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + completedAt: isoAt(18), + toolCall: { name: 'swarm_wait', argumentsJson: '{"since":1}' }, + }, + }, + ], + }, + }, + }, + transcripts: {}, + }); + + // Poll 1: wakingCid is parked on swarm_wait; aliveCid has mEntry.killed=false despite RPC kill + const p1 = await h.buildTelemetryPayloadInternal(rootCid, false, { range: 'today' }); + const byCid1 = new Map(p1.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(p1.activeConversation.swarmTitle, 'Local Manifest Title'); + assert.equal(byCid1.get(aliveCid)?.swarmState, 'waiting'); + assert.equal(byCid1.get(wakingCid)?.swarmState, 'waiting'); + assert.equal(byCid1.get(wakingCid)?.isRunning, false); + + // Poll 2: Simulate wakingCid RPC failing (enters cooldown / skips fetch) WHILE local transcript.jsonl records a wakeup! + h.state.trajectories[wakingCid] = new Error('transient local RPC stall'); + h.state.transcripts[wakingCid] = [ + { + type: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + content: '[swarm] new board message #9', + created_at: isoAt(60), + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_RUNNING', + tool_calls: [{ name: 'read_file', argumentsJson: '{"Path":"main.mjs"}' }], + created_at: isoAt(61), + }, + ]; + h.state.transcriptMtimeMs = 2; + + const p2 = await h.buildTelemetryPayloadInternal(rootCid, false, { range: 'today' }); + const byCid2 = new Map(p2.activeConversation.agents.map((a) => [a.cascadeId, a])); + assert.equal(byCid2.get(wakingCid)?.isRunning, true); + assert.equal(byCid2.get(wakingCid)?.swarmState, 'working'); +}); + diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index 0f80bb5..9330883 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -3042,4 +3042,200 @@ export function isParkedOnSwarmWait(rawSteps = []) { return false; } +function parseSwarmToolArgs(rawToolCall) { + if (!rawToolCall || typeof rawToolCall !== 'object') return null; + const direct = rawToolCall.args || rawToolCall.arguments; + if (direct && typeof direct === 'object' && !Array.isArray(direct)) { + return direct; + } + const rawJson = + typeof rawToolCall.argumentsJson === 'string' + ? rawToolCall.argumentsJson + : typeof direct === 'string' + ? direct + : typeof rawToolCall.function?.arguments === 'string' + ? rawToolCall.function.arguments + : ''; + if (!rawJson.trim()) return null; + try { + const parsed = JSON.parse(rawJson); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } +} + +function normalizeSwarmToolName(rawToolCall) { + return String( + rawToolCall?.name || rawToolCall?.toolName || rawToolCall?.function?.name || '' + ) + .trim() + .toLowerCase() + .replace(/^default_api:/, ''); +} + +function isSwarmStepCompletedSuccess(step) { + const st = typeof step?.status === 'string' ? step.status.trim().toUpperCase() : ''; + if (st) { + if (!LIVE_TERMINAL_STATUSES.has(st)) { + return false; + } + if (st.includes('ERROR') || st.includes('CANCEL') || st.includes('FAIL')) { + return false; + } + } + const tcSt = + typeof step?.metadata?.toolCall?.status === 'string' + ? step.metadata.toolCall.status.trim().toUpperCase() + : ''; + if (tcSt) { + if ( + tcSt.includes('ERROR') || + tcSt.includes('CANCEL') || + tcSt.includes('FAIL') || + /(?:WAIT|PEND|RUN|GENERAT|IN_PROGRESS|STREAM)/i.test(tcSt) + ) { + return false; + } + } + return true; +} + +function extractSwarmCallIntent(rawToolCall) { + const args = parseSwarmToolArgs(rawToolCall); + if (!args || typeof args.action !== 'string') return null; + const action = args.action.trim().toLowerCase(); + if (action === 'title') { + if (typeof args.title !== 'string') return null; + const nextTitle = args.title.trim(); + if (!nextTitle) return null; + return { action: 'title', value: nextTitle, sig: `title:${nextTitle}` }; + } + if (action === 'kill') { + if (typeof args.name !== 'string') return null; + const member = args.name.trim().replace(/^@+/, '').toLowerCase(); + if (!member) return null; + return { action: 'kill', value: member, sig: `kill:${member}` }; + } + return null; +} + +/** + * 从原始轨迹 RPC 步骤中提取 Native Swarm 元数据(纯 RPC 解析,无需读取远端磁盘 `members.json`): + * - `title`:最后一次成功调用 `swarm(action: "title")` 设置的蜂群标题; + * - `killedMembers`:被 `swarm(action: "kill")` 终止的工蜂成员名(小写去 `@`)及其终止时间戳映射。 + * + * @param {Array} [rawSteps=[]] + * @returns {{ title?: string, killedMembers?: Record } | null} + */ +export function extractSwarmMetaFromSteps(rawSteps = []) { + if (!Array.isArray(rawSteps) || rawSteps.length === 0) return null; + + const executedToolCallIds = new Set(); + for (const st of rawSteps) { + const tc = st?.metadata?.toolCall; + if (!tc || normalizeSwarmToolName(tc) !== 'swarm') continue; + const tcId = String(tc.id || tc.toolCallId || '').trim(); + if (tcId) { + executedToolCallIds.add(tcId); + } + } + + let title = ''; + const killedMap = new Map(); + + const applyIntent = (intent, stepMs) => { + if (!intent) return; + if (intent.action === 'title') { + title = intent.value; + } else if (intent.action === 'kill') { + const prevMs = killedMap.get(intent.value); + killedMap.set(intent.value, prevMs === undefined ? stepMs : Math.max(prevMs, stepMs)); + } + }; + + for (let i = 0; i < rawSteps.length; i++) { + const st = rawSteps[i]; + if (!st || typeof st !== 'object') continue; + const stepMs = + parseIsoMs(st?.metadata?.completedAt || st?.metadata?.createdAt || st?.created_at) || 0; + + const execTc = st?.metadata?.toolCall; + if (execTc && normalizeSwarmToolName(execTc) === 'swarm') { + if (isSwarmStepCompletedSuccess(st)) { + applyIntent(extractSwarmCallIntent(execTc), stepMs); + } + continue; + } + + if (!isSwarmStepCompletedSuccess(st)) continue; + const plannerCalls = getStepPlannerToolCalls(st); + if (plannerCalls.length === 0) continue; + + // 收集同一轮次内无 toolCall.id 的执行步骤签名,防止失败或进行中的无 ID 执行步骤回落误触发 planner 提案 + let turnIdlessExecCounts = null; + for (const tc of plannerCalls) { + if (normalizeSwarmToolName(tc) !== 'swarm') continue; + const tcId = String(tc?.id || tc?.toolCallId || '').trim(); + if (tcId && executedToolCallIds.has(tcId)) { + continue; + } + const intent = extractSwarmCallIntent(tc); + if (!intent) continue; + if (!tcId) { + if (!turnIdlessExecCounts) { + turnIdlessExecCounts = new Map(); + for (let j = i + 1; j < rawSteps.length; j++) { + const nextSt = rawSteps[j]; + if (!nextSt || typeof nextSt !== 'object') continue; + const nt = String(nextSt.type || '').trim().toUpperCase(); + if ( + isPlannerStep(nextSt) || + nt.includes('USER_INPUT') || + nt.includes('SYSTEM_MESSAGE') || + isCheckpointStep(nextSt) + ) { + break; + } + const nextExecTc = nextSt?.metadata?.toolCall; + if (!nextExecTc || normalizeSwarmToolName(nextExecTc) !== 'swarm') continue; + const nextExecId = String(nextExecTc.id || nextExecTc.toolCallId || '').trim(); + if (nextExecId) continue; + const nextIntent = extractSwarmCallIntent(nextExecTc); + if (!nextIntent) continue; + turnIdlessExecCounts.set( + nextIntent.sig, + (turnIdlessExecCounts.get(nextIntent.sig) || 0) + 1 + ); + } + } + const matchedCount = turnIdlessExecCounts.get(intent.sig) || 0; + if (matchedCount > 0) { + turnIdlessExecCounts.set(intent.sig, matchedCount - 1); + continue; + } + } + applyIntent(intent, stepMs); + } + } + + if (!title && killedMap.size === 0) return null; + let killedMembers = null; + if (killedMap.size > 0) { + killedMembers = {}; + for (const [member, killMs] of killedMap.entries()) { + Object.defineProperty(killedMembers, member, { + value: killMs, + enumerable: true, + writable: true, + configurable: true, + }); + } + } + return { + ...(title ? { title } : {}), + ...(killedMembers ? { killedMembers } : {}), + }; +} +