The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): hydrate scoped subagents and read extended live transcripts
Teknium975699714dcd
diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsxindex c7a085450be..b58e2057026 100644--- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx@@ -35,6 +35,7 @@ import { SessionControlSections } from './session-control'import { useSessionValue } from './session-control-utils'import { StatusItemRow } from './status-row'import { SubagentSection } from './subagent-section'+import { useSubagentSnapshot } from './use-subagent-snapshot'// Slow safety-net poll for silent exits (processes without notify_on_complete// emit no event when they die). Only armed while a running row is on screen.@@ -93,6 +94,7 @@ interface ComposerStatusStackProps {export function ComposerStatusStack({ onSubmit, queue, sessionId }: ComposerStatusStackProps) {const { t } = useI18n()const navigate = useNavigate()+ useSubagentSnapshot(sessionId)// Subscribe to THIS session's slice only. Both maps churn on other// sessions' activity (subagent ticks, background polls, preview updates in// any tile); a whole-map `useStore` re-rendered every mounted stack — onediff --git a/apps/desktop/src/app/chat/composer/status-stack/subagent-hydration.test.tsx b/apps/desktop/src/app/chat/composer/status-stack/subagent-hydration.test.tsxnew file mode 100644index 00000000000..8ce59a6d33c--- /dev/null+++ b/apps/desktop/src/app/chat/composer/status-stack/subagent-hydration.test.tsx@@ -0,0 +1,94 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, expect, it, vi } from 'vitest'++import * as gateway from '@/store/gateway'+import { _resetSessionOwnerHintsForTests, setSessionOwnerHint } from '@/store/session'+import { $subagentsBySession, upsertSubagent } from '@/store/subagents'++import { ComposerStatusStack } from './index'++vi.stubGlobal(+ 'ResizeObserver',+ class {+ disconnect() {}+ observe() {}+ unobserve() {}+ }+)+Element.prototype.animate = vi.fn(() => ({ cancel() {} }) as Animation)+afterEach(() => {+ cleanup()+ $subagentsBySession.set({})+ _resetSessionOwnerHintsForTests()+ vi.restoreAllMocks()+})++it('hydrates the empty owner composer and exposes an extended owner-routed transcript without leaking on session change', async () => {+ const text = 'Full transcript line with preserved whitespace\n'.repeat(100)++ const request = vi.spyOn(gateway, 'requestGatewayForAgent').mockImplementation(async (_c, _p, method) => {+ if (method === 'subagent.list') {+ return {+ subagents: [{ subagent_id: 'worker', goal: 'Recovered work', started_at: 1000, status: 'running' }],+ delegations: []+ } as never+ }++ if (method === 'subagent.tail') {+ return { subagent_id: 'worker', available: true, text, truncated: true } as never+ }++ return {} as never+ })++ setSessionOwnerHint('parent', { connectionId: 'remote-owner', profile: 'research' })++ const view = render(+ <MemoryRouter>+ <ComposerStatusStack queue={null} sessionId="parent" />+ </MemoryRouter>+ )++ await screen.findByText('Recovered work')+ expect($subagentsBySession.get().parent[0].startedAt).toBe(1000000)+ fireEvent.click(screen.getByRole('button', { name: /Recovered work/ }))+ await waitFor(() => expect(document.querySelector('[data-slot="subagent-transcript"]')?.textContent).toContain(text))+ expect(request).toHaveBeenCalledWith('remote-owner', 'research', 'subagent.tail', {+ session_id: 'parent',+ subagent_id: 'worker'+ })+ view.rerender(+ <MemoryRouter>+ <ComposerStatusStack queue={null} sessionId="other" />+ </MemoryRouter>+ )+ expect(document.querySelector('[data-slot="subagent-transcript"]')).toBeNull()+})++it('does not resurrect a child completed while the roster snapshot was in flight', async () => {+ let resolve!: (value: unknown) => void+ vi.spyOn(gateway, 'requestGatewayForAgent').mockImplementation(async (_c, _p, method) => {+ if (method === 'subagent.list') {+ return (await new Promise<unknown>(r => {+ resolve = r+ })) as never+ }++ return {} as never+ })+ setSessionOwnerHint('parent', { connectionId: 'remote-owner', profile: 'research' })+ upsertSubagent('parent', { subagent_id: 'worker', goal: 'Finishing work' })+ render(+ <MemoryRouter>+ <ComposerStatusStack queue={null} sessionId="parent" />+ </MemoryRouter>+ )+ await waitFor(() => expect(resolve).toBeTypeOf('function'))+ act(() => upsertSubagent('parent', { subagent_id: 'worker', status: 'completed' }, false, 'subagent.complete'))+ await act(async () =>+ resolve({ subagents: [{ subagent_id: 'worker', goal: 'Finishing work', status: 'running' }], delegations: [] })+ )+ expect(screen.queryByText('Finishing work')).toBeNull()+ expect($subagentsBySession.get().parent[0].status).toBe('completed')+})diff --git a/apps/desktop/src/app/chat/composer/status-stack/subagent-section.tsx b/apps/desktop/src/app/chat/composer/status-stack/subagent-section.tsxindex bac54f320da..230cc7fdfb3 100644--- a/apps/desktop/src/app/chat/composer/status-stack/subagent-section.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/subagent-section.tsx@@ -11,6 +11,7 @@ import { useSessionSlice } from '@/lib/use-session-slice'import { $subagentsBySession, type SubagentProgress } from '@/store/subagents'import { SubagentControls } from './subagent-controls'+import { SubagentTranscript } from './subagent-transcript'interface SubagentSectionProps {sessionId: string@@ -78,7 +79,7 @@ export function SubagentSection({ sessionId }: SubagentSectionProps) {</StatusSection>{detail && (<div className="max-h-[25vh] overflow-y-auto overscroll-contain px-3 py-2" data-slot="composer-subagent-detail">- {(detail.status === 'running' || detail.status === 'queued') && (+ {!detail.id.startsWith('delegation:') && (<SubagentControlskey={`${sessionId}:${detail.id}`}sessionId={sessionId}@@ -88,6 +89,9 @@ export function SubagentSection({ sessionId }: SubagentSectionProps) {/>)}<SubagentRow node={{ ...detail, children: [] }} nowMs={nowMs} />+ {!detail.id.startsWith('delegation:') && (+ <SubagentTranscript key={`tail:${sessionId}:${detail.id}`} sessionId={sessionId} subagentId={detail.id} />+ )}</div>)}</div>diff --git a/apps/desktop/src/app/chat/composer/status-stack/subagent-transcript.tsx b/apps/desktop/src/app/chat/composer/status-stack/subagent-transcript.tsxnew file mode 100644index 00000000000..542c45b87eb--- /dev/null+++ b/apps/desktop/src/app/chat/composer/status-stack/subagent-transcript.tsx@@ -0,0 +1,73 @@+import { useEffect, useState } from 'react'++import { useI18n } from '@/i18n'+import { knownOwnerForSession, requestForOwnedSession } from '@/store/session-states'++import { rejectUnownedSubagentRequest } from './use-subagent-snapshot'++interface Tail {+ available: boolean+ text: string+ truncated: boolean+}++export function SubagentTranscript({ sessionId, subagentId }: { sessionId: string; subagentId: string }) {+ const { t } = useI18n()+ const [tail, setTail] = useState<Tail | null>(null)+ useEffect(() => {+ let cancelled = false+ let pending = false+ const owner = JSON.stringify(knownOwnerForSession(sessionId))++ const refresh = async () => {+ if (pending || document.visibilityState === 'hidden') {+ return+ }++ pending = true++ try {+ const result = await requestForOwnedSession<Tail>(sessionId, rejectUnownedSubagentRequest, 'subagent.tail', {+ session_id: sessionId,+ subagent_id: subagentId+ })++ if (!cancelled && owner === JSON.stringify(knownOwnerForSession(sessionId))) {+ setTail({+ available: result.available,+ text: typeof result.text === 'string' ? result.text.slice(-16384) : '',+ truncated: result.truncated+ })+ }+ } catch {+ if (!cancelled) {+ setTail({ available: false, text: '', truncated: false })+ }+ } finally {+ pending = false+ }+ }++ void refresh()+ const timer = window.setInterval(() => void refresh(), 2000)++ return () => {+ cancelled = true+ window.clearInterval(timer)+ }+ }, [sessionId, subagentId])++ return (+ <section className="mt-2 text-xs" data-slot="subagent-transcript">+ <h4 className="text-(--ui-text-secondary)">{t.agents.extendedTranscript}</h4>+ {tail?.truncated && <p className="text-(--ui-text-tertiary)">{t.agents.transcriptTruncated}</p>}+ {tail?.available ? (+ <pre className="max-h-[30vh] overflow-auto whitespace-pre-wrap break-words font-mono text-[0.68rem]">+ {tail.text}+ </pre>+ ) : (+ <p className="text-(--ui-text-tertiary)">{tail ? t.agents.transcriptUnavailable : t.agents.waitingActivity}</p>+ )}+ </section>+ )+}diff --git a/apps/desktop/src/app/chat/composer/status-stack/use-subagent-snapshot.ts b/apps/desktop/src/app/chat/composer/status-stack/use-subagent-snapshot.tsnew file mode 100644index 00000000000..8550121423a--- /dev/null+++ b/apps/desktop/src/app/chat/composer/status-stack/use-subagent-snapshot.ts@@ -0,0 +1,75 @@+import { useStore } from '@nanostores/react'+import { useEffect } from 'react'++import { $gatewayState } from '@/store/session'+import { knownOwnerForSession, requestForOwnedSession } from '@/store/session-states'+import { $subagentsBySession, reconcileSubagentSnapshot, type SubagentPayload } from '@/store/subagents'++export const rejectUnownedSubagentRequest = async <T>(): Promise<T> => {+ throw new Error('Subagent owner unavailable')+}++/** Hydrate even an empty composer; live events remain authoritative over reads. */+export function useSubagentSnapshot(sessionId: string | null) {+ const gatewayState = useStore($gatewayState)+ useEffect(() => {+ if (!sessionId) {+ return+ }++ let cancelled = false+ let pending = false+ let failures = 0++ const refresh = async () => {+ if (cancelled || pending || failures >= 3) {+ return+ }++ pending = true+ const before = $subagentsBySession.get()[sessionId]+ const owner = JSON.stringify(knownOwnerForSession(sessionId))++ try {+ const snapshot = await requestForOwnedSession<{ subagents: SubagentPayload[]; delegations: SubagentPayload[] }>(+ sessionId,+ rejectUnownedSubagentRequest,+ 'subagent.list',+ { session_id: sessionId }+ )++ if (+ !cancelled &&+ owner === JSON.stringify(knownOwnerForSession(sessionId)) &&+ before === $subagentsBySession.get()[sessionId] &&+ Array.isArray(snapshot.subagents)+ ) {+ reconcileSubagentSnapshot(sessionId, snapshot.subagents, snapshot.delegations)+ }++ failures = 0+ } catch {+ // Older backends retain their event-fed frame; don't hot-loop a missing RPC.+ failures+++ } finally {+ pending = false+ }+ }++ void refresh()+ const timer = window.setInterval(() => void refresh(), 5000)++ const retry = () => {+ failures = 0+ void refresh()+ }++ window.addEventListener('focus', retry)++ return () => {+ cancelled = true+ window.clearInterval(timer)+ window.removeEventListener('focus', retry)+ }+ }, [sessionId, gatewayState])+}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 32ec296f75b..cbb7452a379 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1069,6 +1069,10 @@ export const ar = defineLocale({failedToUpdate: name => `فشل تحديث ${name}`},agents: {+ extendedTranscript: 'سجل موسّع',+ transcriptTruncated: 'عرض أحدث 16 KiB',+ transcriptUnavailable: 'السجل المباشر غير متاح',+close: 'إغلاق الوكلاء',title: 'شجرة التوليد',subtitle: 'نشاط الوكلاء الفرعيين المباشر للدور الحالي.',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 11b6d8e6ee3..280d691f19d 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1582,6 +1582,10 @@ export const en: Translations = {resetToMine: 'Back to my map'},agents: {+ extendedTranscript: 'Extended transcript',+ transcriptTruncated: 'Showing the latest 16 KiB',+ transcriptUnavailable: 'Live transcript unavailable',+close: 'Close agents',title: 'Spawn tree',subtitle: 'Live subagent activity for the current turn.',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 4da03e279f9..08d7d3f2851 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -1395,6 +1395,10 @@ export const ja = defineLocale({emptyDesc: 'Hermes がスキルやメモリを蓄積すると、ここに表示されます。'},agents: {+ extendedTranscript: '詳細な実行ログ',+ transcriptTruncated: '最新の 16 KiB を表示',+ transcriptUnavailable: 'ライブログは利用できません',+close: 'エージェントを閉じる',title: 'スポーンツリー',subtitle: '現在のターンのライブサブエージェントのアクティビティ。',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex ae4716db123..45fc98d7b21 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -1660,6 +1660,10 @@ export const ru = defineLocale({resetToMine: 'Вернуться к моей карте'},agents: {+ extendedTranscript: 'Подробный журнал',+ transcriptTruncated: 'Последние 16 КиБ',+ transcriptUnavailable: 'Текущий журнал недоступен',+close: 'Закрыть агентов',title: 'Дерево запусков',subtitle: 'Активные субагенты текущего хода в реальном времени.',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex f30043fe7a3..6ed488b170f 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1393,6 +1393,9 @@ export interface Translations {resetToMine: string}agents: {+ extendedTranscript: string+ transcriptTruncated: string+ transcriptUnavailable: stringclose: stringtitle: stringsubtitle: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 10d4eb9f28b..d5243ce78ed 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -1342,6 +1342,10 @@ export const zhHant = defineLocale({emptyDesc: '當 Hermes 為你的工作建立技能與記憶時,會顯示在這裡。'},agents: {+ extendedTranscript: '完整記錄尾端',+ transcriptTruncated: '顯示最新 16 KiB',+ transcriptUnavailable: '即時記錄無法使用',+close: '關閉代理',title: '派生樹',subtitle: '目前回合的子代理即時活動。',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 2d04fba130e..1366057b68b 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -1754,6 +1754,10 @@ export const zh: Translations = {resetToMine: '返回我的图谱'},agents: {+ extendedTranscript: '扩展记录',+ transcriptTruncated: '显示最新 16 KiB',+ transcriptUnavailable: '实时记录不可用',+close: '关闭代理',title: '派生树',subtitle: '当前回合的子代理实时活动。',diff --git a/apps/desktop/src/store/subagent-snapshot.test.ts b/apps/desktop/src/store/subagent-snapshot.test.tsnew file mode 100644index 00000000000..4605fd74e01--- /dev/null+++ b/apps/desktop/src/store/subagent-snapshot.test.ts@@ -0,0 +1,32 @@+import { afterEach, expect, it } from 'vitest'++import { $subagentsBySession, reconcileSubagentSnapshot } from './subagents'++afterEach(() => $subagentsBySession.set({}))+it('projects unresolved running delegations once, replaces them with real workers, and retires completed units', () => {+ const delegation = {+ delegation_id: 'batch',+ goal: 'Queued unit',+ status: 'running',+ dispatched_at: 1000,+ subagent_ids: []+ }+ reconcileSubagentSnapshot('owner', [], [delegation])+ expect($subagentsBySession.get().owner).toMatchObject([+ { id: 'delegation:batch', goal: 'Queued unit', startedAt: 1000000 }+ ])+ const child = {+ subagent_id: 'worker',+ delegation_id: 'batch',+ goal: 'Actual worker',+ status: 'running',+ started_at: 1001+ }+ reconcileSubagentSnapshot('owner', [child], [delegation])+ expect($subagentsBySession.get().owner.map(row => row.id)).toEqual(['worker'])+ const before = $subagentsBySession.get().owner+ reconcileSubagentSnapshot('owner', [child], [delegation])+ expect($subagentsBySession.get().owner).toBe(before)+ reconcileSubagentSnapshot('owner', [], [{ ...delegation, status: 'completed' }])+ expect($subagentsBySession.get().owner).toEqual([])+})diff --git a/apps/desktop/src/store/subagents.ts b/apps/desktop/src/store/subagents.tsindex ae923aae8d8..fc2103e41f0 100644--- a/apps/desktop/src/store/subagents.ts+++ b/apps/desktop/src/store/subagents.ts@@ -212,6 +212,62 @@ function toProgress(payload: SubagentPayload, prev: SubagentProgress | undefined}}+/** Reconcile a scoped, race-checked snapshot without replacing stream history. */+export function reconcileSubagentSnapshot(+ sid: string,+ children: SubagentPayload[],+ delegations: SubagentPayload[] = []+) {+ const represented = new Set(children.map(child => str(child.delegation_id)).filter(Boolean))++ const payloads: SubagentPayload[] = [+ ...children,+ ...delegations+ .filter(unit => unit.status === 'running' && !represented.has(str(unit.delegation_id)) && str(unit.delegation_id))+ .map(unit => ({+ ...unit,+ subagent_id: `delegation:${str(unit.delegation_id)}`,+ started_at: unit.dispatched_at,+ status: 'queued'+ }))+ ]++ const map = $subagentsBySession.get()+ const previous = map[sid] ?? []+ const ids = new Set(payloads.map(p => str(p.subagent_id)).filter(Boolean))+ const next = previous.filter(item => TERMINAL.has(item.status) || ids.has(item.id))++ for (const payload of payloads) {+ const id = str(payload.subagent_id)++ if (!id) {+ continue+ }++ const index = next.findIndex(item => item.id === id)+ const prev = next[index]++ if (prev && TERMINAL.has(prev.status)) {+ continue+ }++ const projected = toProgress(payload, prev)+ projected.startedAt = (num(payload.started_at) ?? 0) * 1000 || prev?.startedAt || projected.startedAt+ projected.updatedAt = prev?.updatedAt ?? projected.startedAt+ projected.currentTool = str(payload.current_tool) || undefined++ if (index < 0) {+ next.push(projected)+ } else {+ next[index] = JSON.stringify(prev) === JSON.stringify(projected) ? prev : projected+ }+ }++ if (next.length !== previous.length || next.some((item, index) => item !== previous[index])) {+ $subagentsBySession.set({ ...map, [sid]: next })+ }+}+export function clearSessionSubagents(sid: string) {const map = $subagentsBySession.get()