@kolisachint/hoocode-agent 0.4.53 → 0.4.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/team-approvals.d.ts +55 -0
- package/dist/core/team-approvals.d.ts.map +1 -0
- package/dist/core/team-approvals.js +95 -0
- package/dist/core/team-approvals.js.map +1 -0
- package/dist/core/team-view.d.ts +29 -0
- package/dist/core/team-view.d.ts.map +1 -1
- package/dist/core/team-view.js +50 -1
- package/dist/core/team-view.js.map +1 -1
- package/dist/modes/interactive/components/team-attach-panel.d.ts +18 -1
- package/dist/modes/interactive/components/team-attach-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/team-attach-panel.js +96 -5
- package/dist/modes/interactive/components/team-attach-panel.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +56 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team-view.d.ts","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElF,uEAAuE;AACvE,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAE7F,+EAA+E;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AC,EAAE,OAAO,SAAS,CAAC;IACzB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IAClC,sDAAsD;IACtD,IAAI,IAAI,IAAI,CAAC;IACb,uEAAuE;IACvE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD;;;;OAIG;IACH,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAChE,gEAAgE;IAChE,eAAe,IAAI,MAAM,CAAC;CAC1B;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,kBAAkB,CA2G9F","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; agent_end only marks clean completions\n\t\t\t\t// (mirrors hooteams' own status tracking).\n\t\t\t\tconst failed = this.store.agents().find((a) => a.id === this.agentId(role))?.state === \"failed\";\n\t\t\t\tif (!failed) {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team-view.d.ts","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElF,uEAAuE;AACvE,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAE7F,+EAA+E;AAC/E,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,qBAAqB,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,E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EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,gCAAgC;IAChC,KAAK,CAAC,EAAE,OAAO,SAAS,CAAC;IACzB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IAClC,sDAAsD;IACtD,IAAI,IAAI,IAAI,CAAC;IACb,uEAAuE;IACvE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD;;;;OAIG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzE;;;;OAIG;IACH,gBAAgB,IAAI,OAAO,CAAC,mBAAmB,EAAE,CAAC,CAAC;IACnD;;;;OAIG;IACH,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAChE,gEAAgE;IAChE,eAAe,IAAI,MAAM,CAAC;CAC1B;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,kBAAkB,CA8H9F","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n\t/** Task lifecycle fields carried by task_* events from the orchestrator. */\n\ttaskId?: string;\n\t/** Approval gate carried by task_paused. */\n\tquestion?: string;\n\toptions?: string[];\n\t/** Answer carried by task_resumed. */\n\tchosenOption?: string;\n\t/** \"done\" | \"error\" on task_finished. */\n\tstatus?: string;\n\t/** Run id carried by dag_complete / dag_failed. */\n\trunId?: string;\n}\n\n/** One unanswered approval gate from GET /tasks/pending. */\nexport interface TeamPendingApproval {\n\ttaskId: string;\n\tquestion: string;\n\toptions: string[];\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tcase \"paused\":\n\t\t\treturn \"waiting\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\" || state === \"waiting\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\t// Dag settlement events are tagged role=\"orchestrator\" — they describe\n\t\t// the run, not a member, and must not create a phantom roster entry.\n\t\tif (event.type === \"dag_complete\" || event.type === \"dag_failed\") return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; agent_end only marks clean completions\n\t\t\t\t// (mirrors hooteams' own status tracking).\n\t\t\t\tconst failed = this.store.agents().find((a) => a.id === this.agentId(role))?.state === \"failed\";\n\t\t\t\tif (!failed) {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\": {\n\t\t\t\tconst title = `awaiting approval: ${event.question ?? \"?\"}`;\n\t\t\t\tthis.ensureRole(role, \"waiting\", title);\n\t\t\t\tthis.patchRole(role, \"waiting\", title);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\": {\n\t\t\t\tconst state = event.status === \"error\" ? \"failed\" : \"done\";\n\t\t\t\tthis.ensureRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tthis.patchRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Answer a paused task: POST /tasks/:taskId/resume { option, feedback? }.\n\t * Rejects with \"answered elsewhere\" on 409 (first answer wins across\n\t * surfaces) and with HTTP/network errors otherwise.\n\t */\n\tresume(taskId: string, option: string, feedback?: string): Promise<void>;\n\t/**\n\t * GET /tasks/pending — gates that opened before we attached. Resolves to\n\t * [] when the server has no active run (404) so callers need no special\n\t * casing.\n\t */\n\tpendingApprovals(): Promise<TeamPendingApproval[]>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync resume(taskId: string, option: string, feedback?: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 409) throw new Error(`task \"${taskId}\" was answered elsewhere`);\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync pendingApprovals(): Promise<TeamPendingApproval[]> {\n\t\t\tconst response = await fetch(`${base}/tasks/pending`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 404) return [];\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tconst body = (await response.json()) as { pending?: TeamPendingApproval[] };\n\t\t\treturn Array.isArray(body.pending) ? body.pending : [];\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
package/dist/core/team-view.js
CHANGED
|
@@ -28,6 +28,8 @@ function stateFromStatus(status) {
|
|
|
28
28
|
return "done";
|
|
29
29
|
case "error":
|
|
30
30
|
return "failed";
|
|
31
|
+
case "paused":
|
|
32
|
+
return "waiting";
|
|
31
33
|
default:
|
|
32
34
|
return "idle";
|
|
33
35
|
}
|
|
@@ -48,7 +50,7 @@ function taskStatusFromState(state) {
|
|
|
48
50
|
}
|
|
49
51
|
/** Only these states represent activity worth a task row of its own. */
|
|
50
52
|
function stateWarrantsTask(state) {
|
|
51
|
-
return state === "active" || state === "running" || state === "failed";
|
|
53
|
+
return state === "active" || state === "running" || state === "failed" || state === "waiting";
|
|
52
54
|
}
|
|
53
55
|
/**
|
|
54
56
|
* Maps team status snapshots and TeamEvents onto task-store patches.
|
|
@@ -79,6 +81,10 @@ export class TeamViewMapper {
|
|
|
79
81
|
applyEvent(event) {
|
|
80
82
|
if (!event || typeof event.role !== "string" || event.role.length === 0)
|
|
81
83
|
return;
|
|
84
|
+
// Dag settlement events are tagged role="orchestrator" — they describe
|
|
85
|
+
// the run, not a member, and must not create a phantom roster entry.
|
|
86
|
+
if (event.type === "dag_complete" || event.type === "dag_failed")
|
|
87
|
+
return;
|
|
82
88
|
const role = event.role;
|
|
83
89
|
switch (event.type) {
|
|
84
90
|
case "agent_start":
|
|
@@ -116,6 +122,26 @@ export class TeamViewMapper {
|
|
|
116
122
|
}
|
|
117
123
|
break;
|
|
118
124
|
}
|
|
125
|
+
case "task_started":
|
|
126
|
+
this.ensureRole(role, "active", `task: ${event.taskId ?? "?"}`);
|
|
127
|
+
this.patchRole(role, "active", `task: ${event.taskId ?? "?"}`);
|
|
128
|
+
break;
|
|
129
|
+
case "task_paused": {
|
|
130
|
+
const title = `awaiting approval: ${event.question ?? "?"}`;
|
|
131
|
+
this.ensureRole(role, "waiting", title);
|
|
132
|
+
this.patchRole(role, "waiting", title);
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
case "task_resumed":
|
|
136
|
+
this.ensureRole(role, "active", `task: ${event.taskId ?? "?"}`);
|
|
137
|
+
this.patchRole(role, "active", `task: ${event.taskId ?? "?"}`);
|
|
138
|
+
break;
|
|
139
|
+
case "task_finished": {
|
|
140
|
+
const state = event.status === "error" ? "failed" : "done";
|
|
141
|
+
this.ensureRole(role, state, state === "failed" ? "error" : "idle");
|
|
142
|
+
this.patchRole(role, state, state === "failed" ? "error" : "idle");
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
119
145
|
default:
|
|
120
146
|
// Unknown event types still prove the role exists.
|
|
121
147
|
this.ensureRole(role, "idle", event.type);
|
|
@@ -262,6 +288,29 @@ export function connectTeamView(url, options = {}) {
|
|
|
262
288
|
if (!response.ok)
|
|
263
289
|
throw new Error(`HTTP ${response.status}`);
|
|
264
290
|
},
|
|
291
|
+
async resume(taskId, option, feedback) {
|
|
292
|
+
const response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {
|
|
293
|
+
method: "POST",
|
|
294
|
+
headers: { "content-type": "application/json" },
|
|
295
|
+
body: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),
|
|
296
|
+
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),
|
|
297
|
+
});
|
|
298
|
+
if (response.status === 409)
|
|
299
|
+
throw new Error(`task "${taskId}" was answered elsewhere`);
|
|
300
|
+
if (!response.ok)
|
|
301
|
+
throw new Error(`HTTP ${response.status}`);
|
|
302
|
+
},
|
|
303
|
+
async pendingApprovals() {
|
|
304
|
+
const response = await fetch(`${base}/tasks/pending`, {
|
|
305
|
+
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),
|
|
306
|
+
});
|
|
307
|
+
if (response.status === 404)
|
|
308
|
+
return [];
|
|
309
|
+
if (!response.ok)
|
|
310
|
+
throw new Error(`HTTP ${response.status}`);
|
|
311
|
+
const body = (await response.json());
|
|
312
|
+
return Array.isArray(body.pending) ? body.pending : [];
|
|
313
|
+
},
|
|
265
314
|
subscribe(listener) {
|
|
266
315
|
listeners.add(listener);
|
|
267
316
|
return () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team-view.js","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAuBlF,4DAA0D;AAC1D,SAAS,eAAe,CAAC,MAA0B,EAAkB;IACpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,QAAQ,CAAC;QACjB,KAAK,MAAM;YACV,OAAO,SAAS,CAAC;QAClB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,OAAO;YACX,OAAO,QAAQ,CAAC;QACjB;YACC,OAAO,MAAM,CAAC;IAChB,CAAC;AAAA,CACD;AAED,SAAS,mBAAmB,CAAC,KAAqB,EAAc;IAC/D,QAAQ,KAAK,EAAE,CAAC;QACf,KAAK,MAA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AE,OAAe,EAAiB;YACzD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,QAAQ,EAAE;gBAC7C,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;gBAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;gBACvC,MAAM,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC;aACnF,CAAC,CAAC;YACH,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QAAA,CAC7D;QACD,SAAS,CAAC,QAAwC,EAAc;YAC/D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE,CAAC;gBACZ,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAAA,CAC3B,CAAC;QAAA,CACF;QACD,eAAe,GAAW;YACzB,OAAO,SAAS,CAAC,IAAI,CAAC;QAAA,CACtB;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; agent_end only marks clean completions\n\t\t\t\t// (mirrors hooteams' own status tracking).\n\t\t\t\tconst failed = this.store.agents().find((a) => a.id === this.agentId(role))?.state === \"failed\";\n\t\t\t\tif (!failed) {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team-view.js","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAyClF,4DAA0D;AAC1D,SAAS,eAAe,CAAC,MAA0B,EAAkB;IACpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,QAAQ,CAAC;QACjB,KAAK,MAAM;YACV,OAAO,SAAS,CAAC;QAClB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,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AAA,CACF;QACD,eAAe,GAAW;YACzB,OAAO,SAAS,CAAC,IAAI,CAAC;QAAA,CACtB;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n\t/** Task lifecycle fields carried by task_* events from the orchestrator. */\n\ttaskId?: string;\n\t/** Approval gate carried by task_paused. */\n\tquestion?: string;\n\toptions?: string[];\n\t/** Answer carried by task_resumed. */\n\tchosenOption?: string;\n\t/** \"done\" | \"error\" on task_finished. */\n\tstatus?: string;\n\t/** Run id carried by dag_complete / dag_failed. */\n\trunId?: string;\n}\n\n/** One unanswered approval gate from GET /tasks/pending. */\nexport interface TeamPendingApproval {\n\ttaskId: string;\n\tquestion: string;\n\toptions: string[];\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tcase \"paused\":\n\t\t\treturn \"waiting\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\" || state === \"waiting\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\t// Dag settlement events are tagged role=\"orchestrator\" — they describe\n\t\t// the run, not a member, and must not create a phantom roster entry.\n\t\tif (event.type === \"dag_complete\" || event.type === \"dag_failed\") return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; agent_end only marks clean completions\n\t\t\t\t// (mirrors hooteams' own status tracking).\n\t\t\t\tconst failed = this.store.agents().find((a) => a.id === this.agentId(role))?.state === \"failed\";\n\t\t\t\tif (!failed) {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\": {\n\t\t\t\tconst title = `awaiting approval: ${event.question ?? \"?\"}`;\n\t\t\t\tthis.ensureRole(role, \"waiting\", title);\n\t\t\t\tthis.patchRole(role, \"waiting\", title);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\": {\n\t\t\t\tconst state = event.status === \"error\" ? \"failed\" : \"done\";\n\t\t\t\tthis.ensureRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tthis.patchRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Answer a paused task: POST /tasks/:taskId/resume { option, feedback? }.\n\t * Rejects with \"answered elsewhere\" on 409 (first answer wins across\n\t * surfaces) and with HTTP/network errors otherwise.\n\t */\n\tresume(taskId: string, option: string, feedback?: string): Promise<void>;\n\t/**\n\t * GET /tasks/pending — gates that opened before we attached. Resolves to\n\t * [] when the server has no active run (404) so callers need no special\n\t * casing.\n\t */\n\tpendingApprovals(): Promise<TeamPendingApproval[]>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync resume(taskId: string, option: string, feedback?: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 409) throw new Error(`task \"${taskId}\" was answered elsewhere`);\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync pendingApprovals(): Promise<TeamPendingApproval[]> {\n\t\t\tconst response = await fetch(`${base}/tasks/pending`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 404) return [];\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tconst body = (await response.json()) as { pending?: TeamPendingApproval[] };\n\t\t\treturn Array.isArray(body.pending) ? body.pending : [];\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
|
@@ -11,8 +11,15 @@
|
|
|
11
11
|
* The panel filters the team connection's single shared /events subscription —
|
|
12
12
|
* it never opens its own SSE connection — and unsubscribes on dispose(), so
|
|
13
13
|
* attach/detach cycles leave no leaked subscribers.
|
|
14
|
+
*
|
|
15
|
+
* Approval gates: task_* lifecycle events render as stream lines, and when the
|
|
16
|
+
* attached role pauses, presentApproval() embeds the AskOptions pane right
|
|
17
|
+
* where the stream stopped — pick an option (or type a free-form answer) and
|
|
18
|
+
* the caller answers the server; the stream then carries on under a
|
|
19
|
+
* "✓ answered: …" stamp.
|
|
14
20
|
*/
|
|
15
21
|
import type { Component, Focusable, TUI } from "@kolisachint/hoocode-tui";
|
|
22
|
+
import type { TeamApproval } from "../../../core/team-approvals.js";
|
|
16
23
|
import type { TeamViewConnection } from "../../../core/team-view.js";
|
|
17
24
|
/** Fixed-capacity FIFO over a circular array: push evicts the oldest entry. */
|
|
18
25
|
export declare class RingBuffer<T> {
|
|
@@ -41,10 +48,20 @@ export declare class TeamAttachPanelComponent implements Component, Focusable {
|
|
|
41
48
|
private partial;
|
|
42
49
|
private partialKind;
|
|
43
50
|
private unsubscribe;
|
|
51
|
+
/** Gate currently embedded in the panel; input is delegated to it. */
|
|
52
|
+
private approval;
|
|
44
53
|
constructor(role: string, connection: TeamViewConnection, callbacks: TeamAttachPanelCallbacks, ui?: TUI | undefined, bufferLines?: number);
|
|
45
|
-
/** Detach from the shared event stream. Idempotent. */
|
|
54
|
+
/** Detach from the shared event stream; settles any open gate as skipped. Idempotent. */
|
|
46
55
|
dispose(): void;
|
|
47
56
|
invalidate(): void;
|
|
57
|
+
/**
|
|
58
|
+
* Embed one approval gate in the panel (the attached role paused). Resolves
|
|
59
|
+
* with the chosen or free-form answer; undefined when skipped (esc), when
|
|
60
|
+
* the signal aborts (answered elsewhere), or when the panel is disposed.
|
|
61
|
+
* Answering the server is the caller's job — on an answer the panel just
|
|
62
|
+
* stamps "✓ answered: …" into the stream.
|
|
63
|
+
*/
|
|
64
|
+
presentApproval(approval: TeamApproval, signal: AbortSignal): Promise<string | undefined>;
|
|
48
65
|
handleInput(data: string): void;
|
|
49
66
|
private styledPartial;
|
|
50
67
|
/** Flush the streaming tail into the buffer as a finished line. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team-attach-panel.d.ts","sourceRoot":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vD,OAAO,IAAI,IAAI,CAGd;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAQ9B;IAED,OAAO,CAAC,aAAa;IAIrB,mEAAmE;IACnE,OAAO,CAAC,SAAS;IAMjB,iFAAiF;IACjF,OAAO,CAAC,WAAW;IAYnB,4EAA4E;IAC5E,OAAO,CAAC,UAAU;IA8DlB,6EAA6E;IAC7E,iBAAiB,IAAI,MAAM,CAE1B;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAyC9B;CACD","sourcesContent":["/**\n * Attach side-panel for a hooteams role (`a` in team focus).\n *\n * Renders one role's live TeamEvents in the style of hooteams' StreamRenderer\n * (`hooteams attach <role>`): ◉ lifecycle lines, dim italic thinking, inline\n * streaming text, ✓/✗ tool results, dim per-turn usage stamps. Differences\n * from the CLI renderer are dictated by the host: colors go through hoocode's\n * theme helpers (no raw ANSI) and output lands in a bounded ring buffer\n * instead of an unbounded stdout stream.\n *\n * The panel filters the team connection's single shared /events subscription —\n * it never opens its own SSE connection — and unsubscribes on dispose(), so\n * attach/detach cycles leave no leaked subscribers.\n */\n\nimport type { Component, Focusable, TUI } from \"@kolisachint/hoocode-tui\";\nimport { getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from \"@kolisachint/hoocode-tui\";\nimport type { TeamViewConnection, TeamViewEvent } from \"../../../core/team-view.js\";\nimport { theme } from \"../theme/theme.js\";\n\n/** Fixed-capacity FIFO over a circular array: push evicts the oldest entry. */\nexport class RingBuffer<T> {\n\tprivate readonly slots: (T | undefined)[];\n\tprivate start = 0;\n\tprivate count = 0;\n\n\tconstructor(readonly capacity: number) {\n\t\tif (!Number.isInteger(capacity) || capacity <= 0) throw new Error(`invalid ring buffer capacity ${capacity}`);\n\t\tthis.slots = new Array<T | undefined>(capacity);\n\t}\n\n\tpush(item: T): void {\n\t\tconst end = (this.start + this.count) % this.capacity;\n\t\tthis.slots[end] = item;\n\t\tif (this.count < this.capacity) this.count++;\n\t\telse this.start = (this.start + 1) % this.capacity;\n\t}\n\n\tget length(): number {\n\t\treturn this.count;\n\t}\n\n\ttoArray(): T[] {\n\t\tconst out: T[] = [];\n\t\tfor (let i = 0; i < this.count; i++) {\n\t\t\tout.push(this.slots[(this.start + i) % this.capacity] as T);\n\t\t}\n\t\treturn out;\n\t}\n}\n\nfunction argsPreview(args: unknown, max = 60): string {\n\tconst text = JSON.stringify(args) ?? \"\";\n\treturn text.length > max ? `${text.slice(0, max)}…` : text;\n}\n\nexport interface TeamAttachPanelCallbacks {\n\t/** `q`/esc: close the panel; the role keeps running. */\n\tonDetach: () => void;\n\t/** `n`: nudge the attached role. */\n\tonNudge: (role: string) => void;\n}\n\n/** Logical event lines kept in the buffer (wrapped to width at render time). */\nconst DEFAULT_BUFFER_LINES = 200;\n\nexport class TeamAttachPanelComponent implements Component, Focusable {\n\tfocused = false;\n\n\tprivate readonly lines: RingBuffer<string>;\n\t/** Streaming tail (text/thinking deltas) not yet terminated by a line break. */\n\tprivate partial = \"\";\n\tprivate partialKind: \"text\" | \"thinking\" = \"text\";\n\tprivate unsubscribe: (() => void) | undefined;\n\n\tconstructor(\n\t\treadonly role: string,\n\t\tconnection: TeamViewConnection,\n\t\tprivate readonly callbacks: TeamAttachPanelCallbacks,\n\t\tprivate readonly ui?: TUI,\n\t\tbufferLines = DEFAULT_BUFFER_LINES,\n\t) {\n\t\tthis.lines = new RingBuffer(bufferLines);\n\t\t// Filter the shared stream down to this role; no second SSE connection.\n\t\tthis.unsubscribe = connection.subscribe((event) => {\n\t\t\tif (event.role !== this.role) return;\n\t\t\tthis.applyEvent(event);\n\t\t\tthis.ui?.requestRender();\n\t\t});\n\t}\n\n\t/** Detach from the shared event stream. Idempotent. */\n\tdispose(): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached rendering state.\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (matchesKey(data, \"q\") || getKeybindings().matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.callbacks.onDetach();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"n\")) {\n\t\t\tthis.callbacks.onNudge(this.role);\n\t\t}\n\t}\n\n\tprivate styledPartial(): string {\n\t\treturn this.partialKind === \"thinking\" ? theme.italic(theme.fg(\"dim\", this.partial)) : this.partial;\n\t}\n\n\t/** Flush the streaming tail into the buffer as a finished line. */\n\tprivate breakLine(): void {\n\t\tif (this.partial.length === 0) return;\n\t\tthis.lines.push(this.styledPartial());\n\t\tthis.partial = \"\";\n\t}\n\n\t/** Append streaming delta text, completing buffer lines at embedded newlines. */\n\tprivate appendDelta(delta: string, kind: \"text\" | \"thinking\"): void {\n\t\tif (this.partialKind !== kind) this.breakLine();\n\t\tthis.partialKind = kind;\n\t\tconst parts = delta.split(\"\\n\");\n\t\tfor (let i = 0; i < parts.length - 1; i++) {\n\t\t\tthis.partial += parts[i];\n\t\t\tthis.breakLine();\n\t\t\tthis.partialKind = kind;\n\t\t}\n\t\tthis.partial += parts[parts.length - 1];\n\t}\n\n\t/** Mirrors hooteams' StreamRenderer event handling, themed and buffered. */\n\tprivate applyEvent(event: TeamViewEvent): void {\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(theme.fg(\"accent\", `◉ ${event.role} started`));\n\t\t\t\tbreak;\n\t\t\tcase \"message_update\": {\n\t\t\t\tconst delta = event.assistantMessageEvent;\n\t\t\t\tif (!delta) break;\n\t\t\t\tif (delta.type === \"thinking_start\") {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t\tthis.lines.push(theme.fg(\"dim\", \"◉ thinking…\"));\n\t\t\t\t} else if (delta.type === \"thinking_delta\") {\n\t\t\t\t\tthis.appendDelta(delta.delta ?? \"\", \"thinking\");\n\t\t\t\t} else if (delta.type === \"thinking_end\") {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t} else if (delta.type === \"text_delta\") {\n\t\t\t\t\tthis.appendDelta(delta.delta ?? \"\", \"text\");\n\t\t\t\t} else if (delta.type === \"text_end\") {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(\n\t\t\t\t\ttheme.fg(\"accent\", \"◉ tool: \") +\n\t\t\t\t\t\ttheme.bold(theme.fg(\"accent\", event.toolName ?? \"?\")) +\n\t\t\t\t\t\ttheme.fg(\"accent\", `(${argsPreview(event.args)})`) +\n\t\t\t\t\t\t\" \" +\n\t\t\t\t\t\ttheme.fg(\"warning\", \"running…\"),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(\n\t\t\t\t\tevent.isError\n\t\t\t\t\t\t? theme.fg(\"error\", ` ✗ ${event.toolName ?? \"?\"} failed`)\n\t\t\t\t\t\t: theme.fg(\"success\", ` ✓ ${event.toolName ?? \"?\"} done`),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\": {\n\t\t\t\tthis.breakLine();\n\t\t\t\tconst usage = event.message?.usage;\n\t\t\t\tif (usage) {\n\t\t\t\t\tconst cost = usage.cost?.total ? ` $${usage.cost.total.toFixed(4)}` : \"\";\n\t\t\t\t\tthis.lines.push(\n\t\t\t\t\t\ttheme.fg(\"dim\", `— turn: ${usage.input ?? 0} in / ${usage.output ?? 0} out tokens${cost}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (event.message?.errorMessage) {\n\t\t\t\t\tthis.lines.push(theme.fg(\"error\", `error: ${event.message.errorMessage}`));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(theme.fg(\"accent\", `◉ ${event.role} idle`));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Buffered logical line count (completed lines only). Exposed for tests. */\n\tbufferedLineCount(): number {\n\t\treturn this.lines.length;\n\t}\n\n\trender(width: number): string[] {\n\t\tconst inner = Math.max(1, width);\n\n\t\t// Header: role identity left, key hints right.\n\t\tconst titlePlain = `◉ ${this.role} — attached`;\n\t\tconst title =\n\t\t\ttheme.fg(\"accent\", \"◉ \") + theme.bold(theme.fg(\"accent\", this.role)) + theme.fg(\"muted\", \" — attached\");\n\t\tconst hintsPlain = \"n nudge · q detach\";\n\t\tconst hints = theme.fg(\"dim\", hintsPlain);\n\t\tlet header: string;\n\t\tif (visibleWidth(titlePlain) + 2 + visibleWidth(hintsPlain) <= inner) {\n\t\t\theader = title + \" \".repeat(inner - visibleWidth(titlePlain) - visibleWidth(hintsPlain)) + hints;\n\t\t} else {\n\t\t\theader = truncateToWidth(title, inner, \"…\");\n\t\t}\n\t\tconst rule = theme.fg(\"borderMuted\", \"─\".repeat(inner));\n\n\t\t// Body: wrap each buffered line, then keep the newest rows that fit the\n\t\t// panel's height budget (the freshest output hugs the bottom, like a\n\t\t// terminal tail). Budget derives from the live terminal height so the\n\t\t// panel never asks the overlay compositor to clip it (clipping drops the\n\t\t// bottom — exactly the rows we care about).\n\t\tconst rows = this.ui?.terminal.rows ?? 24;\n\t\tconst bodyBudget = Math.max(5, Math.floor(rows * 0.6) - 3);\n\t\tconst wrapped: string[] = [];\n\t\tfor (const line of this.lines.toArray()) {\n\t\t\tif (line.length === 0) {\n\t\t\t\twrapped.push(\"\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\twrapped.push(...wrapTextWithAnsi(line, inner));\n\t\t}\n\t\tif (this.partial.length > 0) {\n\t\t\twrapped.push(...wrapTextWithAnsi(this.styledPartial(), inner));\n\t\t}\n\t\tconst body = wrapped.slice(-bodyBudget);\n\t\tif (body.length === 0) {\n\t\t\tbody.push(theme.fg(\"dim\", \"waiting for events…\"));\n\t\t}\n\n\t\treturn [header, rule, ...body, rule];\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team-attach-panel.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/team-attach-panel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAG1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,KAAK,EAAE,kBAAkB,EAAiB,MAAM,4BAA4B,CAAC;AAIpF,+EAA+E;AAC/E,qBAAa,UAAU,CAAC,CAAC;IAKZ,QAAQ,CAAC,QAAQ,EAAE,MAAM;IAJrC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAoB;IAC1C,OAAO,CAAC,KAAK,CAAK;IAClB,OAAO,CAAC,KAAK,CAAK;IAElB,YAAqB,QAAQ,EAAE,MAAM,EAGpC;IAED,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,IAAI,CAKlB;IAED,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED,OAAO,IAAI,CAAC,EAAE,CAMb;CACD;AAOD,MAAM,WAAW,wBAAwB;IACxC,wDAAwD;IACxD,QAAQ,EAAE,MAAM,IAAI,CAAC;IACrB,oCAAoC;IACpC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAKD,qBAAa,wBAAyB,YAAW,SAAS,EAAE,SAAS;IAYnE,QAAQ,CAAC,IAAI,EAAE,MAAM;IAErB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;IAdrB,OAAO,UAAS;IAEhB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;IAC3C,gFAAgF;IAChF,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,WAAW,CAA+B;IAClD,OAAO,CAAC,WAAW,CAA2B;IAC9C,sEAAsE;IACtE,OAAO,CAAC,QAAQ,CAA+F;IAE/G,YACU,IAAI,EAAE,MAAM,EACrB,UAAU,EAAE,kBAAkB,EACb,SAAS,EAAE,wBAAwB,EACnC,EAAE,CAAC,iBAAK,EACzB,WAAW,SAAuB,EASlC;IAED,yFAAyF;IACzF,OAAO,IAAI,IAAI,CAId;IAED,UAAU,IAAI,IAAI,CAEjB;IAED;;;;;;OAMG;IACH,eAAe,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA0CxF;IAED,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAc9B;IAED,OAAO,CAAC,aAAa;IAIrB,mEAAmE;IACnE,OAAO,CAAC,SAAS;IAMjB,iFAAiF;IACjF,OAAO,CAAC,WAAW;IAYnB,4EAA4E;IAC5E,OAAO,CAAC,UAAU;IAuFlB,6EAA6E;IAC7E,iBAAiB,IAAI,MAAM,CAE1B;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAsD9B;CACD","sourcesContent":["/**\n * Attach side-panel for a hooteams role (`a` in team focus).\n *\n * Renders one role's live TeamEvents in the style of hooteams' StreamRenderer\n * (`hooteams attach <role>`): ◉ lifecycle lines, dim italic thinking, inline\n * streaming text, ✓/✗ tool results, dim per-turn usage stamps. Differences\n * from the CLI renderer are dictated by the host: colors go through hoocode's\n * theme helpers (no raw ANSI) and output lands in a bounded ring buffer\n * instead of an unbounded stdout stream.\n *\n * The panel filters the team connection's single shared /events subscription —\n * it never opens its own SSE connection — and unsubscribes on dispose(), so\n * attach/detach cycles leave no leaked subscribers.\n *\n * Approval gates: task_* lifecycle events render as stream lines, and when the\n * attached role pauses, presentApproval() embeds the AskOptions pane right\n * where the stream stopped — pick an option (or type a free-form answer) and\n * the caller answers the server; the stream then carries on under a\n * \"✓ answered: …\" stamp.\n */\n\nimport type { Component, Focusable, TUI } from \"@kolisachint/hoocode-tui\";\nimport { getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from \"@kolisachint/hoocode-tui\";\nimport type { AskQuestion } from \"../../../core/extensions/types.js\";\nimport type { TeamApproval } from \"../../../core/team-approvals.js\";\nimport type { TeamViewConnection, TeamViewEvent } from \"../../../core/team-view.js\";\nimport { theme } from \"../theme/theme.js\";\nimport { AskOptionsComponent } from \"./ask-options.js\";\n\n/** Fixed-capacity FIFO over a circular array: push evicts the oldest entry. */\nexport class RingBuffer<T> {\n\tprivate readonly slots: (T | undefined)[];\n\tprivate start = 0;\n\tprivate count = 0;\n\n\tconstructor(readonly capacity: number) {\n\t\tif (!Number.isInteger(capacity) || capacity <= 0) throw new Error(`invalid ring buffer capacity ${capacity}`);\n\t\tthis.slots = new Array<T | undefined>(capacity);\n\t}\n\n\tpush(item: T): void {\n\t\tconst end = (this.start + this.count) % this.capacity;\n\t\tthis.slots[end] = item;\n\t\tif (this.count < this.capacity) this.count++;\n\t\telse this.start = (this.start + 1) % this.capacity;\n\t}\n\n\tget length(): number {\n\t\treturn this.count;\n\t}\n\n\ttoArray(): T[] {\n\t\tconst out: T[] = [];\n\t\tfor (let i = 0; i < this.count; i++) {\n\t\t\tout.push(this.slots[(this.start + i) % this.capacity] as T);\n\t\t}\n\t\treturn out;\n\t}\n}\n\nfunction argsPreview(args: unknown, max = 60): string {\n\tconst text = JSON.stringify(args) ?? \"\";\n\treturn text.length > max ? `${text.slice(0, max)}…` : text;\n}\n\nexport interface TeamAttachPanelCallbacks {\n\t/** `q`/esc: close the panel; the role keeps running. */\n\tonDetach: () => void;\n\t/** `n`: nudge the attached role. */\n\tonNudge: (role: string) => void;\n}\n\n/** Logical event lines kept in the buffer (wrapped to width at render time). */\nconst DEFAULT_BUFFER_LINES = 200;\n\nexport class TeamAttachPanelComponent implements Component, Focusable {\n\tfocused = false;\n\n\tprivate readonly lines: RingBuffer<string>;\n\t/** Streaming tail (text/thinking deltas) not yet terminated by a line break. */\n\tprivate partial = \"\";\n\tprivate partialKind: \"text\" | \"thinking\" = \"text\";\n\tprivate unsubscribe: (() => void) | undefined;\n\t/** Gate currently embedded in the panel; input is delegated to it. */\n\tprivate approval: { component: AskOptionsComponent; settle: (answer: string | undefined) => void } | undefined;\n\n\tconstructor(\n\t\treadonly role: string,\n\t\tconnection: TeamViewConnection,\n\t\tprivate readonly callbacks: TeamAttachPanelCallbacks,\n\t\tprivate readonly ui?: TUI,\n\t\tbufferLines = DEFAULT_BUFFER_LINES,\n\t) {\n\t\tthis.lines = new RingBuffer(bufferLines);\n\t\t// Filter the shared stream down to this role; no second SSE connection.\n\t\tthis.unsubscribe = connection.subscribe((event) => {\n\t\t\tif (event.role !== this.role) return;\n\t\t\tthis.applyEvent(event);\n\t\t\tthis.ui?.requestRender();\n\t\t});\n\t}\n\n\t/** Detach from the shared event stream; settles any open gate as skipped. Idempotent. */\n\tdispose(): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t\tthis.approval?.settle(undefined);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached rendering state.\n\t}\n\n\t/**\n\t * Embed one approval gate in the panel (the attached role paused). Resolves\n\t * with the chosen or free-form answer; undefined when skipped (esc), when\n\t * the signal aborts (answered elsewhere), or when the panel is disposed.\n\t * Answering the server is the caller's job — on an answer the panel just\n\t * stamps \"✓ answered: …\" into the stream.\n\t */\n\tpresentApproval(approval: TeamApproval, signal: AbortSignal): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (signal.aborted || this.unsubscribe === undefined) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// The coordinator shows one gate at a time; a stray second call\n\t\t\t// settles the first as skipped instead of stacking panes.\n\t\t\tthis.approval?.settle(undefined);\n\n\t\t\tlet settled = false;\n\t\t\tconst settle = (answer: string | undefined): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tthis.approval = undefined;\n\t\t\t\tif (answer !== undefined) {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t\tthis.lines.push(theme.fg(\"success\", ` ✓ answered: ${answer}`));\n\t\t\t\t}\n\t\t\t\tthis.ui?.requestRender();\n\t\t\t\tresolve(answer);\n\t\t\t};\n\t\t\tconst onAbort = (): void => settle(undefined);\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tconst question: AskQuestion = {\n\t\t\t\tquestion: approval.question,\n\t\t\t\tshort: approval.taskId,\n\t\t\t\tdetail: `team task \"${approval.taskId}\" is paused until answered`,\n\t\t\t\toptions: approval.options.map((label) => ({ label })),\n\t\t\t\tallowCustom: true,\n\t\t\t};\n\t\t\tconst component = new AskOptionsComponent(\n\t\t\t\t[question],\n\t\t\t\t(answers) => settle(answers[0]),\n\t\t\t\t() => settle(undefined),\n\t\t\t);\n\t\t\tcomponent.focused = this.focused;\n\t\t\tthis.approval = { component, settle };\n\t\t\tthis.ui?.requestRender();\n\t\t});\n\t}\n\n\thandleInput(data: string): void {\n\t\t// An open gate owns the keyboard: q/n must type into the custom row, not\n\t\t// detach or nudge. esc skips the gate (AskOptions cancel), not the panel.\n\t\tif (this.approval) {\n\t\t\tthis.approval.component.handleInput(data);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"q\") || getKeybindings().matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.callbacks.onDetach();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"n\")) {\n\t\t\tthis.callbacks.onNudge(this.role);\n\t\t}\n\t}\n\n\tprivate styledPartial(): string {\n\t\treturn this.partialKind === \"thinking\" ? theme.italic(theme.fg(\"dim\", this.partial)) : this.partial;\n\t}\n\n\t/** Flush the streaming tail into the buffer as a finished line. */\n\tprivate breakLine(): void {\n\t\tif (this.partial.length === 0) return;\n\t\tthis.lines.push(this.styledPartial());\n\t\tthis.partial = \"\";\n\t}\n\n\t/** Append streaming delta text, completing buffer lines at embedded newlines. */\n\tprivate appendDelta(delta: string, kind: \"text\" | \"thinking\"): void {\n\t\tif (this.partialKind !== kind) this.breakLine();\n\t\tthis.partialKind = kind;\n\t\tconst parts = delta.split(\"\\n\");\n\t\tfor (let i = 0; i < parts.length - 1; i++) {\n\t\t\tthis.partial += parts[i];\n\t\t\tthis.breakLine();\n\t\t\tthis.partialKind = kind;\n\t\t}\n\t\tthis.partial += parts[parts.length - 1];\n\t}\n\n\t/** Mirrors hooteams' StreamRenderer event handling, themed and buffered. */\n\tprivate applyEvent(event: TeamViewEvent): void {\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(theme.fg(\"accent\", `◉ ${event.role} started`));\n\t\t\t\tbreak;\n\t\t\tcase \"message_update\": {\n\t\t\t\tconst delta = event.assistantMessageEvent;\n\t\t\t\tif (!delta) break;\n\t\t\t\tif (delta.type === \"thinking_start\") {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t\tthis.lines.push(theme.fg(\"dim\", \"◉ thinking…\"));\n\t\t\t\t} else if (delta.type === \"thinking_delta\") {\n\t\t\t\t\tthis.appendDelta(delta.delta ?? \"\", \"thinking\");\n\t\t\t\t} else if (delta.type === \"thinking_end\") {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t} else if (delta.type === \"text_delta\") {\n\t\t\t\t\tthis.appendDelta(delta.delta ?? \"\", \"text\");\n\t\t\t\t} else if (delta.type === \"text_end\") {\n\t\t\t\t\tthis.breakLine();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(\n\t\t\t\t\ttheme.fg(\"accent\", \"◉ tool: \") +\n\t\t\t\t\t\ttheme.bold(theme.fg(\"accent\", event.toolName ?? \"?\")) +\n\t\t\t\t\t\ttheme.fg(\"accent\", `(${argsPreview(event.args)})`) +\n\t\t\t\t\t\t\" \" +\n\t\t\t\t\t\ttheme.fg(\"warning\", \"running…\"),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(\n\t\t\t\t\tevent.isError\n\t\t\t\t\t\t? theme.fg(\"error\", ` ✗ ${event.toolName ?? \"?\"} failed`)\n\t\t\t\t\t\t: theme.fg(\"success\", ` ✓ ${event.toolName ?? \"?\"} done`),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\": {\n\t\t\t\tthis.breakLine();\n\t\t\t\tconst usage = event.message?.usage;\n\t\t\t\tif (usage) {\n\t\t\t\t\tconst cost = usage.cost?.total ? ` $${usage.cost.total.toFixed(4)}` : \"\";\n\t\t\t\t\tthis.lines.push(\n\t\t\t\t\t\ttheme.fg(\"dim\", `— turn: ${usage.input ?? 0} in / ${usage.output ?? 0} out tokens${cost}`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (event.message?.errorMessage) {\n\t\t\t\t\tthis.lines.push(theme.fg(\"error\", `error: ${event.message.errorMessage}`));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(theme.fg(\"accent\", `◉ ${event.role} idle`));\n\t\t\t\tbreak;\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(theme.fg(\"accent\", `◉ task ${event.taskId ?? \"?\"} started`));\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(theme.fg(\"warning\", `⏸ awaiting approval: ${event.question ?? \"?\"}`));\n\t\t\t\tbreak;\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(\n\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\"accent\",\n\t\t\t\t\t\t`▶ task ${event.taskId ?? \"?\"} resumed${event.chosenOption ? `: ${event.chosenOption}` : \"\"}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\":\n\t\t\t\tthis.breakLine();\n\t\t\t\tthis.lines.push(\n\t\t\t\t\tevent.status === \"error\"\n\t\t\t\t\t\t? theme.fg(\"error\", `✗ task ${event.taskId ?? \"?\"} failed`)\n\t\t\t\t\t\t: theme.fg(\"success\", `✓ task ${event.taskId ?? \"?\"} done`),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Buffered logical line count (completed lines only). Exposed for tests. */\n\tbufferedLineCount(): number {\n\t\treturn this.lines.length;\n\t}\n\n\trender(width: number): string[] {\n\t\tconst inner = Math.max(1, width);\n\n\t\t// Header: role identity left, key hints right. An open gate owns the\n\t\t// keyboard and renders its own hints, so the panel's would lie.\n\t\tconst titlePlain = `◉ ${this.role} — attached`;\n\t\tconst title =\n\t\t\ttheme.fg(\"accent\", \"◉ \") + theme.bold(theme.fg(\"accent\", this.role)) + theme.fg(\"muted\", \" — attached\");\n\t\tconst hintsPlain = this.approval ? \"\" : \"n nudge · q detach\";\n\t\tconst hints = theme.fg(\"dim\", hintsPlain);\n\t\tlet header: string;\n\t\tif (visibleWidth(titlePlain) + 2 + visibleWidth(hintsPlain) <= inner) {\n\t\t\theader = title + \" \".repeat(inner - visibleWidth(titlePlain) - visibleWidth(hintsPlain)) + hints;\n\t\t} else {\n\t\t\theader = truncateToWidth(title, inner, \"…\");\n\t\t}\n\t\tconst rule = theme.fg(\"borderMuted\", \"─\".repeat(inner));\n\n\t\t// Body: wrap each buffered line, then keep the newest rows that fit the\n\t\t// panel's height budget (the freshest output hugs the bottom, like a\n\t\t// terminal tail). Budget derives from the live terminal height so the\n\t\t// panel never asks the overlay compositor to clip it (clipping drops the\n\t\t// bottom — exactly the rows we care about).\n\t\tconst rows = this.ui?.terminal.rows ?? 24;\n\t\tconst bodyBudget = Math.max(5, Math.floor(rows * 0.6) - 3);\n\n\t\t// An open gate takes its rows out of the stream's budget: the freshest\n\t\t// output stays visible above the question for context.\n\t\tlet approvalLines: string[] = [];\n\t\tif (this.approval) {\n\t\t\tthis.approval.component.focused = this.focused;\n\t\t\tapprovalLines = this.approval.component.render(inner);\n\t\t}\n\n\t\tconst wrapped: string[] = [];\n\t\tfor (const line of this.lines.toArray()) {\n\t\t\tif (line.length === 0) {\n\t\t\t\twrapped.push(\"\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\twrapped.push(...wrapTextWithAnsi(line, inner));\n\t\t}\n\t\tif (this.partial.length > 0) {\n\t\t\twrapped.push(...wrapTextWithAnsi(this.styledPartial(), inner));\n\t\t}\n\t\tconst keep = Math.max(0, bodyBudget - approvalLines.length);\n\t\tconst body = keep > 0 ? wrapped.slice(-keep) : [];\n\t\tif (body.length === 0 && approvalLines.length === 0) {\n\t\t\tbody.push(theme.fg(\"dim\", \"waiting for events…\"));\n\t\t}\n\n\t\t// The gate brings its own accent rules, so it closes the panel itself.\n\t\tif (approvalLines.length > 0) return [header, rule, ...body, ...approvalLines];\n\t\treturn [header, rule, ...body, rule];\n\t}\n}\n"]}
|
|
@@ -11,9 +11,16 @@
|
|
|
11
11
|
* The panel filters the team connection's single shared /events subscription —
|
|
12
12
|
* it never opens its own SSE connection — and unsubscribes on dispose(), so
|
|
13
13
|
* attach/detach cycles leave no leaked subscribers.
|
|
14
|
+
*
|
|
15
|
+
* Approval gates: task_* lifecycle events render as stream lines, and when the
|
|
16
|
+
* attached role pauses, presentApproval() embeds the AskOptions pane right
|
|
17
|
+
* where the stream stopped — pick an option (or type a free-form answer) and
|
|
18
|
+
* the caller answers the server; the stream then carries on under a
|
|
19
|
+
* "✓ answered: …" stamp.
|
|
14
20
|
*/
|
|
15
21
|
import { getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@kolisachint/hoocode-tui";
|
|
16
22
|
import { theme } from "../theme/theme.js";
|
|
23
|
+
import { AskOptionsComponent } from "./ask-options.js";
|
|
17
24
|
/** Fixed-capacity FIFO over a circular array: push evicts the oldest entry. */
|
|
18
25
|
export class RingBuffer {
|
|
19
26
|
capacity;
|
|
@@ -61,6 +68,8 @@ export class TeamAttachPanelComponent {
|
|
|
61
68
|
partial = "";
|
|
62
69
|
partialKind = "text";
|
|
63
70
|
unsubscribe;
|
|
71
|
+
/** Gate currently embedded in the panel; input is delegated to it. */
|
|
72
|
+
approval;
|
|
64
73
|
constructor(role, connection, callbacks, ui, bufferLines = DEFAULT_BUFFER_LINES) {
|
|
65
74
|
this.role = role;
|
|
66
75
|
this.callbacks = callbacks;
|
|
@@ -74,15 +83,67 @@ export class TeamAttachPanelComponent {
|
|
|
74
83
|
this.ui?.requestRender();
|
|
75
84
|
});
|
|
76
85
|
}
|
|
77
|
-
/** Detach from the shared event stream. Idempotent. */
|
|
86
|
+
/** Detach from the shared event stream; settles any open gate as skipped. Idempotent. */
|
|
78
87
|
dispose() {
|
|
79
88
|
this.unsubscribe?.();
|
|
80
89
|
this.unsubscribe = undefined;
|
|
90
|
+
this.approval?.settle(undefined);
|
|
81
91
|
}
|
|
82
92
|
invalidate() {
|
|
83
93
|
// No cached rendering state.
|
|
84
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Embed one approval gate in the panel (the attached role paused). Resolves
|
|
97
|
+
* with the chosen or free-form answer; undefined when skipped (esc), when
|
|
98
|
+
* the signal aborts (answered elsewhere), or when the panel is disposed.
|
|
99
|
+
* Answering the server is the caller's job — on an answer the panel just
|
|
100
|
+
* stamps "✓ answered: …" into the stream.
|
|
101
|
+
*/
|
|
102
|
+
presentApproval(approval, signal) {
|
|
103
|
+
return new Promise((resolve) => {
|
|
104
|
+
if (signal.aborted || this.unsubscribe === undefined) {
|
|
105
|
+
resolve(undefined);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
// The coordinator shows one gate at a time; a stray second call
|
|
109
|
+
// settles the first as skipped instead of stacking panes.
|
|
110
|
+
this.approval?.settle(undefined);
|
|
111
|
+
let settled = false;
|
|
112
|
+
const settle = (answer) => {
|
|
113
|
+
if (settled)
|
|
114
|
+
return;
|
|
115
|
+
settled = true;
|
|
116
|
+
signal.removeEventListener("abort", onAbort);
|
|
117
|
+
this.approval = undefined;
|
|
118
|
+
if (answer !== undefined) {
|
|
119
|
+
this.breakLine();
|
|
120
|
+
this.lines.push(theme.fg("success", ` ✓ answered: ${answer}`));
|
|
121
|
+
}
|
|
122
|
+
this.ui?.requestRender();
|
|
123
|
+
resolve(answer);
|
|
124
|
+
};
|
|
125
|
+
const onAbort = () => settle(undefined);
|
|
126
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
127
|
+
const question = {
|
|
128
|
+
question: approval.question,
|
|
129
|
+
short: approval.taskId,
|
|
130
|
+
detail: `team task "${approval.taskId}" is paused until answered`,
|
|
131
|
+
options: approval.options.map((label) => ({ label })),
|
|
132
|
+
allowCustom: true,
|
|
133
|
+
};
|
|
134
|
+
const component = new AskOptionsComponent([question], (answers) => settle(answers[0]), () => settle(undefined));
|
|
135
|
+
component.focused = this.focused;
|
|
136
|
+
this.approval = { component, settle };
|
|
137
|
+
this.ui?.requestRender();
|
|
138
|
+
});
|
|
139
|
+
}
|
|
85
140
|
handleInput(data) {
|
|
141
|
+
// An open gate owns the keyboard: q/n must type into the custom row, not
|
|
142
|
+
// detach or nudge. esc skips the gate (AskOptions cancel), not the panel.
|
|
143
|
+
if (this.approval) {
|
|
144
|
+
this.approval.component.handleInput(data);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
86
147
|
if (matchesKey(data, "q") || getKeybindings().matches(data, "tui.select.cancel")) {
|
|
87
148
|
this.callbacks.onDetach();
|
|
88
149
|
return;
|
|
@@ -173,6 +234,24 @@ export class TeamAttachPanelComponent {
|
|
|
173
234
|
this.breakLine();
|
|
174
235
|
this.lines.push(theme.fg("accent", `◉ ${event.role} idle`));
|
|
175
236
|
break;
|
|
237
|
+
case "task_started":
|
|
238
|
+
this.breakLine();
|
|
239
|
+
this.lines.push(theme.fg("accent", `◉ task ${event.taskId ?? "?"} started`));
|
|
240
|
+
break;
|
|
241
|
+
case "task_paused":
|
|
242
|
+
this.breakLine();
|
|
243
|
+
this.lines.push(theme.fg("warning", `⏸ awaiting approval: ${event.question ?? "?"}`));
|
|
244
|
+
break;
|
|
245
|
+
case "task_resumed":
|
|
246
|
+
this.breakLine();
|
|
247
|
+
this.lines.push(theme.fg("accent", `▶ task ${event.taskId ?? "?"} resumed${event.chosenOption ? `: ${event.chosenOption}` : ""}`));
|
|
248
|
+
break;
|
|
249
|
+
case "task_finished":
|
|
250
|
+
this.breakLine();
|
|
251
|
+
this.lines.push(event.status === "error"
|
|
252
|
+
? theme.fg("error", `✗ task ${event.taskId ?? "?"} failed`)
|
|
253
|
+
: theme.fg("success", `✓ task ${event.taskId ?? "?"} done`));
|
|
254
|
+
break;
|
|
176
255
|
}
|
|
177
256
|
}
|
|
178
257
|
/** Buffered logical line count (completed lines only). Exposed for tests. */
|
|
@@ -181,10 +260,11 @@ export class TeamAttachPanelComponent {
|
|
|
181
260
|
}
|
|
182
261
|
render(width) {
|
|
183
262
|
const inner = Math.max(1, width);
|
|
184
|
-
// Header: role identity left, key hints right.
|
|
263
|
+
// Header: role identity left, key hints right. An open gate owns the
|
|
264
|
+
// keyboard and renders its own hints, so the panel's would lie.
|
|
185
265
|
const titlePlain = `◉ ${this.role} — attached`;
|
|
186
266
|
const title = theme.fg("accent", "◉ ") + theme.bold(theme.fg("accent", this.role)) + theme.fg("muted", " — attached");
|
|
187
|
-
const hintsPlain = "n nudge · q detach";
|
|
267
|
+
const hintsPlain = this.approval ? "" : "n nudge · q detach";
|
|
188
268
|
const hints = theme.fg("dim", hintsPlain);
|
|
189
269
|
let header;
|
|
190
270
|
if (visibleWidth(titlePlain) + 2 + visibleWidth(hintsPlain) <= inner) {
|
|
@@ -201,6 +281,13 @@ export class TeamAttachPanelComponent {
|
|
|
201
281
|
// bottom — exactly the rows we care about).
|
|
202
282
|
const rows = this.ui?.terminal.rows ?? 24;
|
|
203
283
|
const bodyBudget = Math.max(5, Math.floor(rows * 0.6) - 3);
|
|
284
|
+
// An open gate takes its rows out of the stream's budget: the freshest
|
|
285
|
+
// output stays visible above the question for context.
|
|
286
|
+
let approvalLines = [];
|
|
287
|
+
if (this.approval) {
|
|
288
|
+
this.approval.component.focused = this.focused;
|
|
289
|
+
approvalLines = this.approval.component.render(inner);
|
|
290
|
+
}
|
|
204
291
|
const wrapped = [];
|
|
205
292
|
for (const line of this.lines.toArray()) {
|
|
206
293
|
if (line.length === 0) {
|
|
@@ -212,10 +299,14 @@ export class TeamAttachPanelComponent {
|
|
|
212
299
|
if (this.partial.length > 0) {
|
|
213
300
|
wrapped.push(...wrapTextWithAnsi(this.styledPartial(), inner));
|
|
214
301
|
}
|
|
215
|
-
const
|
|
216
|
-
|
|
302
|
+
const keep = Math.max(0, bodyBudget - approvalLines.length);
|
|
303
|
+
const body = keep > 0 ? wrapped.slice(-keep) : [];
|
|
304
|
+
if (body.length === 0 && approvalLines.length === 0) {
|
|
217
305
|
body.push(theme.fg("dim", "waiting for events…"));
|
|
218
306
|
}
|
|
307
|
+
// The gate brings its own accent rules, so it closes the panel itself.
|
|
308
|
+
if (approvalLines.length > 0)
|
|
309
|
+
return [header, rule, ...body, ...approvalLines];
|
|
219
310
|
return [header, rule, ...body, rule];
|
|
220
311
|
}
|
|
221
312
|
}
|