Skip to content
This repository was archived by the owner on Aug 17, 2026. It is now read-only.

Commit d4f302c

Browse files
committed
feat(grunt/tui): hivemind sidebar + clickable #N ticket refs (#12)
* feat(grunt/tui): hivemind sidebar + clickable #N ticket refs Refs hivemind anomalyco#229 + anomalyco#233 — make hivemind state ambient in the gruntcode TUI so Nik has operator awareness without window-switching to hivemind-ui. New 'hivemind' panel inside the existing right sidebar, between the session title block and the gruntcode footer. Polls hivemind-api on localhost:7890 every 2s for: - This peer's status (id, summary, wakeable flag, last_seen) - Live peers (other alive sessions, with summaries) - Unread inbox (DMs targeting this peer; client-side filtered, doesn't auto-markRead just from polling) - Board pulse (open / claimed / stale counts; high-prio + mine highlights) When hivemind-api is down, shows a 'api offline' placeholder. When the session isn't announced (no --peer-id), shows 'not announced yet'. Wake-log section deferred — hivemind-api doesn't yet expose /api/wake-log; filed as a follow-up. The other 4 sections cover the core ambient-awareness use case. New files: - packages/opencode/src/cli/cmd/tui/context/hivemind.tsx — solid-js context with poll loop + state store - packages/opencode/src/cli/cmd/tui/routes/session/hivemind-sections.tsx — the 4 rendered sections Wired: - app.tsx wraps the tree in HivemindProvider - sidebar.tsx renders <HivemindSections /> in the existing scrollbox In the assistant message TextPart, before passing markdown to the renderer, linkify hivemind ticket refs: 'anomalyco#229' becomes the markdown link '[anomalyco#229](http://localhost:5173/tasks/229)'. The markdown renderer styles links with theme.markdownLink (blue/cyan); terminals supporting OSC 8 (iTerm2, kitty) make the link clickable. Falls back to colored-but-non- clickable in older terminals. Regex `(^|[^\w/#])#(\d{1,5})\b` avoids false positives on hex colors (#fff has letters), already-linked refs ([anomalyco#229] won't match because prev char is '['), and longer-than-5-digit numbers. URL base configurable via HIVEMIND_UI_BASE env (defaults to http://localhost:5173 to match the running hivemind-ui dev server). bun typecheck clean. Local install via scripts/install-local.sh works; binary reports v1.15.10-grunt.7-5-g18407fd53-dirty-local. * feat(grunt/tui): bare gruntcode auto-lands in session route (sidebar visible from first frame) Refs hivemind anomalyco#229. The hivemind sidebar lives inside the session route — so bare `gruntcode` landing on the home/splash route HID the sidebar until the user submitted their first prompt. Nik's intent was 'open gruntcode tab and already be in that view, ready to type'. This effect auto-creates an empty session and navigates when: - No explicit --session / --continue / --fork - No --prompt (--prompt has its own auto-submit path on home) - Currently on home route - sync + model are ready (session.create requires agent + model) Escape hatch: OPENCODE_DISABLE_AUTO_SESSION=1 keeps legacy 'land on splash' behavior for users who prefer the home route.
1 parent 5071c64 commit d4f302c

5 files changed

Lines changed: 424 additions & 14 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/app.tsx‎

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { StartupLoading } from "@tui/component/startup-loading"
3333
import { SyncProvider, useSync } from "@tui/context/sync"
3434
import { SyncProviderV2 } from "@tui/context/sync-v2"
3535
import { LocalProvider, useLocal } from "@tui/context/local"
36+
import { HivemindProvider } from "@tui/context/hivemind"
3637
import { DialogModel } from "@tui/component/dialog-model"
3738
import { useConnected } from "@tui/component/use-connected"
3839
import { DialogMcp } from "@tui/component/dialog-mcp"
@@ -258,19 +259,21 @@ async function mountTui(input: TuiInput & { keymap: ReturnType<typeof createDefa
258259
<SyncProviderV2>
259260
<ThemeProvider mode={mode}>
260261
<LocalProvider>
261-
<PromptStashProvider>
262-
<DialogProvider>
263-
<FrecencyProvider>
264-
<PromptHistoryProvider>
265-
<PromptRefProvider>
266-
<EditorContextProvider>
267-
<App onSnapshot={input.onSnapshot} />
268-
</EditorContextProvider>
269-
</PromptRefProvider>
270-
</PromptHistoryProvider>
271-
</FrecencyProvider>
272-
</DialogProvider>
273-
</PromptStashProvider>
262+
<HivemindProvider>
263+
<PromptStashProvider>
264+
<DialogProvider>
265+
<FrecencyProvider>
266+
<PromptHistoryProvider>
267+
<PromptRefProvider>
268+
<EditorContextProvider>
269+
<App onSnapshot={input.onSnapshot} />
270+
</EditorContextProvider>
271+
</PromptRefProvider>
272+
</PromptHistoryProvider>
273+
</FrecencyProvider>
274+
</DialogProvider>
275+
</PromptStashProvider>
276+
</HivemindProvider>
274277
</LocalProvider>
275278
</ThemeProvider>
276279
</SyncProviderV2>
@@ -523,6 +526,52 @@ function App(props: { onSnapshot?: () => Promise<string[]> }) {
523526
}
524527
})
525528

529+
// grunt-it: bare `gruntcode` should land directly in the session view so the
530+
// hivemind sidebar is visible from the first frame, ready for input. Without this,
531+
// the user sees the splash/home route until they submit the first prompt — which
532+
// hides the sidebar (the sidebar lives inside the session route).
533+
//
534+
// We auto-create an empty session and navigate when ALL of these hold:
535+
// - No explicit --session / --continue / --fork (those have their own navigate paths)
536+
// - No --prompt (--prompt with no session would land in home + auto-submit; let it)
537+
// - Currently on home route (not already navigated elsewhere)
538+
// - sync + model are ready (session.create needs an agent + model)
539+
//
540+
// Set OPENCODE_DISABLE_AUTO_SESSION=1 to keep the legacy "land on splash" behavior.
541+
let autoCreated = false
542+
createEffect(() => {
543+
if (autoCreated) return
544+
if (process.env["OPENCODE_DISABLE_AUTO_SESSION"]) return
545+
if (args.sessionID || args.continue || args.fork || args.prompt) return
546+
if (route.data.type !== "home") return
547+
if (!sync.ready || !local.model.ready) return
548+
const agent = local.agent.current()
549+
const model = local.model.current()
550+
const variant = local.model.variant.current()
551+
if (!agent || !model) return
552+
autoCreated = true
553+
void sdk.client.session
554+
.create({
555+
agent: agent.name,
556+
model: {
557+
providerID: model.providerID,
558+
id: model.modelID,
559+
variant,
560+
},
561+
})
562+
.then((result) => {
563+
if (result.data?.id) {
564+
route.navigate({ type: "session", sessionID: result.data.id })
565+
} else {
566+
// Non-fatal: stay on home, user can submit manually + that path will create the session.
567+
autoCreated = false
568+
}
569+
})
570+
.catch(() => {
571+
autoCreated = false
572+
})
573+
})
574+
526575
// Handle --session with --fork: wait for sync to be fully complete before forking
527576
// (session list loads in non-blocking phase for --session, so we must wait for "complete"
528577
// to avoid a race where reconcile overwrites the newly forked session)
Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
// grunt-it: hivemind-state context for the TUI sidebar (#229).
2+
//
3+
// Polls hivemind-api at localhost:7890 every N seconds. Falls back to a "hivemind-api offline"
4+
// state when the API isn't reachable (api is auto-started via launchd but may be down during dev).
5+
//
6+
// We chose polling over SSE for v1 because:
7+
// 1. SSE in a long-lived TUI process needs reconnect-on-error logic + heartbeat handling
8+
// 2. The per-turn read cadence of hivemind is fine with a 2s poll — agents aren't watching
9+
// realtime updates between turns anyway; the panel is for ambient awareness, not live alerts
10+
// 3. Polling has zero state to recover from on api restart
11+
//
12+
// If we need sub-second updates later, swap the polling for an EventSource subscription to
13+
// /api/events (same wire format).
14+
15+
import { createSimpleContext } from "./helper"
16+
import { createSignal, onCleanup, onMount } from "solid-js"
17+
import { createStore } from "solid-js/store"
18+
import { getPeerID } from "@opencode-ai/core/util/opencode-process"
19+
20+
const DEFAULT_API = "http://127.0.0.1:7890"
21+
const POLL_INTERVAL_MS = 2000
22+
23+
export type Peer = {
24+
id: string
25+
engine: string
26+
cwd?: string | null
27+
repo?: string | null
28+
summary?: string | null
29+
http_port?: number | null
30+
session_id?: string | null
31+
last_seen_at: string
32+
stale: boolean
33+
}
34+
35+
export type Task = {
36+
id: number
37+
title: string
38+
scope?: string | null
39+
zone?: string | null
40+
priority: "high" | "normal" | "low"
41+
status: "open" | "claimed" | "done" | "cancelled"
42+
owner?: string | null
43+
stale?: boolean
44+
}
45+
46+
export type Message = {
47+
id: number
48+
from_peer: string
49+
to_peer: string
50+
subject?: string | null
51+
body: string
52+
sent_at: string
53+
read_at?: string | null
54+
}
55+
56+
export type WakeEvent = {
57+
id: number
58+
waker_peer_id: string
59+
waked_peer_id: string
60+
trigger_kind: string
61+
trigger_payload?: string | null
62+
waked_at: string
63+
http_status?: number | null
64+
error_message?: string | null
65+
}
66+
67+
type State = {
68+
/** http://127.0.0.1:7890 by default; configurable via opencode.json tui.hivemindSidebar.apiBase */
69+
apiBase: string
70+
/** API liveness — flips false when a fetch fails; flips back true on success. */
71+
apiOnline: boolean
72+
/** Last fetch timestamp (ms epoch) so the UI can show "stale by Ns" if poll is hung. */
73+
lastFetchAt: number
74+
/** This peer's own row (looked up from /api/peers/<self-id>). null if not announced yet. */
75+
self: Peer | null
76+
/** Other alive peers. */
77+
peers: Peer[]
78+
/** Unread DMs for self (newest first). */
79+
inbox: Message[]
80+
/** Recent wakes targeting self (newest first, capped). */
81+
wakes: WakeEvent[]
82+
/** Board pulse — minimal aggregate counts. */
83+
board: {
84+
open: number
85+
claimed: number
86+
done24h: number
87+
stale: number
88+
/** Open tickets where the current peer is the owner. */
89+
mineClaimedCount: number
90+
/** High-priority opens in YOUR zones (zones the self peer has worked recently). */
91+
highPrioMine: number
92+
}
93+
}
94+
95+
const emptyBoard = (): State["board"] => ({
96+
open: 0,
97+
claimed: 0,
98+
done24h: 0,
99+
stale: 0,
100+
mineClaimedCount: 0,
101+
highPrioMine: 0,
102+
})
103+
104+
export const { use: useHivemind, provider: HivemindProvider } = createSimpleContext({
105+
name: "Hivemind",
106+
init: () => {
107+
const apiBase = process.env.HIVEMIND_API_BASE ?? DEFAULT_API
108+
const [state, setState] = createStore<State>({
109+
apiBase,
110+
apiOnline: false,
111+
lastFetchAt: 0,
112+
self: null,
113+
peers: [],
114+
inbox: [],
115+
wakes: [],
116+
board: emptyBoard(),
117+
})
118+
119+
const peerId = getPeerID()
120+
let timer: ReturnType<typeof setInterval> | undefined
121+
122+
async function fetchJson<T>(path: string): Promise<T | null> {
123+
try {
124+
const controller = new AbortController()
125+
const t = setTimeout(() => controller.abort(), 1500)
126+
const res = await fetch(`${apiBase}${path}`, { signal: controller.signal })
127+
clearTimeout(t)
128+
if (!res.ok) return null
129+
return (await res.json()) as T
130+
} catch {
131+
return null
132+
}
133+
}
134+
135+
async function poll() {
136+
// peers — /api/peers returns { peers: [...] }
137+
const peersWrap = await fetchJson<{ peers: Peer[] }>("/api/peers")
138+
if (peersWrap === null) {
139+
setState("apiOnline", false)
140+
setState("lastFetchAt", Date.now())
141+
return
142+
}
143+
setState("apiOnline", true)
144+
setState("lastFetchAt", Date.now())
145+
146+
const peers = peersWrap.peers ?? []
147+
const self = peerId ? peers.find((p) => p.id === peerId) ?? null : null
148+
setState("self", self)
149+
setState(
150+
"peers",
151+
peers.filter((p) => !p.stale && p.id !== peerId),
152+
)
153+
154+
// inbox + tasks — only fetch when peerId is known (otherwise these are meaningless).
155+
// wakes deferred to a future iteration — hivemind-api doesn't expose wake_log yet.
156+
// Filed as follow-up; until then, the sidebar just shows the other 4 sections.
157+
if (peerId) {
158+
// includeRead=true so we don't accidentally mark all unread messages read just by polling.
159+
// markRead=false explicit-flag for safety. We filter unread client-side.
160+
const [inboxWrap, tasksWrap] = await Promise.all([
161+
fetchJson<{ messages: Message[] }>(
162+
`/api/messages/inbox?peerId=${encodeURIComponent(peerId)}&includeRead=true&markRead=false&limit=20`,
163+
),
164+
fetchJson<{ tasks: Task[] }>("/api/tasks"),
165+
])
166+
if (inboxWrap) {
167+
const unread = (inboxWrap.messages ?? []).filter((m) => !m.read_at).slice(0, 10)
168+
setState("inbox", unread)
169+
}
170+
if (tasksWrap) {
171+
const tasks = tasksWrap.tasks ?? []
172+
const open = tasks.filter((t) => t.status === "open")
173+
const claimed = tasks.filter((t) => t.status === "claimed")
174+
const stale = tasks.filter((t) => t.stale).length
175+
const mineClaimed = claimed.filter((t) => t.owner === peerId).length
176+
// High-prio "in my area" — heuristic: zone of the ticket matches a zone the self peer
177+
// has worked recently. Without an explicit "my zones" affordance yet, just count all
178+
// high-priority opens; future iteration can refine.
179+
const highPrioMine = open.filter((t) => t.priority === "high").length
180+
setState("board", {
181+
open: open.length,
182+
claimed: claimed.length,
183+
done24h: 0,
184+
stale,
185+
mineClaimedCount: mineClaimed,
186+
highPrioMine,
187+
})
188+
}
189+
}
190+
}
191+
192+
onMount(() => {
193+
// Fire once immediately so the panel populates without a delay; then poll on interval.
194+
poll().catch(() => {})
195+
timer = setInterval(() => poll().catch(() => {}), POLL_INTERVAL_MS)
196+
})
197+
198+
onCleanup(() => {
199+
if (timer) clearInterval(timer)
200+
})
201+
202+
/** Manual refresh hook for UI actions that want fresh data NOW. */
203+
function refresh() {
204+
poll().catch(() => {})
205+
}
206+
207+
return {
208+
get state() {
209+
return state
210+
},
211+
refresh,
212+
}
213+
},
214+
})

0 commit comments

Comments
 (0)