@linxiraos/pi-messenger 1.1.0 → 1.3.0

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
package/overlay.ts CHANGED
@@ -1,830 +1,872 @@
1
- /**
2
- * Pi Messenger - Chat Overlay Component
3
- */
4
-
5
- import type { Component, Focusable, TUI } from "@earendil-works/pi-tui";
6
- import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
- import type { Theme } from "@earendil-works/pi-coding-agent";
8
- import {
9
- extractFolder,
10
- formatDuration,
11
- type MessengerState,
12
- type Dirs,
13
- } from "./lib.ts";
14
- import * as crewStore from "./crew/store.ts";
15
- import { adjustConcurrency, autonomousState, isAutonomousForCwd, isPlanningForCwd, planningState } from "./crew/state.ts";
16
- import { loadCrewConfig, cycleCoordinationLevel, setCoordinationOverride } from "./crew/utils/config.ts";
17
- import { readFeedEvents, type FeedEvent, type FeedEventType } from "./feed.ts";
18
- import type { Task } from "./crew/types.ts";
19
- import {
20
- renderStatusBar,
21
- renderWorkersSection,
22
- renderTaskList,
23
- renderTaskSummary,
24
- renderFeedSection,
25
- renderAgentsRow,
26
- renderLegend,
27
- renderEmptyState,
28
- renderPlanningState,
29
- renderDetailView,
30
- navigateTask,
31
- } from "./overlay-render.ts";
32
- import {
33
- createCrewViewState,
34
- handleConfirmInput,
35
- handleBlockReasonInput,
36
- handleMessageInput,
37
- handleRevisePromptInput,
38
- handleCrewKeyBinding,
39
- setNotification,
40
- type CrewViewState,
41
- } from "./overlay-actions.ts";
42
- import { getLiveWorkers, hasLiveWorkers, onLiveWorkersChanged } from "./crew/live-progress.ts";
43
- import { loadConfig } from "./config.ts";
44
- import { discoverCrewAgents } from "./crew/utils/discover.ts";
45
- import { spawnSingleWorker, spawnWorkersForReadyTasks } from "./crew/spawn.ts";
46
- import * as teamStore from "./crew/team/store.ts";
47
- import { spawnLobbyWorker, removeLobbyWorkerByIndex, cleanupUnassignedAliveFiles } from "./crew/lobby.ts";
48
-
49
- export interface OverlayCallbacks {
50
- onBackground?: (snapshot: string) => void;
51
- }
52
-
53
- export class MessengerOverlay implements Component, Focusable {
54
- get width(): number {
55
- return Math.min(100, Math.max(40, process.stdout.columns ?? 90));
56
- }
57
- focused = false;
58
-
59
- private crewViewState: CrewViewState = createCrewViewState();
60
- private cwd: string;
61
- private stuckThresholdMs: number;
62
- private progressTimer: ReturnType<typeof setInterval> | null = null;
63
- private planningTimer: ReturnType<typeof setInterval> | null = null;
64
- private progressUnsubscribe: (() => void) | null = null;
65
- private sawIncompleteWork = false;
66
- private completionTimer: ReturnType<typeof setTimeout> | null = null;
67
- private completionDismissed = false;
68
- private wasPlanning: boolean;
69
- private prevInProgressCount = 0;
70
-
71
- constructor(
72
- private tui: TUI,
73
- private theme: Theme,
74
- private state: MessengerState,
75
- private dirs: Dirs,
76
- private done: (snapshot?: string) => void,
77
- private callbacks: OverlayCallbacks,
78
- cwd: string,
79
- ) {
80
- this.cwd = cwd;
81
- const cfg = loadConfig(this.cwd);
82
- this.stuckThresholdMs = cfg.stuckThreshold * 1000;
83
-
84
- for (const key of this.state.unreadCounts.keys()) {
85
- this.state.unreadCounts.set(key, 0);
86
- }
87
-
88
- this.wasPlanning = isPlanningForCwd(this.cwd);
89
-
90
- this.progressUnsubscribe = onLiveWorkersChanged(() => {
91
- this.syncCrewRefreshTimers();
92
- this.tui.requestRender();
93
- });
94
-
95
- this.syncCrewRefreshTimers();
96
- }
97
-
98
- private hasPlan(): boolean {
99
- return crewStore.hasPlan(this.cwd);
100
- }
101
-
102
- private handleTaskStart(task: Task): void {
103
- const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
104
- if (config.dependencies !== "advisory") {
105
- const unmet = task.depends_on.filter(depId => crewStore.getTask(this.cwd, depId)?.status !== "done");
106
- if (unmet.length > 0) {
107
- setNotification(this.crewViewState, this.tui, false, `Unmet deps: ${unmet.join(", ")}`);
108
- this.tui.requestRender();
109
- return;
110
- }
111
- }
112
- if (teamStore.taskNeedsApproval(task)) {
113
- const message = teamStore.taskNeedsRevision(task) ? `${task.id} needs revision` : `${task.id} needs lead approval`;
114
- setNotification(this.crewViewState, this.tui, false, message);
115
- this.tui.requestRender();
116
- return;
117
- }
118
-
119
- const worker = spawnSingleWorker(this.cwd, task.id, this.state.model);
120
- if (worker) {
121
- setNotification(this.crewViewState, this.tui, true, `${worker.name} → ${task.id}`);
122
- } else {
123
- setNotification(this.crewViewState, this.tui, false, `Failed to spawn worker for ${task.id}`);
124
- }
125
- this.tui.requestRender();
126
- }
127
-
128
- private spawnWorkerForReadyTask(task: Task, newConcurrency: number): void {
129
- const worker = spawnSingleWorker(this.cwd, task.id, this.state.model);
130
- if (!worker) {
131
- const message = teamStore.taskNeedsRevision(task)
132
- ? `${task.id} needs revision`
133
- : teamStore.taskNeedsApproval(task)
134
- ? `${task.id} needs lead approval`
135
- : `Failed to spawn worker for ${task.id}`;
136
- setNotification(this.crewViewState, this.tui, false, message);
137
- this.tui.requestRender();
138
- return;
139
- }
140
-
141
- setNotification(this.crewViewState, this.tui, true, `${worker.name} → ${task.id} (${newConcurrency}w)`);
142
- this.tui.requestRender();
143
- }
144
-
145
- private isPlanningActiveForCurrentProject(): boolean {
146
- return isPlanningForCwd(this.cwd);
147
- }
148
-
149
- private checkAutoSpawnOnPlanComplete(planning: boolean, tasks: Task[]): void {
150
- const wasPlanningBefore = this.wasPlanning;
151
- this.wasPlanning = planning;
152
-
153
- if (!wasPlanningBefore || planning) return;
154
-
155
- const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
156
- const readyTasks = crewStore.getReadyTasksFrom(tasks, { advisory: config.dependencies === "advisory" });
157
- const startableTasks = readyTasks.filter(t => !teamStore.taskNeedsApproval(t));
158
- if (startableTasks.length > 0) {
159
- const target = Math.min(startableTasks.length, autonomousState.concurrency);
160
- const { assigned } = spawnWorkersForReadyTasks(this.cwd, target, this.state.model);
161
- if (assigned > 0) {
162
- setNotification(this.crewViewState, this.tui, true, `Plan ready — ${assigned} worker${assigned > 1 ? "s" : ""} started`);
163
- this.tui.requestRender();
164
- }
165
- } else if (readyTasks.length > 0) {
166
- const rejected = readyTasks.filter(teamStore.taskNeedsRevision);
167
- const pending = readyTasks.filter(teamStore.taskPendingApproval);
168
- const message = rejected.length > 0
169
- ? `Plan ready — ${rejected.length} task${rejected.length > 1 ? "s" : ""} need revision`
170
- : `Plan ready — ${pending.length} task${pending.length > 1 ? "s" : ""} need lead approval`;
171
- setNotification(this.crewViewState, this.tui, false, message);
172
- this.tui.requestRender();
173
- }
174
-
175
- cleanupUnassignedAliveFiles(this.cwd);
176
- }
177
-
178
- private checkAutoRefillWorkers(tasks: Task[], hasPlan: boolean): void {
179
- const inProgressCount = tasks.filter(t => t.status === "in_progress").length;
180
- const prev = this.prevInProgressCount;
181
- this.prevInProgressCount = inProgressCount;
182
-
183
- if (inProgressCount >= prev || inProgressCount >= autonomousState.concurrency || !hasPlan) return;
184
-
185
- const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
186
- const readyTasks = crewStore.getReadyTasksFrom(tasks, { advisory: config.dependencies === "advisory" });
187
- const startableTasks = readyTasks.filter(t => !teamStore.taskNeedsApproval(t));
188
- if (startableTasks.length === 0) return;
189
-
190
- const slots = autonomousState.concurrency - inProgressCount;
191
- const target = Math.min(startableTasks.length, slots);
192
- if (target <= 0) return;
193
-
194
- const { assigned } = spawnWorkersForReadyTasks(this.cwd, target, this.state.model);
195
- if (assigned > 0) {
196
- setNotification(this.crewViewState, this.tui, true, `${assigned} worker${assigned > 1 ? "s" : ""} → ready tasks`);
197
- this.tui.requestRender();
198
- }
199
- }
200
-
201
- private syncCrewRefreshTimers(): void {
202
- if (hasLiveWorkers(this.cwd)) this.startProgressRefresh();
203
- else this.stopProgressRefresh();
204
-
205
- if (this.isPlanningActiveForCurrentProject()) this.startPlanningRefresh();
206
- else this.stopPlanningRefresh();
207
- }
208
-
209
- private startProgressRefresh(): void {
210
- if (this.progressTimer) return;
211
- this.progressTimer = setInterval(() => {
212
- if (hasLiveWorkers(this.cwd)) {
213
- this.tui.requestRender();
214
- } else {
215
- this.stopProgressRefresh();
216
- }
217
- }, 1000);
218
- }
219
-
220
- private stopProgressRefresh(): void {
221
- if (this.progressTimer) {
222
- clearInterval(this.progressTimer);
223
- this.progressTimer = null;
224
- }
225
- }
226
-
227
- private startPlanningRefresh(): void {
228
- if (this.planningTimer) return;
229
- this.planningTimer = setInterval(() => {
230
- if (this.isPlanningActiveForCurrentProject()) {
231
- this.tui.requestRender();
232
- } else {
233
- this.stopPlanningRefresh();
234
- }
235
- }, 15_000);
236
- }
237
-
238
- private stopPlanningRefresh(): void {
239
- if (this.planningTimer) {
240
- clearInterval(this.planningTimer);
241
- this.planningTimer = null;
242
- }
243
- }
244
-
245
- handleInput(data: string): void {
246
- this.cancelCompletionTimer();
247
-
248
- if (data === "\x14") {
249
- this.done(this.generateSnapshot());
250
- return;
251
- }
252
-
253
- if (data === "\x02") {
254
- this.callbacks.onBackground?.(this.generateSnapshot());
255
- return;
256
- }
257
-
258
- if (this.crewViewState.confirmAction) {
259
- handleConfirmInput(data, this.crewViewState, this.cwd, this.state.agentName, this.tui);
260
- return;
261
- }
262
-
263
- if (this.crewViewState.inputMode === "block-reason") {
264
- const tasks = crewStore.getTasks(this.cwd);
265
- const task = tasks[this.crewViewState.selectedTaskIndex];
266
- handleBlockReasonInput(data, this.crewViewState, this.cwd, task, this.state.agentName, this.tui);
267
- return;
268
- }
269
-
270
- if (this.crewViewState.inputMode === "message") {
271
- handleMessageInput(data, this.crewViewState, this.state, this.dirs, this.cwd, this.tui);
272
- return;
273
- }
274
-
275
- if (this.crewViewState.inputMode === "revise-prompt") {
276
- const tasks = crewStore.getTasks(this.cwd);
277
- const task = tasks[this.crewViewState.selectedTaskIndex];
278
- handleRevisePromptInput(data, this.crewViewState, this.cwd, task, this.state.agentName, this.tui);
279
- return;
280
- }
281
-
282
- if (matchesKey(data, "escape")) {
283
- if (this.crewViewState.mode === "detail") {
284
- this.crewViewState.mode = "list";
285
- this.tui.requestRender();
286
- } else {
287
- this.done();
288
- }
289
- return;
290
- }
291
-
292
- if (data === "+" || matchesKey(data, "=") || matchesKey(data, "shift+=") || matchesKey(data, "-")) {
293
- const delta = matchesKey(data, "-") ? -1 : 1;
294
- const crewDir = crewStore.getCrewDir(this.cwd);
295
- const config = loadCrewConfig(crewDir);
296
- const prev = autonomousState.concurrency;
297
- const next = adjustConcurrency(delta, config.concurrency.max);
298
- if (prev === next) {
299
- this.tui.requestRender();
300
- return;
301
- }
302
-
303
- if (next > prev) {
304
- const readyTasks = crewStore.getReadyTasks(this.cwd, { advisory: config.dependencies === "advisory" });
305
- if (readyTasks.length === 0) {
306
- const worker = spawnLobbyWorker(this.cwd, undefined, this.state.model);
307
- const label = worker ? `Lobby worker ${worker.name} spawned (${next}w)` : `Workers → ${next}`;
308
- setNotification(this.crewViewState, this.tui, true, label);
309
- } else {
310
- this.spawnWorkerForReadyTask(readyTasks[0], next);
311
- }
312
- } else {
313
- const killed = removeLobbyWorkerByIndex(this.cwd);
314
- const label = killed ? `Lobby worker removed (${next}w)` : `Workers: ${prev} → ${next}`;
315
- setNotification(this.crewViewState, this.tui, true, label);
316
- }
317
- this.tui.requestRender();
318
- return;
319
- }
320
-
321
- if (data === "@" || matchesKey(data, "m")) {
322
- if (isPlanningForCwd(this.cwd)) {
323
- setNotification(this.crewViewState, this.tui, false, "Chat unavailable during planning");
324
- this.tui.requestRender();
325
- return;
326
- }
327
- this.crewViewState.inputMode = "message";
328
- this.crewViewState.messageInput = data === "@" ? "@" : "";
329
- this.tui.requestRender();
330
- return;
331
- }
332
-
333
- if (matchesKey(data, "f")) {
334
- this.crewViewState.feedFocus = !this.crewViewState.feedFocus;
335
- this.tui.requestRender();
336
- return;
337
- }
338
-
339
- if (matchesKey(data, "v")) {
340
- const crewDir = crewStore.getCrewDir(this.cwd);
341
- const config = loadCrewConfig(crewDir);
342
- const next = cycleCoordinationLevel(config.coordination);
343
- setCoordinationOverride(next);
344
- setNotification(this.crewViewState, this.tui, true, `Coordination: ${next}`);
345
- this.tui.requestRender();
346
- return;
347
- }
348
-
349
- if (matchesKey(data, "c") && this.isPlanningActiveForCurrentProject()) {
350
- this.crewViewState.confirmAction = {
351
- type: "cancel-planning",
352
- taskId: "",
353
- label: "planning",
354
- };
355
- this.tui.requestRender();
356
- return;
357
- }
358
-
359
- const tasks = crewStore.getTasks(this.cwd);
360
- const task = tasks[this.crewViewState.selectedTaskIndex];
361
-
362
- if (matchesKey(data, "right")) {
363
- if (this.crewViewState.mode === "detail") {
364
- navigateTask(this.crewViewState, 1, tasks.length);
365
- this.crewViewState.detailScroll = 0;
366
- this.crewViewState.detailAutoScroll = true;
367
- this.tui.requestRender();
368
- }
369
- return;
370
- }
371
-
372
- if (matchesKey(data, "left")) {
373
- if (this.crewViewState.mode === "detail") {
374
- navigateTask(this.crewViewState, -1, tasks.length);
375
- this.crewViewState.detailScroll = 0;
376
- this.crewViewState.detailAutoScroll = true;
377
- this.tui.requestRender();
378
- }
379
- return;
380
- }
381
-
382
- if (matchesKey(data, "up")) {
383
- if (this.crewViewState.mode === "detail") {
384
- this.crewViewState.detailScroll = Math.max(0, this.crewViewState.detailScroll - 1);
385
- this.crewViewState.detailAutoScroll = false;
386
- } else {
387
- navigateTask(this.crewViewState, -1, tasks.length);
388
- }
389
- this.tui.requestRender();
390
- return;
391
- }
392
-
393
- if (matchesKey(data, "down")) {
394
- if (this.crewViewState.mode === "detail") {
395
- this.crewViewState.detailScroll++;
396
- this.crewViewState.detailAutoScroll = false;
397
- } else {
398
- navigateTask(this.crewViewState, 1, tasks.length);
399
- }
400
- this.tui.requestRender();
401
- return;
402
- }
403
-
404
- if (matchesKey(data, "home")) {
405
- this.crewViewState.selectedTaskIndex = 0;
406
- this.crewViewState.scrollOffset = 0;
407
- if (this.crewViewState.mode === "detail") {
408
- this.crewViewState.detailScroll = 0;
409
- this.crewViewState.detailAutoScroll = false;
410
- }
411
- this.tui.requestRender();
412
- return;
413
- }
414
-
415
- if (matchesKey(data, "end")) {
416
- this.crewViewState.selectedTaskIndex = Math.max(0, tasks.length - 1);
417
- if (this.crewViewState.mode === "detail") {
418
- this.crewViewState.detailScroll = 0;
419
- this.crewViewState.detailAutoScroll = true;
420
- }
421
- this.tui.requestRender();
422
- return;
423
- }
424
-
425
- if (matchesKey(data, "enter")) {
426
- if (task && this.crewViewState.mode !== "detail") {
427
- this.crewViewState.mode = "detail";
428
- this.crewViewState.detailScroll = 0;
429
- this.crewViewState.detailAutoScroll = true;
430
- this.tui.requestRender();
431
- }
432
- return;
433
- }
434
-
435
- if (this.crewViewState.mode === "detail") {
436
- if (matchesKey(data, "[")) {
437
- navigateTask(this.crewViewState, -1, tasks.length);
438
- this.crewViewState.detailScroll = 0;
439
- this.crewViewState.detailAutoScroll = true;
440
- this.tui.requestRender();
441
- return;
442
- }
443
- if (matchesKey(data, "]")) {
444
- navigateTask(this.crewViewState, 1, tasks.length);
445
- this.crewViewState.detailScroll = 0;
446
- this.crewViewState.detailAutoScroll = true;
447
- this.tui.requestRender();
448
- return;
449
- }
450
- }
451
-
452
- if (task) {
453
- if (matchesKey(data, "s") && task.status === "todo" && !task.milestone) {
454
- this.handleTaskStart(task);
455
- return;
456
- }
457
- handleCrewKeyBinding(data, task, this.crewViewState, this.cwd, this.state.agentName, this.tui);
458
- }
459
- }
460
-
461
- private snapshotIdleLabel(): string {
462
- const last = this.state.activity.lastActivityAt || this.state.sessionStartedAt;
463
- const ageMs = Math.max(0, Date.now() - new Date(last).getTime());
464
- return `idle ${formatDuration(ageMs)}`;
465
- }
466
-
467
- private formatTaskSnapshotLine(task: Task, liveTaskIds: Set<string>): string {
468
- if (task.status === "done") {
469
- return `${task.id} (${task.title})`;
470
- }
471
- if (task.status === "in_progress") {
472
- const parts = [task.title];
473
- if (task.assigned_to) parts.push(task.assigned_to);
474
- if (liveTaskIds.has(task.id)) parts.push("live");
475
- return `${task.id} (${parts.join(", ")})`;
476
- }
477
- if (task.status === "blocked") {
478
- const reason = task.blocked_reason ? ` — ${task.blocked_reason}` : "";
479
- return `${task.id} (${task.title}${reason})`;
480
- }
481
- if (task.depends_on.length > 0) {
482
- return `${task.id} (${task.title}, deps: ${task.depends_on.join(" ")})`;
483
- }
484
- return `${task.id} (${task.title})`;
485
- }
486
-
487
- private formatRecentFeedEvent(event: FeedEvent): string {
488
- const time = new Date(event.ts).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
489
- if (event.type === "task.done") return `${event.agent} completed ${event.target ?? "task"} (${time})`;
490
- if (event.type === "task.start") return `${event.agent} started ${event.target ?? "task"} (${time})`;
491
- if (event.type === "message") {
492
- const dir = event.target ? `→ ${event.target}: ` : "✦ ";
493
- return event.preview
494
- ? `${event.agent} ${dir}${event.preview} (${time})`
495
- : `${event.agent} ${dir.trim()} (${time})`;
496
- }
497
- if (event.target) return `${event.agent} ${event.type} ${event.target} (${time})`;
498
- return `${event.agent} ${event.type} (${time})`;
499
- }
500
-
501
- private generateSnapshot(): string {
502
- const plan = crewStore.getPlan(this.cwd);
503
- const tasks = crewStore.getTasks(this.cwd);
504
- const liveWorkers = getLiveWorkers(this.cwd);
505
-
506
- if (this.isPlanningActiveForCurrentProject() && tasks.length === 0) {
507
- const updated = planningState.updatedAt ? formatDuration(Math.max(0, Date.now() - new Date(planningState.updatedAt).getTime())) : "unknown";
508
- return [
509
- `Crew snapshot: planning in progress (pass ${planningState.pass}/${planningState.maxPasses}, ${planningState.phase}), ${autonomousState.concurrency}w concurrency`,
510
- "",
511
- `Planning: pass ${planningState.pass}/${planningState.maxPasses}, phase: ${planningState.phase}, updated ${updated} ago`,
512
- "",
513
- `Agents: You (${this.snapshotIdleLabel()})`,
514
- ].join("\n");
515
- }
516
-
517
- if (!plan) {
518
- const discovered = discoverCrewAgents(this.cwd);
519
- const configLine = discovered.length === 0
520
- ? "Config: no crew agents discovered"
521
- : `Config: ${discovered.map(agent => `${agent.name}${agent.model ? ` (${agent.model})` : ""}`).join(", ")}`;
522
-
523
- return [
524
- `Crew snapshot: no active plan, ${autonomousState.concurrency}w concurrency`,
525
- "",
526
- `Agents: You (${this.snapshotIdleLabel()})`,
527
- "",
528
- configLine,
529
- ].join("\n");
530
- }
531
-
532
- const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
533
- const readyTasks = crewStore.getReadyTasks(this.cwd, { advisory: config.dependencies === "advisory" });
534
- const readyIds = new Set(readyTasks.map(task => task.id));
535
- const liveTaskIds = new Set(Array.from(liveWorkers.keys()));
536
- const activeLines = Array.from(liveWorkers.values()).map(worker => {
537
- const activity = worker.progress.currentTool
538
- ? `${worker.progress.currentTool}${worker.progress.currentToolArgs ? ` ${worker.progress.currentToolArgs}` : ""}`
539
- : "thinking";
540
- return `${worker.taskId} (${worker.agent}, ${activity}, ${formatDuration(Date.now() - worker.startedAt)})`;
541
- });
542
-
543
- const doneTasks = tasks.filter(task => task.status === "done");
544
- const inProgressTasks = tasks.filter(task => task.status === "in_progress");
545
- const blockedTasks = tasks.filter(task => task.status === "blocked");
546
- const waitingTasks = tasks.filter(task => task.status === "todo" && !readyIds.has(task.id));
547
- const recentEvents = readFeedEvents(this.cwd, 2);
548
- const headerParts = [
549
- `Crew snapshot: ${plan.completed_count}/${plan.task_count} tasks done`,
550
- `${readyTasks.length} ready`,
551
- `${autonomousState.concurrency}w`,
552
- ];
553
- if (isAutonomousForCwd(this.cwd)) {
554
- headerParts.push(`autonomous wave ${autonomousState.waveNumber}`);
555
- }
556
-
557
- const lines = [
558
- headerParts.join(", "),
559
- "",
560
- `Active: ${activeLines.length > 0 ? activeLines.join(", ") : "none"}`,
561
- `Done: ${doneTasks.length > 0 ? doneTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
562
- `In progress: ${inProgressTasks.length > 0 ? inProgressTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
563
- `Ready: ${readyTasks.length > 0 ? readyTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
564
- `Blocked: ${blockedTasks.length > 0 ? blockedTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
565
- `Waiting: ${waitingTasks.length > 0 ? waitingTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
566
- ];
567
-
568
- if (recentEvents.length > 0) {
569
- lines.push("");
570
- lines.push(`Recent: ${recentEvents.map(event => this.formatRecentFeedEvent(event)).join(", ")}`);
571
- }
572
-
573
- return lines.join("\n");
574
- }
575
-
576
- render(_width: number): string[] {
577
- const w = this.width;
578
- const innerW = w - 2;
579
- const sectionW = innerW - 2;
580
- const border = (s: string) => this.theme.fg("dim", s);
581
- const pad = (s: string, len: number) => s + " ".repeat(Math.max(0, len - visibleWidth(s)));
582
- const sanitizeRowContent = (content: string) => content
583
- .replaceAll("\r", " ")
584
- .replaceAll("\n", " ")
585
- .replaceAll("\t", " ");
586
- const row = (content: string) => {
587
- const safe = truncateToWidth(sanitizeRowContent(content), sectionW);
588
- return border("│") + pad(" " + safe, innerW) + border("│");
589
- };
590
- const emptyRow = () => border("│") + " ".repeat(innerW) + border("│");
591
- const sectionSeparator = this.theme.fg("dim", "─".repeat(sectionW));
592
-
593
- const tasks = crewStore.getTasks(this.cwd);
594
- if (tasks.length === 0) {
595
- this.crewViewState.selectedTaskIndex = 0;
596
- if (this.crewViewState.mode === "detail") this.crewViewState.mode = "list";
597
- } else {
598
- this.crewViewState.selectedTaskIndex = Math.max(0, Math.min(this.crewViewState.selectedTaskIndex, tasks.length - 1));
599
- }
600
-
601
- const selectedTask = tasks[this.crewViewState.selectedTaskIndex] ?? null;
602
- const hasPlan = this.hasPlan();
603
- const planning = this.isPlanningActiveForCurrentProject();
604
- this.checkAutoSpawnOnPlanComplete(planning, tasks);
605
- this.checkAutoRefillWorkers(tasks, hasPlan);
606
-
607
- const lines: string[] = [];
608
- const titleContent = this.renderTitleContent();
609
- const titleText = ` ${titleContent} `;
610
- const titleLen = visibleWidth(titleContent) + 2;
611
- const borderLen = Math.max(0, innerW - titleLen);
612
- const leftBorder = Math.floor(borderLen / 2);
613
- const rightBorder = borderLen - leftBorder;
614
-
615
- lines.push(border("╭" + "─".repeat(leftBorder)) + titleText + border("─".repeat(rightBorder) + "╮"));
616
- lines.push(row(renderStatusBar(this.theme, this.cwd, sectionW, tasks)));
617
- lines.push(emptyRow());
618
-
619
- const chromeLines = 6;
620
- const termRows = process.stdout.rows ?? 24;
621
- const contentHeight = Math.max(8, termRows - chromeLines);
622
-
623
- const prevTs = this.crewViewState.lastSeenEventTs;
624
- const allEvents = readFeedEvents(this.cwd, 20);
625
- this.detectAndFlashEvents(allEvents, prevTs);
626
- this.checkCompletion(tasks, planning);
627
-
628
- let contentLines: string[];
629
- if (this.crewViewState.mode === "detail" && selectedTask) {
630
- contentLines = renderDetailView(this.cwd, selectedTask, sectionW, contentHeight, this.crewViewState);
631
- } else {
632
- const workersLimit = termRows <= 26 ? 2 : 5;
633
- const hasWorkers = hasLiveWorkers(this.cwd);
634
-
635
- let workerLines = renderWorkersSection(this.theme, this.cwd, sectionW, workersLimit);
636
- const agentsLine = renderAgentsRow(
637
- this.cwd,
638
- sectionW,
639
- this.state,
640
- this.dirs,
641
- this.stuckThresholdMs,
642
- new Map([[this.cwd, tasks]]),
643
- );
644
- const agentsHeight = 2;
645
- const workersHeight = () => workerLines.length > 0 ? workerLines.length + 1 : 0;
646
- const available = contentHeight - workersHeight() - agentsHeight;
647
-
648
- const isFeedFocus = this.crewViewState.feedFocus;
649
- let feedHeight: number;
650
- let mainHeight: number;
651
-
652
- if (!hasPlan && !planning) {
653
- feedHeight = Math.min(allEvents.length, Math.max(2, Math.floor(available * 0.4)));
654
- mainHeight = available - feedHeight - (feedHeight > 0 ? 1 : 0);
655
- } else if (isFeedFocus) {
656
- const summaryLines = 2;
657
- mainHeight = summaryLines;
658
- feedHeight = available - summaryLines - 1;
659
- } else if (hasWorkers) {
660
- feedHeight = Math.max(6, Math.floor(available * 0.7));
661
- mainHeight = available - feedHeight - 1;
662
- } else {
663
- feedHeight = Math.max(4, Math.floor(available * 0.6));
664
- mainHeight = available - feedHeight - 1;
665
- }
666
-
667
- feedHeight = Math.max(0, feedHeight);
668
- mainHeight = Math.max(2, mainHeight);
669
-
670
- // Cap task list to actual content height — surplus goes to feed
671
- const isTaskList = hasPlan && !isFeedFocus && tasks.length > 0;
672
- if (isTaskList) {
673
- const taskContentHeight = Math.max(2, tasks.length);
674
- if (taskContentHeight < mainHeight) {
675
- const surplus = mainHeight - taskContentHeight;
676
- feedHeight += surplus;
677
- mainHeight = taskContentHeight;
678
- }
679
- }
680
-
681
- const displayEvents = allEvents.slice(-feedHeight);
682
- let feedLines = renderFeedSection(this.theme, displayEvents, sectionW, prevTs);
683
- if (feedLines.length > feedHeight) feedLines = feedLines.slice(-feedHeight);
684
-
685
- while (workerLines.length > 0 && workersHeight() + mainHeight + (feedLines.length > 0 ? feedLines.length + 1 : 0) + agentsHeight > contentHeight) {
686
- workerLines = workerLines.slice(0, workerLines.length - 1);
687
- }
688
-
689
- let mainLines: string[];
690
- if (!hasPlan && !planning) {
691
- mainLines = renderEmptyState(this.theme, this.cwd, sectionW, mainHeight);
692
- } else if (planning && tasks.length === 0) {
693
- mainLines = renderPlanningState(this.theme, this.cwd, sectionW, mainHeight);
694
- } else if (isFeedFocus && tasks.length > 0) {
695
- mainLines = renderTaskSummary(this.theme, this.cwd, sectionW, mainHeight, tasks);
696
- } else {
697
- mainLines = renderTaskList(this.theme, this.cwd, sectionW, mainHeight, this.crewViewState, tasks);
698
- }
699
-
700
- contentLines = [];
701
-
702
- contentLines.push(agentsLine);
703
- contentLines.push(sectionSeparator);
704
-
705
- if (workerLines.length > 0) {
706
- contentLines.push(...workerLines);
707
- contentLines.push(sectionSeparator);
708
- }
709
-
710
- contentLines.push(...mainLines);
711
-
712
- if (feedLines.length > 0) {
713
- contentLines.push(sectionSeparator);
714
- contentLines.push(...feedLines);
715
- }
716
-
717
- if (contentLines.length > contentHeight) {
718
- contentLines = contentLines.slice(0, contentHeight);
719
- }
720
- while (contentLines.length < contentHeight) {
721
- contentLines.push("");
722
- }
723
- }
724
-
725
- for (const line of contentLines) {
726
- lines.push(row(line));
727
- }
728
-
729
- lines.push(border("├" + "─".repeat(innerW) + "┤"));
730
- lines.push(row(renderLegend(this.theme, this.cwd, sectionW, this.crewViewState, selectedTask)));
731
- lines.push(border("╰" + "─".repeat(innerW) + "╯"));
732
-
733
- if (allEvents.length > 0) {
734
- this.crewViewState.lastSeenEventTs = allEvents[allEvents.length - 1].ts;
735
- }
736
-
737
- return lines;
738
- }
739
-
740
- private static readonly SIGNIFICANT_EVENTS = new Set<FeedEventType>([
741
- "task.done", "task.block", "task.start", "message",
742
- "plan.done", "plan.failed", "task.revise", "task.revise-tree",
743
- ]);
744
-
745
- private detectAndFlashEvents(events: FeedEvent[], prevTs: string | null): void {
746
- if (prevTs === null) return;
747
- const newEvents = events.filter(e => e.ts > prevTs);
748
- if (newEvents.length === 0) return;
749
-
750
- const significant = newEvents.filter(e => MessengerOverlay.SIGNIFICANT_EVENTS.has(e.type));
751
- if (significant.length === 0) return;
752
-
753
- const last = significant[significant.length - 1];
754
- const sameType = significant.filter(e => e.type === last.type);
755
-
756
- let message: string;
757
- if (sameType.length > 1) {
758
- const label =
759
- last.type === "task.done" ? `${sameType.length} tasks completed` :
760
- last.type === "task.start" ? `${sameType.length} tasks started` :
761
- last.type === "task.block" ? `${sameType.length} tasks blocked` :
762
- last.type === "message" ? `${sameType.length} new messages` :
763
- `${sameType.length} ${last.type} events`;
764
- message = label;
765
- } else {
766
- const target = last.target ? ` ${last.target}` : "";
767
- const preview = last.preview ? ` — ${last.preview.slice(0, 40)}` : "";
768
- message =
769
- last.type === "task.done" ? `${last.agent} completed${target}` :
770
- last.type === "task.start" ? `${last.agent} started${target}` :
771
- last.type === "task.block" ? `${last.agent} blocked${target}${preview}` :
772
- last.type === "message" ? `${last.agent}${preview || " sent a message"}` :
773
- last.type === "plan.done" ? "Planning completed" :
774
- last.type === "plan.failed" ? "Planning failed" :
775
- `${last.agent} ${last.type}${target}`;
776
- }
777
-
778
- setNotification(this.crewViewState, this.tui, true, message);
779
- }
780
-
781
- private checkCompletion(tasks: Task[], planning: boolean): void {
782
- const allDone = tasks.length > 0 && tasks.every(t => t.status === "done");
783
- const isIdle = !hasLiveWorkers(this.cwd) && !isAutonomousForCwd(this.cwd) && !planning;
784
-
785
- if (!allDone) {
786
- this.sawIncompleteWork = true;
787
- this.cancelCompletionTimer();
788
- this.completionDismissed = false;
789
- return;
790
- }
791
-
792
- if (isIdle && this.sawIncompleteWork && !this.completionTimer && !this.completionDismissed) {
793
- setNotification(this.crewViewState, this.tui, true, "All tasks complete! Closing in 3s...");
794
- this.completionTimer = setTimeout(() => {
795
- this.completionTimer = null;
796
- this.done(this.generateSnapshot());
797
- }, 3000);
798
- }
799
- }
800
-
801
- private cancelCompletionTimer(): void {
802
- if (this.completionTimer) {
803
- clearTimeout(this.completionTimer);
804
- this.completionTimer = null;
805
- this.completionDismissed = true;
806
- }
807
- }
808
-
809
- private renderTitleContent(): string {
810
- const label = this.theme.fg("accent", "Messenger");
811
- const folder = this.theme.fg("dim", extractFolder(this.cwd));
812
- return `${label} ─ ${folder}`;
813
- }
814
-
815
- invalidate(): void {
816
- // No cached state
817
- }
818
-
819
- dispose(): void {
820
- this.stopProgressRefresh();
821
- this.stopPlanningRefresh();
822
- this.cancelCompletionTimer();
823
- if (this.crewViewState.notificationTimer) {
824
- clearTimeout(this.crewViewState.notificationTimer);
825
- this.crewViewState.notificationTimer = null;
826
- }
827
- this.progressUnsubscribe?.();
828
- this.progressUnsubscribe = null;
829
- }
830
- }
1
+ /**
2
+ * Pi Messenger - Chat Overlay Component
3
+ */
4
+
5
+ import type { Component, Focusable, TUI } from "@linxiraos/pi-tui";
6
+ import { matchesKey, truncateToWidth, visibleWidth } from "@linxiraos/pi-tui";
7
+ import type { Theme } from "@linxiraos/zeta";
8
+ import { extractFolder, formatDuration, type MessengerState, type Dirs } from "./lib.ts";
9
+ import * as crewStore from "./crew/store.ts";
10
+ import {
11
+ adjustConcurrency,
12
+ autonomousState,
13
+ isAutonomousForCwd,
14
+ isPlanningForCwd,
15
+ planningState,
16
+ } from "./crew/state.ts";
17
+ import { loadCrewConfig, cycleCoordinationLevel, setCoordinationOverride } from "./crew/utils/config.ts";
18
+ import { readFeedEvents, type FeedEvent, type FeedEventType } from "./feed.ts";
19
+ import type { Task } from "./crew/types.ts";
20
+ import {
21
+ renderStatusBar,
22
+ renderWorkersSection,
23
+ renderTaskList,
24
+ renderTaskSummary,
25
+ renderFeedSection,
26
+ renderAgentsRow,
27
+ renderLegend,
28
+ renderEmptyState,
29
+ renderPlanningState,
30
+ renderDetailView,
31
+ navigateTask,
32
+ } from "./overlay-render.ts";
33
+ import {
34
+ createCrewViewState,
35
+ handleConfirmInput,
36
+ handleBlockReasonInput,
37
+ handleMessageInput,
38
+ handleRevisePromptInput,
39
+ handleCrewKeyBinding,
40
+ setNotification,
41
+ type CrewViewState,
42
+ } from "./overlay-actions.ts";
43
+ import { getLiveWorkers, hasLiveWorkers, onLiveWorkersChanged } from "./crew/live-progress.ts";
44
+ import { loadConfig } from "./config.ts";
45
+ import { discoverCrewAgents } from "./crew/utils/discover.ts";
46
+ import { spawnSingleWorker, spawnWorkersForReadyTasks } from "./crew/spawn.ts";
47
+ import * as teamStore from "./crew/team/store.ts";
48
+ import { spawnLobbyWorker, removeLobbyWorkerByIndex, cleanupUnassignedAliveFiles } from "./crew/lobby.ts";
49
+
50
+ export interface OverlayCallbacks {
51
+ onBackground?: (snapshot: string) => void;
52
+ }
53
+
54
+ export class MessengerOverlay implements Component, Focusable {
55
+ get width(): number {
56
+ return Math.min(100, Math.max(40, process.stdout.columns ?? 90));
57
+ }
58
+ focused = false;
59
+
60
+ private crewViewState: CrewViewState = createCrewViewState();
61
+ private cwd: string;
62
+ private stuckThresholdMs: number;
63
+ private progressTimer: ReturnType<typeof setInterval> | null = null;
64
+ private planningTimer: ReturnType<typeof setInterval> | null = null;
65
+ private progressUnsubscribe: (() => void) | null = null;
66
+ private sawIncompleteWork = false;
67
+ private completionTimer: ReturnType<typeof setTimeout> | null = null;
68
+ private completionDismissed = false;
69
+ private wasPlanning: boolean;
70
+ private prevInProgressCount = 0;
71
+
72
+ constructor(
73
+ private tui: TUI,
74
+ private theme: Theme,
75
+ private state: MessengerState,
76
+ private dirs: Dirs,
77
+ private done: (snapshot?: string) => void,
78
+ private callbacks: OverlayCallbacks,
79
+ cwd: string,
80
+ ) {
81
+ this.cwd = cwd;
82
+ const cfg = loadConfig(this.cwd);
83
+ this.stuckThresholdMs = cfg.stuckThreshold * 1000;
84
+
85
+ for (const key of this.state.unreadCounts.keys()) {
86
+ this.state.unreadCounts.set(key, 0);
87
+ }
88
+
89
+ this.wasPlanning = isPlanningForCwd(this.cwd);
90
+
91
+ this.progressUnsubscribe = onLiveWorkersChanged(() => {
92
+ this.syncCrewRefreshTimers();
93
+ this.tui.requestRender();
94
+ });
95
+
96
+ this.syncCrewRefreshTimers();
97
+ }
98
+
99
+ private hasPlan(): boolean {
100
+ return crewStore.hasPlan(this.cwd);
101
+ }
102
+
103
+ private handleTaskStart(task: Task): void {
104
+ const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
105
+ if (config.dependencies !== "advisory") {
106
+ const unmet = task.depends_on.filter(depId => crewStore.getTask(this.cwd, depId)?.status !== "done");
107
+ if (unmet.length > 0) {
108
+ setNotification(this.crewViewState, this.tui, false, `Unmet deps: ${unmet.join(", ")}`);
109
+ this.tui.requestRender();
110
+ return;
111
+ }
112
+ }
113
+ if (teamStore.taskNeedsApproval(task)) {
114
+ const message = teamStore.taskNeedsRevision(task)
115
+ ? `${task.id} needs revision`
116
+ : `${task.id} needs lead approval`;
117
+ setNotification(this.crewViewState, this.tui, false, message);
118
+ this.tui.requestRender();
119
+ return;
120
+ }
121
+
122
+ const worker = spawnSingleWorker(this.cwd, task.id, this.state.model);
123
+ if (worker) {
124
+ setNotification(this.crewViewState, this.tui, true, `${worker.name} → ${task.id}`);
125
+ } else {
126
+ setNotification(this.crewViewState, this.tui, false, `Failed to spawn worker for ${task.id}`);
127
+ }
128
+ this.tui.requestRender();
129
+ }
130
+
131
+ private spawnWorkerForReadyTask(task: Task, newConcurrency: number): void {
132
+ const worker = spawnSingleWorker(this.cwd, task.id, this.state.model);
133
+ if (!worker) {
134
+ const message = teamStore.taskNeedsRevision(task)
135
+ ? `${task.id} needs revision`
136
+ : teamStore.taskNeedsApproval(task)
137
+ ? `${task.id} needs lead approval`
138
+ : `Failed to spawn worker for ${task.id}`;
139
+ setNotification(this.crewViewState, this.tui, false, message);
140
+ this.tui.requestRender();
141
+ return;
142
+ }
143
+
144
+ setNotification(this.crewViewState, this.tui, true, `${worker.name} → ${task.id} (${newConcurrency}w)`);
145
+ this.tui.requestRender();
146
+ }
147
+
148
+ private isPlanningActiveForCurrentProject(): boolean {
149
+ return isPlanningForCwd(this.cwd);
150
+ }
151
+
152
+ private checkAutoSpawnOnPlanComplete(planning: boolean, tasks: Task[]): void {
153
+ const wasPlanningBefore = this.wasPlanning;
154
+ this.wasPlanning = planning;
155
+
156
+ if (!wasPlanningBefore || planning) return;
157
+
158
+ const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
159
+ const readyTasks = crewStore.getReadyTasksFrom(tasks, { advisory: config.dependencies === "advisory" });
160
+ const startableTasks = readyTasks.filter(t => !teamStore.taskNeedsApproval(t));
161
+ if (startableTasks.length > 0) {
162
+ const target = Math.min(startableTasks.length, autonomousState.concurrency);
163
+ const { assigned } = spawnWorkersForReadyTasks(this.cwd, target, this.state.model);
164
+ if (assigned > 0) {
165
+ setNotification(
166
+ this.crewViewState,
167
+ this.tui,
168
+ true,
169
+ `Plan ready — ${assigned} worker${assigned > 1 ? "s" : ""} started`,
170
+ );
171
+ this.tui.requestRender();
172
+ }
173
+ } else if (readyTasks.length > 0) {
174
+ const rejected = readyTasks.filter(teamStore.taskNeedsRevision);
175
+ const pending = readyTasks.filter(teamStore.taskPendingApproval);
176
+ const message =
177
+ rejected.length > 0
178
+ ? `Plan ready — ${rejected.length} task${rejected.length > 1 ? "s" : ""} need revision`
179
+ : `Plan ready — ${pending.length} task${pending.length > 1 ? "s" : ""} need lead approval`;
180
+ setNotification(this.crewViewState, this.tui, false, message);
181
+ this.tui.requestRender();
182
+ }
183
+
184
+ cleanupUnassignedAliveFiles(this.cwd);
185
+ }
186
+
187
+ private checkAutoRefillWorkers(tasks: Task[], hasPlan: boolean): void {
188
+ const inProgressCount = tasks.filter(t => t.status === "in_progress").length;
189
+ const prev = this.prevInProgressCount;
190
+ this.prevInProgressCount = inProgressCount;
191
+
192
+ if (inProgressCount >= prev || inProgressCount >= autonomousState.concurrency || !hasPlan) return;
193
+
194
+ const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
195
+ const readyTasks = crewStore.getReadyTasksFrom(tasks, { advisory: config.dependencies === "advisory" });
196
+ const startableTasks = readyTasks.filter(t => !teamStore.taskNeedsApproval(t));
197
+ if (startableTasks.length === 0) return;
198
+
199
+ const slots = autonomousState.concurrency - inProgressCount;
200
+ const target = Math.min(startableTasks.length, slots);
201
+ if (target <= 0) return;
202
+
203
+ const { assigned } = spawnWorkersForReadyTasks(this.cwd, target, this.state.model);
204
+ if (assigned > 0) {
205
+ setNotification(
206
+ this.crewViewState,
207
+ this.tui,
208
+ true,
209
+ `${assigned} worker${assigned > 1 ? "s" : ""} → ready tasks`,
210
+ );
211
+ this.tui.requestRender();
212
+ }
213
+ }
214
+
215
+ private syncCrewRefreshTimers(): void {
216
+ if (hasLiveWorkers(this.cwd)) this.startProgressRefresh();
217
+ else this.stopProgressRefresh();
218
+
219
+ if (this.isPlanningActiveForCurrentProject()) this.startPlanningRefresh();
220
+ else this.stopPlanningRefresh();
221
+ }
222
+
223
+ private startProgressRefresh(): void {
224
+ if (this.progressTimer) return;
225
+ this.progressTimer = setInterval(() => {
226
+ if (hasLiveWorkers(this.cwd)) {
227
+ this.tui.requestRender();
228
+ } else {
229
+ this.stopProgressRefresh();
230
+ }
231
+ }, 1000);
232
+ }
233
+
234
+ private stopProgressRefresh(): void {
235
+ if (this.progressTimer) {
236
+ clearInterval(this.progressTimer);
237
+ this.progressTimer = null;
238
+ }
239
+ }
240
+
241
+ private startPlanningRefresh(): void {
242
+ if (this.planningTimer) return;
243
+ this.planningTimer = setInterval(() => {
244
+ if (this.isPlanningActiveForCurrentProject()) {
245
+ this.tui.requestRender();
246
+ } else {
247
+ this.stopPlanningRefresh();
248
+ }
249
+ }, 15_000);
250
+ }
251
+
252
+ private stopPlanningRefresh(): void {
253
+ if (this.planningTimer) {
254
+ clearInterval(this.planningTimer);
255
+ this.planningTimer = null;
256
+ }
257
+ }
258
+
259
+ handleInput(data: string): void {
260
+ this.cancelCompletionTimer();
261
+
262
+ if (data === "\x14") {
263
+ this.done(this.generateSnapshot());
264
+ return;
265
+ }
266
+
267
+ if (data === "\x02") {
268
+ this.callbacks.onBackground?.(this.generateSnapshot());
269
+ return;
270
+ }
271
+
272
+ if (this.crewViewState.confirmAction) {
273
+ handleConfirmInput(data, this.crewViewState, this.cwd, this.state.agentName, this.tui);
274
+ return;
275
+ }
276
+
277
+ if (this.crewViewState.inputMode === "block-reason") {
278
+ const tasks = crewStore.getTasks(this.cwd);
279
+ const task = tasks[this.crewViewState.selectedTaskIndex];
280
+ handleBlockReasonInput(data, this.crewViewState, this.cwd, task, this.state.agentName, this.tui);
281
+ return;
282
+ }
283
+
284
+ if (this.crewViewState.inputMode === "message") {
285
+ handleMessageInput(data, this.crewViewState, this.state, this.dirs, this.cwd, this.tui);
286
+ return;
287
+ }
288
+
289
+ if (this.crewViewState.inputMode === "revise-prompt") {
290
+ const tasks = crewStore.getTasks(this.cwd);
291
+ const task = tasks[this.crewViewState.selectedTaskIndex];
292
+ handleRevisePromptInput(data, this.crewViewState, this.cwd, task, this.state.agentName, this.tui);
293
+ return;
294
+ }
295
+
296
+ if (matchesKey(data, "escape")) {
297
+ if (this.crewViewState.mode === "detail") {
298
+ this.crewViewState.mode = "list";
299
+ this.tui.requestRender();
300
+ } else {
301
+ this.done();
302
+ }
303
+ return;
304
+ }
305
+
306
+ if (data === "+" || matchesKey(data, "=") || matchesKey(data, "shift+=") || matchesKey(data, "-")) {
307
+ const delta = matchesKey(data, "-") ? -1 : 1;
308
+ const crewDir = crewStore.getCrewDir(this.cwd);
309
+ const config = loadCrewConfig(crewDir);
310
+ const prev = autonomousState.concurrency;
311
+ const next = adjustConcurrency(delta, config.concurrency.max);
312
+ if (prev === next) {
313
+ this.tui.requestRender();
314
+ return;
315
+ }
316
+
317
+ if (next > prev) {
318
+ const readyTasks = crewStore.getReadyTasks(this.cwd, { advisory: config.dependencies === "advisory" });
319
+ if (readyTasks.length === 0) {
320
+ const worker = spawnLobbyWorker(this.cwd, undefined, this.state.model);
321
+ const label = worker ? `Lobby worker ${worker.name} spawned (${next}w)` : `Workers → ${next}`;
322
+ setNotification(this.crewViewState, this.tui, true, label);
323
+ } else {
324
+ this.spawnWorkerForReadyTask(readyTasks[0], next);
325
+ }
326
+ } else {
327
+ const killed = removeLobbyWorkerByIndex(this.cwd);
328
+ const label = killed ? `Lobby worker removed (${next}w)` : `Workers: ${prev} → ${next}`;
329
+ setNotification(this.crewViewState, this.tui, true, label);
330
+ }
331
+ this.tui.requestRender();
332
+ return;
333
+ }
334
+
335
+ if (data === "@" || matchesKey(data, "m")) {
336
+ if (isPlanningForCwd(this.cwd)) {
337
+ setNotification(this.crewViewState, this.tui, false, "Chat unavailable during planning");
338
+ this.tui.requestRender();
339
+ return;
340
+ }
341
+ this.crewViewState.inputMode = "message";
342
+ this.crewViewState.messageInput = data === "@" ? "@" : "";
343
+ this.tui.requestRender();
344
+ return;
345
+ }
346
+
347
+ if (matchesKey(data, "f")) {
348
+ this.crewViewState.feedFocus = !this.crewViewState.feedFocus;
349
+ this.tui.requestRender();
350
+ return;
351
+ }
352
+
353
+ if (matchesKey(data, "v")) {
354
+ const crewDir = crewStore.getCrewDir(this.cwd);
355
+ const config = loadCrewConfig(crewDir);
356
+ const next = cycleCoordinationLevel(config.coordination);
357
+ setCoordinationOverride(next);
358
+ setNotification(this.crewViewState, this.tui, true, `Coordination: ${next}`);
359
+ this.tui.requestRender();
360
+ return;
361
+ }
362
+
363
+ if (matchesKey(data, "c") && this.isPlanningActiveForCurrentProject()) {
364
+ this.crewViewState.confirmAction = {
365
+ type: "cancel-planning",
366
+ taskId: "",
367
+ label: "planning",
368
+ };
369
+ this.tui.requestRender();
370
+ return;
371
+ }
372
+
373
+ const tasks = crewStore.getTasks(this.cwd);
374
+ const task = tasks[this.crewViewState.selectedTaskIndex];
375
+
376
+ if (matchesKey(data, "right")) {
377
+ if (this.crewViewState.mode === "detail") {
378
+ navigateTask(this.crewViewState, 1, tasks.length);
379
+ this.crewViewState.detailScroll = 0;
380
+ this.crewViewState.detailAutoScroll = true;
381
+ this.tui.requestRender();
382
+ }
383
+ return;
384
+ }
385
+
386
+ if (matchesKey(data, "left")) {
387
+ if (this.crewViewState.mode === "detail") {
388
+ navigateTask(this.crewViewState, -1, tasks.length);
389
+ this.crewViewState.detailScroll = 0;
390
+ this.crewViewState.detailAutoScroll = true;
391
+ this.tui.requestRender();
392
+ }
393
+ return;
394
+ }
395
+
396
+ if (matchesKey(data, "up")) {
397
+ if (this.crewViewState.mode === "detail") {
398
+ this.crewViewState.detailScroll = Math.max(0, this.crewViewState.detailScroll - 1);
399
+ this.crewViewState.detailAutoScroll = false;
400
+ } else {
401
+ navigateTask(this.crewViewState, -1, tasks.length);
402
+ }
403
+ this.tui.requestRender();
404
+ return;
405
+ }
406
+
407
+ if (matchesKey(data, "down")) {
408
+ if (this.crewViewState.mode === "detail") {
409
+ this.crewViewState.detailScroll++;
410
+ this.crewViewState.detailAutoScroll = false;
411
+ } else {
412
+ navigateTask(this.crewViewState, 1, tasks.length);
413
+ }
414
+ this.tui.requestRender();
415
+ return;
416
+ }
417
+
418
+ if (matchesKey(data, "home")) {
419
+ this.crewViewState.selectedTaskIndex = 0;
420
+ this.crewViewState.scrollOffset = 0;
421
+ if (this.crewViewState.mode === "detail") {
422
+ this.crewViewState.detailScroll = 0;
423
+ this.crewViewState.detailAutoScroll = false;
424
+ }
425
+ this.tui.requestRender();
426
+ return;
427
+ }
428
+
429
+ if (matchesKey(data, "end")) {
430
+ this.crewViewState.selectedTaskIndex = Math.max(0, tasks.length - 1);
431
+ if (this.crewViewState.mode === "detail") {
432
+ this.crewViewState.detailScroll = 0;
433
+ this.crewViewState.detailAutoScroll = true;
434
+ }
435
+ this.tui.requestRender();
436
+ return;
437
+ }
438
+
439
+ if (matchesKey(data, "enter")) {
440
+ if (task && this.crewViewState.mode !== "detail") {
441
+ this.crewViewState.mode = "detail";
442
+ this.crewViewState.detailScroll = 0;
443
+ this.crewViewState.detailAutoScroll = true;
444
+ this.tui.requestRender();
445
+ }
446
+ return;
447
+ }
448
+
449
+ if (this.crewViewState.mode === "detail") {
450
+ if (matchesKey(data, "[")) {
451
+ navigateTask(this.crewViewState, -1, tasks.length);
452
+ this.crewViewState.detailScroll = 0;
453
+ this.crewViewState.detailAutoScroll = true;
454
+ this.tui.requestRender();
455
+ return;
456
+ }
457
+ if (matchesKey(data, "]")) {
458
+ navigateTask(this.crewViewState, 1, tasks.length);
459
+ this.crewViewState.detailScroll = 0;
460
+ this.crewViewState.detailAutoScroll = true;
461
+ this.tui.requestRender();
462
+ return;
463
+ }
464
+ }
465
+
466
+ if (task) {
467
+ if (matchesKey(data, "s") && task.status === "todo" && !task.milestone) {
468
+ this.handleTaskStart(task);
469
+ return;
470
+ }
471
+ handleCrewKeyBinding(data, task, this.crewViewState, this.cwd, this.state.agentName, this.tui);
472
+ }
473
+ }
474
+
475
+ private snapshotIdleLabel(): string {
476
+ const last = this.state.activity.lastActivityAt || this.state.sessionStartedAt;
477
+ const ageMs = Math.max(0, Date.now() - new Date(last).getTime());
478
+ return `idle ${formatDuration(ageMs)}`;
479
+ }
480
+
481
+ private formatTaskSnapshotLine(task: Task, liveTaskIds: Set<string>): string {
482
+ if (task.status === "done") {
483
+ return `${task.id} (${task.title})`;
484
+ }
485
+ if (task.status === "in_progress") {
486
+ const parts = [task.title];
487
+ if (task.assigned_to) parts.push(task.assigned_to);
488
+ if (liveTaskIds.has(task.id)) parts.push("live");
489
+ return `${task.id} (${parts.join(", ")})`;
490
+ }
491
+ if (task.status === "blocked") {
492
+ const reason = task.blocked_reason ? ` — ${task.blocked_reason}` : "";
493
+ return `${task.id} (${task.title}${reason})`;
494
+ }
495
+ if (task.depends_on.length > 0) {
496
+ return `${task.id} (${task.title}, deps: ${task.depends_on.join(" ")})`;
497
+ }
498
+ return `${task.id} (${task.title})`;
499
+ }
500
+
501
+ private formatRecentFeedEvent(event: FeedEvent): string {
502
+ const time = new Date(event.ts).toLocaleTimeString("en-US", {
503
+ hour: "2-digit",
504
+ minute: "2-digit",
505
+ hour12: false,
506
+ });
507
+ if (event.type === "task.done") return `${event.agent} completed ${event.target ?? "task"} (${time})`;
508
+ if (event.type === "task.start") return `${event.agent} started ${event.target ?? "task"} (${time})`;
509
+ if (event.type === "message") {
510
+ const dir = event.target ? `→ ${event.target}: ` : "✦ ";
511
+ return event.preview
512
+ ? `${event.agent} ${dir}${event.preview} (${time})`
513
+ : `${event.agent} ${dir.trim()} (${time})`;
514
+ }
515
+ if (event.target) return `${event.agent} ${event.type} ${event.target} (${time})`;
516
+ return `${event.agent} ${event.type} (${time})`;
517
+ }
518
+
519
+ private generateSnapshot(): string {
520
+ const plan = crewStore.getPlan(this.cwd);
521
+ const tasks = crewStore.getTasks(this.cwd);
522
+ const liveWorkers = getLiveWorkers(this.cwd);
523
+
524
+ if (this.isPlanningActiveForCurrentProject() && tasks.length === 0) {
525
+ const updated = planningState.updatedAt
526
+ ? formatDuration(Math.max(0, Date.now() - new Date(planningState.updatedAt).getTime()))
527
+ : "unknown";
528
+ return [
529
+ `Crew snapshot: planning in progress (pass ${planningState.pass}/${planningState.maxPasses}, ${planningState.phase}), ${autonomousState.concurrency}w concurrency`,
530
+ "",
531
+ `Planning: pass ${planningState.pass}/${planningState.maxPasses}, phase: ${planningState.phase}, updated ${updated} ago`,
532
+ "",
533
+ `Agents: You (${this.snapshotIdleLabel()})`,
534
+ ].join("\n");
535
+ }
536
+
537
+ if (!plan) {
538
+ const discovered = discoverCrewAgents(this.cwd);
539
+ const configLine =
540
+ discovered.length === 0
541
+ ? "Config: no crew agents discovered"
542
+ : `Config: ${discovered.map(agent => `${agent.name}${agent.model ? ` (${agent.model})` : ""}`).join(", ")}`;
543
+
544
+ return [
545
+ `Crew snapshot: no active plan, ${autonomousState.concurrency}w concurrency`,
546
+ "",
547
+ `Agents: You (${this.snapshotIdleLabel()})`,
548
+ "",
549
+ configLine,
550
+ ].join("\n");
551
+ }
552
+
553
+ const config = loadCrewConfig(crewStore.getCrewDir(this.cwd));
554
+ const readyTasks = crewStore.getReadyTasks(this.cwd, { advisory: config.dependencies === "advisory" });
555
+ const readyIds = new Set(readyTasks.map(task => task.id));
556
+ const liveTaskIds = new Set(Array.from(liveWorkers.keys()));
557
+ const activeLines = Array.from(liveWorkers.values()).map(worker => {
558
+ const activity = worker.progress.currentTool
559
+ ? `${worker.progress.currentTool}${worker.progress.currentToolArgs ? ` ${worker.progress.currentToolArgs}` : ""}`
560
+ : "thinking";
561
+ return `${worker.taskId} (${worker.agent}, ${activity}, ${formatDuration(Date.now() - worker.startedAt)})`;
562
+ });
563
+
564
+ const doneTasks = tasks.filter(task => task.status === "done");
565
+ const inProgressTasks = tasks.filter(task => task.status === "in_progress");
566
+ const blockedTasks = tasks.filter(task => task.status === "blocked");
567
+ const waitingTasks = tasks.filter(task => task.status === "todo" && !readyIds.has(task.id));
568
+ const recentEvents = readFeedEvents(this.cwd, 2);
569
+ const headerParts = [
570
+ `Crew snapshot: ${plan.completed_count}/${plan.task_count} tasks done`,
571
+ `${readyTasks.length} ready`,
572
+ `${autonomousState.concurrency}w`,
573
+ ];
574
+ if (isAutonomousForCwd(this.cwd)) {
575
+ headerParts.push(`autonomous wave ${autonomousState.waveNumber}`);
576
+ }
577
+
578
+ const lines = [
579
+ headerParts.join(", "),
580
+ "",
581
+ `Active: ${activeLines.length > 0 ? activeLines.join(", ") : "none"}`,
582
+ `Done: ${doneTasks.length > 0 ? doneTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
583
+ `In progress: ${inProgressTasks.length > 0 ? inProgressTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
584
+ `Ready: ${readyTasks.length > 0 ? readyTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
585
+ `Blocked: ${blockedTasks.length > 0 ? blockedTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
586
+ `Waiting: ${waitingTasks.length > 0 ? waitingTasks.map(task => this.formatTaskSnapshotLine(task, liveTaskIds)).join(", ") : "none"}`,
587
+ ];
588
+
589
+ if (recentEvents.length > 0) {
590
+ lines.push("");
591
+ lines.push(`Recent: ${recentEvents.map(event => this.formatRecentFeedEvent(event)).join(", ")}`);
592
+ }
593
+
594
+ return lines.join("\n");
595
+ }
596
+
597
+ render(_width: number): string[] {
598
+ const w = this.width;
599
+ const innerW = w - 2;
600
+ const sectionW = innerW - 2;
601
+ const border = (s: string) => this.theme.fg("dim", s);
602
+ const pad = (s: string, len: number) => s + " ".repeat(Math.max(0, len - visibleWidth(s)));
603
+ const sanitizeRowContent = (content: string) =>
604
+ content.replaceAll("\r", " ").replaceAll("\n", " ").replaceAll("\t", " ");
605
+ const row = (content: string) => {
606
+ const safe = truncateToWidth(sanitizeRowContent(content), sectionW);
607
+ return border("│") + pad(" " + safe, innerW) + border("│");
608
+ };
609
+ const emptyRow = () => border("│") + " ".repeat(innerW) + border("│");
610
+ const sectionSeparator = this.theme.fg("dim", "─".repeat(sectionW));
611
+
612
+ const tasks = crewStore.getTasks(this.cwd);
613
+ if (tasks.length === 0) {
614
+ this.crewViewState.selectedTaskIndex = 0;
615
+ if (this.crewViewState.mode === "detail") this.crewViewState.mode = "list";
616
+ } else {
617
+ this.crewViewState.selectedTaskIndex = Math.max(
618
+ 0,
619
+ Math.min(this.crewViewState.selectedTaskIndex, tasks.length - 1),
620
+ );
621
+ }
622
+
623
+ const selectedTask = tasks[this.crewViewState.selectedTaskIndex] ?? null;
624
+ const hasPlan = this.hasPlan();
625
+ const planning = this.isPlanningActiveForCurrentProject();
626
+ this.checkAutoSpawnOnPlanComplete(planning, tasks);
627
+ this.checkAutoRefillWorkers(tasks, hasPlan);
628
+
629
+ const lines: string[] = [];
630
+ const titleContent = this.renderTitleContent();
631
+ const titleText = ` ${titleContent} `;
632
+ const titleLen = visibleWidth(titleContent) + 2;
633
+ const borderLen = Math.max(0, innerW - titleLen);
634
+ const leftBorder = Math.floor(borderLen / 2);
635
+ const rightBorder = borderLen - leftBorder;
636
+
637
+ lines.push(border("╭" + "─".repeat(leftBorder)) + titleText + border("─".repeat(rightBorder) + "╮"));
638
+ lines.push(row(renderStatusBar(this.theme, this.cwd, sectionW, tasks)));
639
+ lines.push(emptyRow());
640
+
641
+ const chromeLines = 6;
642
+ const termRows = process.stdout.rows ?? 24;
643
+ const contentHeight = Math.max(8, termRows - chromeLines);
644
+
645
+ const prevTs = this.crewViewState.lastSeenEventTs;
646
+ const allEvents = readFeedEvents(this.cwd, 20);
647
+ this.detectAndFlashEvents(allEvents, prevTs);
648
+ this.checkCompletion(tasks, planning);
649
+
650
+ let contentLines: string[];
651
+ if (this.crewViewState.mode === "detail" && selectedTask) {
652
+ contentLines = renderDetailView(this.cwd, selectedTask, sectionW, contentHeight, this.crewViewState);
653
+ } else {
654
+ const workersLimit = termRows <= 26 ? 2 : 5;
655
+ const hasWorkers = hasLiveWorkers(this.cwd);
656
+
657
+ let workerLines = renderWorkersSection(this.theme, this.cwd, sectionW, workersLimit);
658
+ const agentsLine = renderAgentsRow(
659
+ this.cwd,
660
+ sectionW,
661
+ this.state,
662
+ this.dirs,
663
+ this.stuckThresholdMs,
664
+ new Map([[this.cwd, tasks]]),
665
+ );
666
+ const agentsHeight = 2;
667
+ const workersHeight = () => (workerLines.length > 0 ? workerLines.length + 1 : 0);
668
+ const available = contentHeight - workersHeight() - agentsHeight;
669
+
670
+ const isFeedFocus = this.crewViewState.feedFocus;
671
+ let feedHeight: number;
672
+ let mainHeight: number;
673
+
674
+ if (!hasPlan && !planning) {
675
+ feedHeight = Math.min(allEvents.length, Math.max(2, Math.floor(available * 0.4)));
676
+ mainHeight = available - feedHeight - (feedHeight > 0 ? 1 : 0);
677
+ } else if (isFeedFocus) {
678
+ const summaryLines = 2;
679
+ mainHeight = summaryLines;
680
+ feedHeight = available - summaryLines - 1;
681
+ } else if (hasWorkers) {
682
+ feedHeight = Math.max(6, Math.floor(available * 0.7));
683
+ mainHeight = available - feedHeight - 1;
684
+ } else {
685
+ feedHeight = Math.max(4, Math.floor(available * 0.6));
686
+ mainHeight = available - feedHeight - 1;
687
+ }
688
+
689
+ feedHeight = Math.max(0, feedHeight);
690
+ mainHeight = Math.max(2, mainHeight);
691
+
692
+ // Cap task list to actual content height — surplus goes to feed
693
+ const isTaskList = hasPlan && !isFeedFocus && tasks.length > 0;
694
+ if (isTaskList) {
695
+ const taskContentHeight = Math.max(2, tasks.length);
696
+ if (taskContentHeight < mainHeight) {
697
+ const surplus = mainHeight - taskContentHeight;
698
+ feedHeight += surplus;
699
+ mainHeight = taskContentHeight;
700
+ }
701
+ }
702
+
703
+ const displayEvents = allEvents.slice(-feedHeight);
704
+ let feedLines = renderFeedSection(this.theme, displayEvents, sectionW, prevTs);
705
+ if (feedLines.length > feedHeight) feedLines = feedLines.slice(-feedHeight);
706
+
707
+ while (
708
+ workerLines.length > 0 &&
709
+ workersHeight() + mainHeight + (feedLines.length > 0 ? feedLines.length + 1 : 0) + agentsHeight >
710
+ contentHeight
711
+ ) {
712
+ workerLines = workerLines.slice(0, workerLines.length - 1);
713
+ }
714
+
715
+ let mainLines: string[];
716
+ if (!hasPlan && !planning) {
717
+ mainLines = renderEmptyState(this.theme, this.cwd, sectionW, mainHeight);
718
+ } else if (planning && tasks.length === 0) {
719
+ mainLines = renderPlanningState(this.theme, this.cwd, sectionW, mainHeight);
720
+ } else if (isFeedFocus && tasks.length > 0) {
721
+ mainLines = renderTaskSummary(this.theme, this.cwd, sectionW, mainHeight, tasks);
722
+ } else {
723
+ mainLines = renderTaskList(this.theme, this.cwd, sectionW, mainHeight, this.crewViewState, tasks);
724
+ }
725
+
726
+ contentLines = [];
727
+
728
+ contentLines.push(agentsLine);
729
+ contentLines.push(sectionSeparator);
730
+
731
+ if (workerLines.length > 0) {
732
+ contentLines.push(...workerLines);
733
+ contentLines.push(sectionSeparator);
734
+ }
735
+
736
+ contentLines.push(...mainLines);
737
+
738
+ if (feedLines.length > 0) {
739
+ contentLines.push(sectionSeparator);
740
+ contentLines.push(...feedLines);
741
+ }
742
+
743
+ if (contentLines.length > contentHeight) {
744
+ contentLines = contentLines.slice(0, contentHeight);
745
+ }
746
+ while (contentLines.length < contentHeight) {
747
+ contentLines.push("");
748
+ }
749
+ }
750
+
751
+ for (const line of contentLines) {
752
+ lines.push(row(line));
753
+ }
754
+
755
+ lines.push(border("├" + "─".repeat(innerW) + "┤"));
756
+ lines.push(row(renderLegend(this.theme, this.cwd, sectionW, this.crewViewState, selectedTask)));
757
+ lines.push(border("╰" + "─".repeat(innerW) + "╯"));
758
+
759
+ if (allEvents.length > 0) {
760
+ this.crewViewState.lastSeenEventTs = allEvents[allEvents.length - 1].ts;
761
+ }
762
+
763
+ return lines;
764
+ }
765
+
766
+ private static readonly SIGNIFICANT_EVENTS = new Set<FeedEventType>([
767
+ "task.done",
768
+ "task.block",
769
+ "task.start",
770
+ "message",
771
+ "plan.done",
772
+ "plan.failed",
773
+ "task.revise",
774
+ "task.revise-tree",
775
+ ]);
776
+
777
+ private detectAndFlashEvents(events: FeedEvent[], prevTs: string | null): void {
778
+ if (prevTs === null) return;
779
+ const newEvents = events.filter(e => e.ts > prevTs);
780
+ if (newEvents.length === 0) return;
781
+
782
+ const significant = newEvents.filter(e => MessengerOverlay.SIGNIFICANT_EVENTS.has(e.type));
783
+ if (significant.length === 0) return;
784
+
785
+ const last = significant[significant.length - 1];
786
+ const sameType = significant.filter(e => e.type === last.type);
787
+
788
+ let message: string;
789
+ if (sameType.length > 1) {
790
+ const label =
791
+ last.type === "task.done"
792
+ ? `${sameType.length} tasks completed`
793
+ : last.type === "task.start"
794
+ ? `${sameType.length} tasks started`
795
+ : last.type === "task.block"
796
+ ? `${sameType.length} tasks blocked`
797
+ : last.type === "message"
798
+ ? `${sameType.length} new messages`
799
+ : `${sameType.length} ${last.type} events`;
800
+ message = label;
801
+ } else {
802
+ const target = last.target ? ` ${last.target}` : "";
803
+ const preview = last.preview ? ` — ${last.preview.slice(0, 40)}` : "";
804
+ message =
805
+ last.type === "task.done"
806
+ ? `${last.agent} completed${target}`
807
+ : last.type === "task.start"
808
+ ? `${last.agent} started${target}`
809
+ : last.type === "task.block"
810
+ ? `${last.agent} blocked${target}${preview}`
811
+ : last.type === "message"
812
+ ? `${last.agent}${preview || " sent a message"}`
813
+ : last.type === "plan.done"
814
+ ? "Planning completed"
815
+ : last.type === "plan.failed"
816
+ ? "Planning failed"
817
+ : `${last.agent} ${last.type}${target}`;
818
+ }
819
+
820
+ setNotification(this.crewViewState, this.tui, true, message);
821
+ }
822
+
823
+ private checkCompletion(tasks: Task[], planning: boolean): void {
824
+ const allDone = tasks.length > 0 && tasks.every(t => t.status === "done");
825
+ const isIdle = !hasLiveWorkers(this.cwd) && !isAutonomousForCwd(this.cwd) && !planning;
826
+
827
+ if (!allDone) {
828
+ this.sawIncompleteWork = true;
829
+ this.cancelCompletionTimer();
830
+ this.completionDismissed = false;
831
+ return;
832
+ }
833
+
834
+ if (isIdle && this.sawIncompleteWork && !this.completionTimer && !this.completionDismissed) {
835
+ setNotification(this.crewViewState, this.tui, true, "All tasks complete! Closing in 3s...");
836
+ this.completionTimer = setTimeout(() => {
837
+ this.completionTimer = null;
838
+ this.done(this.generateSnapshot());
839
+ }, 3000);
840
+ }
841
+ }
842
+
843
+ private cancelCompletionTimer(): void {
844
+ if (this.completionTimer) {
845
+ clearTimeout(this.completionTimer);
846
+ this.completionTimer = null;
847
+ this.completionDismissed = true;
848
+ }
849
+ }
850
+
851
+ private renderTitleContent(): string {
852
+ const label = this.theme.fg("accent", "Messenger");
853
+ const folder = this.theme.fg("dim", extractFolder(this.cwd));
854
+ return `${label} ─ ${folder}`;
855
+ }
856
+
857
+ invalidate(): void {
858
+ // No cached state
859
+ }
860
+
861
+ dispose(): void {
862
+ this.stopProgressRefresh();
863
+ this.stopPlanningRefresh();
864
+ this.cancelCompletionTimer();
865
+ if (this.crewViewState.notificationTimer) {
866
+ clearTimeout(this.crewViewState.notificationTimer);
867
+ this.crewViewState.notificationTimer = null;
868
+ }
869
+ this.progressUnsubscribe?.();
870
+ this.progressUnsubscribe = null;
871
+ }
872
+ }