mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 05:37:19 +01:00
feat(watch): Loki narrates the build live, steer or autopilot from one card; readable screen; no false "Session ended" (#1077)
* fix(watch, terminal): readable live screen, a "What's going on?" button, no false "Session ended"
What the operator saw on a phone, 2026-10-07:
- Watch's "screen" was every spinner frame glued together ("Actioning…●✢4*✶75✻
✻Actioning…5✻…"). A peek is the PTY's byte buffer; deleting the escape codes
kept every redraw. renderTerminalText now replays CR / cursor moves / erase
sequences into the lines the terminal actually shows, and the live line names
the real step ("Running 1 shell command…", "Writing src/app/page.tsx")
instead of Claude Code's decorative spinner word.
- "Open the full terminal" opened a blurred page under a sheet saying "Session
ended — its agent terminal is gone" while it was still connecting to a
healthy session. Connecting no longer reads as gone (presentTerminalRun takes
the real state), the sheet no longer opens by itself over the session, and
the genuinely-lost case names a way forward with a button.
- New: "What's going on?" — under the terminal on phones, in the Loki panel
header, and as the primary button on Watch (opens Terminal with ?explain=1).
Loki answers for a non-programmer: anything waiting on you first, what is
being built and how far along, an honest "Autopilot:" line saying whether it
carries on without you, and up to three one-tap things to tell it next.
- Watch said "Working · 1 min" three times with two spinners; the activity
fold now says when the run started. The kickoff card's four-line "Working"
paragraph with its own spinner is one aligned line, and the pending step's
dot lines up with the icons.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ReWfUGdbNX6X67XDrbF8dg
* refactor(terminal): "What's going on?" state, button and Loki sheet in their own module
TerminalSurface crossed the 510-line function ratchet (533). The explain
request, the sheet that carries its answer and the button now live in
TerminalExplain.tsx; the rail takes them as one `explain` prop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ReWfUGdbNX6X67XDrbF8dg
* feat(watch): Loki narrates the build live; steer it or let autopilot drive, from one card
"Not enough magic" (operator, 2026-10-07). Watch showed a terminal's worth
of facts; a person watching wants to know what is being made for them and
whether they need to do anything.
- While an agent works, Loki reads its screen every ~30s (only when it has
moved) and writes one plain headline in the owner's terms — "Adding the
Team page in three languages" — with a line on what it means. Earlier
headlines stack under it as the story so far. lib/watch-narration (pure,
tested) + POST /api/projects/[id]/watch/narrate (AI-budget gated,
rate-limited, degrades to the agent's own step line, never an error).
- "It needs you" appears only when the screen shows a question or a stop
the agent cannot fix, with one tap to answer.
- The two ways to drive it, on the same card: a "Tell it something" box that
steers the running session (tab-inject), and the project's real autopilot
switch with one line saying what each state does.
- The old live message (typing dots, raw-screen fold, two links) is replaced
by the card; "Look closer" opens the terminal with the explanation asked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ReWfUGdbNX6X67XDrbF8dg
---------
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
33eec2a538
commit
af1463e5a5
19 files changed
+1127
-165
No files matched your search
@@ -169,4 +169,42 @@ check("the live line is what the agent is doing, not the CLI around it", () => {
|
||||
assert(latestActivityLine(["│ > │", " ", "? for shortcuts"]) === null, "chrome became a line");
|
||||
});
|
||||
|
||||
check("a redraw in place is the last frame, not every frame glued together", () => {
|
||||
// 2026-10-07, a phone: the screen read "Actioning…●✢4*✶75✻ ✻Actioning…5✻…"
|
||||
// because the spinner's CR / cursor-up / erase-line moves were deleted
|
||||
// instead of applied.
|
||||
const frames = ["✢", "✶", "✻", "●"]
|
||||
.map((g, i) => `\r\x1b[2K${g} Actioning… (${i + 1}s · esc to interrupt)`)
|
||||
.join("");
|
||||
const raw =
|
||||
"Running 1 shell command…\r\n ⎿ $ cd /tmp && sed -n 71,72p i18n.js\r\n" +
|
||||
frames +
|
||||
"\r\n\x1b[1A\x1b[2K\x1b[G✶ Actioning… (3m 37s · ↓ 6.6k tokens)\r\n ⎿ Tip: Use /btw to ask\r\n" +
|
||||
"──────────\r\n› \r\n──────────\r\n⏵⏵ auto mode on (shift+tab to cycle) · esc to interrupt\r\n";
|
||||
const tail = tailForWatch(raw);
|
||||
assert(
|
||||
tail.filter((l) => l.includes("Actioning")).length === 1,
|
||||
`frames piled up: ${JSON.stringify(tail)}`,
|
||||
);
|
||||
assert(
|
||||
tail.some((l) => l.includes("3m 37s")),
|
||||
"kept a stale frame, not the last one",
|
||||
);
|
||||
assert(
|
||||
latestActivityLine(tail) === "Running 1 shell command…",
|
||||
`the headline is the spinner or chrome: ${latestActivityLine(tail)}`,
|
||||
);
|
||||
});
|
||||
|
||||
check("a tool call reads as a sentence", () => {
|
||||
assert(
|
||||
latestActivityLine(["⏺ Write(src/app/page.tsx)"]) === "Writing src/app/page.tsx",
|
||||
"raw call",
|
||||
);
|
||||
assert(
|
||||
latestActivityLine(["⏺ Read(i18n.js)", " ⎿ Read 72 lines"]) === "Reading i18n.js",
|
||||
"picked the detail",
|
||||
);
|
||||
});
|
||||
|
||||
console.log(`\n✓ project-watch: ${passed} passed`);
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
isQuotaDeath,
|
||||
nextActionForWork,
|
||||
presentTerminalRun,
|
||||
SESSION_LOST_LABEL,
|
||||
railStatusLines,
|
||||
WORKING_NEXT_ACTION,
|
||||
} from "@/lib/terminal-run-view";
|
||||
@@ -143,13 +144,19 @@ check("an open run never claims generation after its PTY is gone", () => {
|
||||
projectKey: "substrata",
|
||||
work: work(),
|
||||
});
|
||||
assert.deepEqual(presentTerminalRun(view, false), {
|
||||
label: "Session ended",
|
||||
stepSummary: "No live terminal session",
|
||||
nextAction:
|
||||
"The run record is still open, but its agent terminal is gone. Start this project again or return to Feedback and Retry.",
|
||||
});
|
||||
assert.equal(presentTerminalRun(view, true).label, "Working · 2 min");
|
||||
const lost = presentTerminalRun(view, "stalled");
|
||||
assert.equal(lost.label, SESSION_LOST_LABEL);
|
||||
assert.doesNotMatch(lost.label, /working|generating/i);
|
||||
assert.match(lost.nextAction, /open the project/i, "names the way forward");
|
||||
assert.equal(presentTerminalRun(view, "live").label, "Working · 2 min");
|
||||
});
|
||||
|
||||
check("attaching to a session is not the session being gone", () => {
|
||||
// 2026-10-07: Terminal opened on a phone said "Session ended — its agent
|
||||
// terminal is gone" while it was still connecting to a healthy session.
|
||||
const view = buildTerminalRunView({ runId: "run-1", projectKey: "farmacia", work: work() });
|
||||
assert.equal(presentTerminalRun(view, "connecting").label, "Working · 2 min");
|
||||
assert.equal(presentTerminalRun(view, "idle").label, "Working · 2 min");
|
||||
});
|
||||
|
||||
check("empty Terminal explains session location and project routing", () => {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Watch narrates the build by itself (lib/watch-narration).
|
||||
*
|
||||
* What has to stay true for the narration to be worth showing:
|
||||
* - an answer with no headline shows nothing, never a blank card;
|
||||
* - "null"-ish strings from a model are absent, not printed;
|
||||
* - it asks again only when the screen moved and 30s have passed;
|
||||
* - a repeated headline refreshes the current beat instead of stacking.
|
||||
*
|
||||
* Run: npx tsx scripts/test/watch-narration.ts
|
||||
*/
|
||||
import {
|
||||
NARRATE_HISTORY,
|
||||
NARRATE_MIN_INTERVAL_MS,
|
||||
narrationPrompt,
|
||||
parseNarration,
|
||||
pushNarration,
|
||||
shouldNarrate,
|
||||
} from "@/lib/watch-narration";
|
||||
|
||||
function assert(condition: unknown, message: string): asserts condition {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
let passed = 0;
|
||||
const check = (label: string, fn: () => void) => {
|
||||
fn();
|
||||
passed += 1;
|
||||
console.log(` ✓ ${label}`);
|
||||
};
|
||||
|
||||
check("reads the model's JSON, fenced or not, and drops null-ish fields", () => {
|
||||
const n = parseNarration(
|
||||
'```json\n{"headline":"Adding the Team page in three languages","detail":"null","needsYou":null}\n```',
|
||||
);
|
||||
assert(n?.headline === "Adding the Team page in three languages", `headline: ${n?.headline}`);
|
||||
assert(n.detail === null, "printed the word null");
|
||||
assert(n.needsYou === null, "invented a need");
|
||||
});
|
||||
|
||||
check("no headline, no narration", () => {
|
||||
assert(parseNarration('{"headline":"","detail":"x"}') === null, "blank headline shown");
|
||||
assert(parseNarration("I cannot see the screen.") === null, "prose shown as a headline");
|
||||
});
|
||||
|
||||
check("long answers are cut, not overflowing a phone", () => {
|
||||
const n = parseNarration(JSON.stringify({ headline: "x".repeat(300) }));
|
||||
assert(n !== null && n.headline.length <= 90, `headline ${n?.headline.length} chars`);
|
||||
});
|
||||
|
||||
check("asks first, then only when the screen moved and 30s passed", () => {
|
||||
const base = { screenKey: "a", lastKey: null, lastAt: null, now: 0, inFlight: false };
|
||||
assert(shouldNarrate(base), "did not ask first");
|
||||
assert(!shouldNarrate({ ...base, inFlight: true }), "asked twice at once");
|
||||
const after = { screenKey: "b", lastKey: "a", lastAt: 0, inFlight: false };
|
||||
assert(!shouldNarrate({ ...after, now: NARRATE_MIN_INTERVAL_MS - 1 }), "asked too soon");
|
||||
assert(shouldNarrate({ ...after, now: NARRATE_MIN_INTERVAL_MS }), "never asked again");
|
||||
assert(
|
||||
!shouldNarrate({ ...after, screenKey: "a", now: NARRATE_MIN_INTERVAL_MS * 5 }),
|
||||
"asked about a screen that had not moved",
|
||||
);
|
||||
});
|
||||
|
||||
check("the story grows by new headlines only, and stays short", () => {
|
||||
const beat = (headline: string, at: number) => ({
|
||||
narration: { headline, detail: null, needsYou: null },
|
||||
at,
|
||||
});
|
||||
let story = pushNarration([], beat("Setting up the project", 1));
|
||||
story = pushNarration(story, beat("Setting up the project", 2));
|
||||
assert(story.length === 1 && story[0]!.at === 2, "a repeat stacked");
|
||||
for (let i = 0; i < 20; i++) story = pushNarration(story, beat(`Step ${i}`, 10 + i));
|
||||
assert(story.length === NARRATE_HISTORY + 1, `kept ${story.length}`);
|
||||
assert(story.at(-1)!.narration.headline === "Step 19", "lost the newest");
|
||||
});
|
||||
|
||||
check("the prompt carries what was asked and the newest screen", () => {
|
||||
const p = narrationPrompt({
|
||||
project: "farmaciadelparco",
|
||||
asked: "Build the pharmacy site",
|
||||
previous: null,
|
||||
screen: Array.from({ length: 100 }, (_, i) => `line ${i}`),
|
||||
});
|
||||
assert(p.includes("farmaciadelparco") && p.includes("Build the pharmacy site"), "lost context");
|
||||
assert(p.includes("line 99") && !p.includes("line 0\n"), "sent the oldest screen");
|
||||
});
|
||||
|
||||
console.log(`\n✓ watch-narration: ${passed} passed`);
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { promptHistory } from "@/db/schema/prompt-history";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { jsonError, jsonOk, readIdParam } from "@/lib/api/route-helpers";
|
||||
import { getProjectCore } from "@/db/queries/projects";
|
||||
import { getProjectOrchestrationRuns } from "@/db/queries/orchestration-runs";
|
||||
import { callTextDetailed } from "@/lib/groq";
|
||||
import { checkAiBudget, recordAiSpend } from "@/lib/ai-budget/gate";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { HTTP_TIMEOUT_LONG_MS, RATE_LIMIT_WINDOW_LONG_MS } from "@/lib/constants/time";
|
||||
import {
|
||||
NARRATE_MAX_LINE_CHARS,
|
||||
NARRATE_MAX_LINES,
|
||||
NARRATION_SYSTEM,
|
||||
narrationPrompt,
|
||||
parseNarration,
|
||||
} from "@/lib/watch-narration";
|
||||
|
||||
/**
|
||||
* One plain-language headline for what the agent is doing now, read from the
|
||||
* screen the Watch page already peeked. See lib/watch-narration.
|
||||
*
|
||||
* Degrades, never errors at the person: out of budget, rate-limited or a model
|
||||
* that answered nothing readable all return `narration: null`, and the page
|
||||
* keeps showing the activity line it already had.
|
||||
*/
|
||||
const Body = z.object({
|
||||
screen: z.array(z.string().max(NARRATE_MAX_LINE_CHARS * 2)).max(NARRATE_MAX_LINES * 2),
|
||||
previous: z.string().max(200).nullable().optional(),
|
||||
});
|
||||
|
||||
/** ~One every 30s for two hours of watching, per person. */
|
||||
const NARRATIONS_PER_HOUR = 240;
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) return jsonError("Unauthorized", 401);
|
||||
const idOrResp = await readIdParam(params);
|
||||
if (idOrResp instanceof NextResponse) return idOrResp;
|
||||
const parsed = Body.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) return jsonError("Invalid screen", 400);
|
||||
|
||||
const project = await getProjectCore(userId, idOrResp);
|
||||
if (!project) return jsonError("Not found", 404);
|
||||
|
||||
const quiet = jsonOk({ narration: null });
|
||||
if (!checkRateLimit(`watch-narrate:${userId}`, NARRATIONS_PER_HOUR, RATE_LIMIT_WINDOW_LONG_MS))
|
||||
return quiet;
|
||||
if (!(await checkAiBudget(userId)).allowed) return quiet;
|
||||
|
||||
const run = (await getProjectOrchestrationRuns(userId, idOrResp, 1))[0] ?? null;
|
||||
const asked = run
|
||||
? await db
|
||||
.select({ custom: promptHistory.customPrompt, resolved: promptHistory.resolvedPrompt })
|
||||
.from(promptHistory)
|
||||
.where(and(eq(promptHistory.userId, userId), eq(promptHistory.runId, run.id)))
|
||||
.orderBy(desc(promptHistory.dispatchedAt))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0]?.custom ?? rows[0]?.resolved ?? null)
|
||||
: null;
|
||||
|
||||
try {
|
||||
const answered = await callTextDetailed(
|
||||
narrationPrompt({
|
||||
project: project.name,
|
||||
asked,
|
||||
previous: parsed.data.previous ?? null,
|
||||
screen: parsed.data.screen,
|
||||
}),
|
||||
{
|
||||
feature: "watch-narrate",
|
||||
systemPrompt: NARRATION_SYSTEM,
|
||||
maxTokens: 300,
|
||||
temperature: 0.2,
|
||||
timeoutMs: HTTP_TIMEOUT_LONG_MS,
|
||||
},
|
||||
);
|
||||
void recordAiSpend(userId, answered.tokens);
|
||||
return jsonOk(
|
||||
{ narration: parseNarration(answered.text) },
|
||||
{ headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("[watch-narrate]", e instanceof Error ? e.message : e);
|
||||
return quiet;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import { db } from "@/db";
|
||||
import { promptHistory } from "@/db/schema/prompt-history";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { readIdParam } from "@/lib/api/route-helpers";
|
||||
import { getProjectCore } from "@/db/queries/projects";
|
||||
import { getProjectAutopilotOverride, getProjectCore } from "@/db/queries/projects";
|
||||
import { getBeaconSettings } from "@/db/queries/beacon-settings";
|
||||
import {
|
||||
getLatestRunForProjectKey,
|
||||
getProjectOrchestrationRuns,
|
||||
@@ -89,7 +90,11 @@ export async function GET(_req: NextRequest, { params }: { params: Promise<{ id:
|
||||
});
|
||||
|
||||
const tab = run.payload?.sessionTab ?? project.name;
|
||||
const up = await getUserProjectByEntityId(userId, idOrResp).catch(() => null);
|
||||
const [up, autopilotOverride, beacon] = await Promise.all([
|
||||
getUserProjectByEntityId(userId, idOrResp).catch(() => null),
|
||||
getProjectAutopilotOverride(userId, project.name).catch(() => null),
|
||||
getBeaconSettings(userId),
|
||||
]);
|
||||
const failed = Boolean(run.finishedAt) && (view.phase === "failed" || view.stalled);
|
||||
return NextResponse.json(
|
||||
{
|
||||
@@ -127,6 +132,9 @@ export async function GET(_req: NextRequest, { params }: { params: Promise<{ id:
|
||||
// The one tap: a finished run that did not deliver can be sent again.
|
||||
canRetry: failed,
|
||||
userProjectId: up?.id ?? null,
|
||||
// Steer or let go: Watch offers the project's real autopilot switch
|
||||
// beside the box that steers it, not a description of either.
|
||||
autopilot: { override: autopilotOverride, inherited: beacon.auto_inject_mode },
|
||||
terminalHref: fleetSurfaceHref("terminal", tab, undefined, run.id),
|
||||
},
|
||||
{ headers: { "Cache-Control": "no-store" } },
|
||||
|
||||
+58
-2
@@ -4461,8 +4461,64 @@
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
.ui-watch-tail {
|
||||
@apply mt-1 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-surface-raised p-3 font-mono text-xs leading-relaxed text-text-secondary;
|
||||
|
||||
/* Watch's live card: Loki narrating the build, the story so far, and the
|
||||
two ways to drive it (steer / autopilot). The headline rises in when it
|
||||
changes, so a new step reads as news rather than a silent text swap. */
|
||||
.ui-watch-live {
|
||||
@apply space-y-4 rounded-2xl border border-border-default bg-surface-base p-4 sm:p-5;
|
||||
}
|
||||
.ui-watch-live-kicker {
|
||||
@apply flex items-center gap-2 text-xs font-medium text-text-secondary;
|
||||
}
|
||||
.ui-watch-live-dot {
|
||||
@apply relative inline-flex h-2 w-2 shrink-0 rounded-full;
|
||||
background-color: var(--status-positive);
|
||||
}
|
||||
.ui-watch-live-dot::after {
|
||||
content: "";
|
||||
@apply absolute inset-0 rounded-full;
|
||||
background-color: var(--status-positive);
|
||||
animation: ui-watch-ping 1.6s cubic-bezier(0, 0, 0.2, 1) infinite;
|
||||
}
|
||||
.ui-watch-headline {
|
||||
@apply text-lg font-semibold leading-snug text-text-primary sm:text-xl;
|
||||
animation: ui-watch-rise 0.45s ease-out;
|
||||
}
|
||||
.ui-watch-story {
|
||||
@apply space-y-1.5 border-t border-border-subtle pt-3;
|
||||
}
|
||||
.ui-watch-story-item {
|
||||
@apply flex items-start gap-2 text-sm text-text-secondary;
|
||||
}
|
||||
.ui-watch-steer {
|
||||
@apply flex items-center gap-2 rounded-xl border border-border-default bg-surface-raised p-1.5 pl-3;
|
||||
}
|
||||
.ui-watch-steer-input {
|
||||
@apply min-h-10 min-w-0 flex-1 bg-transparent text-base text-text-primary outline-none placeholder:text-text-muted sm:text-sm;
|
||||
}
|
||||
@keyframes ui-watch-rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
@keyframes ui-watch-ping {
|
||||
75%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: scale(2.4);
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ui-watch-headline,
|
||||
.ui-watch-live-dot::after {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Exactly three lines of relaxed text (3 × 1.625em), for blocks whose child
|
||||
|
||||
@@ -313,11 +313,13 @@ export function ProjectKickoff({
|
||||
</ol>
|
||||
)}
|
||||
|
||||
{/* One quiet line under the steps, aligned with their labels. It was a
|
||||
four-line paragraph with its own spinner — a second "working"
|
||||
beside the step that is already spinning, hanging off its own
|
||||
left edge (operator, 2026-10-07). */}
|
||||
{running && (
|
||||
<p className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden="true" />
|
||||
Working — usually a minute or two. It runs on Loki, not in this page: lock your phone,
|
||||
close the tab or open Terminal — it keeps going and is here when you come back.
|
||||
<p className="pl-6.5 text-xs text-text-tertiary">
|
||||
Runs on Loki — you can close this page; it keeps going.
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -348,7 +350,13 @@ function StepIcon({ state }: { state: KickoffStepState }) {
|
||||
return <Check className="h-4 w-4 shrink-0 text-status-positive" aria-hidden="true" />;
|
||||
if (state === "failed")
|
||||
return <AlertCircle className="h-4 w-4 shrink-0 text-status-negative" aria-hidden="true" />;
|
||||
return <span className="ui-dot ui-dot-neutral mx-1.5 shrink-0" aria-hidden="true" />;
|
||||
// Same 16px box as the icons, so a pending step's label lines up with the
|
||||
// rest instead of sitting a few pixels off.
|
||||
return (
|
||||
<span className="flex h-4 w-4 shrink-0 items-center justify-center" aria-hidden="true">
|
||||
<span className="ui-dot ui-dot-neutral" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,10 +14,11 @@
|
||||
* takes by itself when a builder refuses a run.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2, MessagesSquare, RotateCcw, SquareTerminal } from "lucide-react";
|
||||
import { Loader2, MessagesSquare, RotateCcw } from "lucide-react";
|
||||
import { withTerminalView } from "@/lib/fleet-context";
|
||||
import { timeAgo } from "@/lib/dates";
|
||||
import { postJson } from "@/lib/api/fetch";
|
||||
import { peekTabOnce } from "@/lib/peek-tab-client";
|
||||
import {
|
||||
@@ -29,13 +30,9 @@ import {
|
||||
import { KICKOFF_STEP_LABEL } from "@/lib/project-kickoff";
|
||||
import type { KickoffRunState } from "@/lib/kickoff/orchestrate";
|
||||
import { ProviderSwitch } from "@/components/agents/ProviderSwitch";
|
||||
import {
|
||||
ActivityGroup,
|
||||
AssistantMessage,
|
||||
ScreenFold,
|
||||
TypingDots,
|
||||
UserMessage,
|
||||
} from "./project-watch-parts";
|
||||
import type { AutoInjectMode } from "@/config/beacon";
|
||||
import { ProjectWatchLive } from "./ProjectWatchLive";
|
||||
import { ActivityGroup, AssistantMessage, TypingDots, UserMessage } from "./project-watch-parts";
|
||||
|
||||
type WatchPayload = {
|
||||
project: { name: string };
|
||||
@@ -64,6 +61,7 @@ type WatchPayload = {
|
||||
userProjectId?: string | null;
|
||||
tab?: string;
|
||||
terminalHref?: string;
|
||||
autopilot?: { override: AutoInjectMode | null; inherited: AutoInjectMode };
|
||||
};
|
||||
|
||||
const LIVE_POLL_MS = 4_000;
|
||||
@@ -82,7 +80,6 @@ export function ProjectWatch({
|
||||
const [tail, setTail] = useState<string[] | null>(null);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
const [retryError, setRetryError] = useState<string | null>(null);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const live = Boolean(data?.run?.live || data?.kickoff?.running || retrying);
|
||||
const working = data?.status?.phase === "working" && data.status.terminalReady;
|
||||
@@ -131,11 +128,8 @@ export function ProjectWatch({
|
||||
};
|
||||
}, [working, tab]);
|
||||
|
||||
// Follow the conversation as it grows.
|
||||
const itemCount = data?.items.length ?? 0;
|
||||
useEffect(() => {
|
||||
if (live) bottomRef.current?.scrollIntoView({ block: "end", behavior: "smooth" });
|
||||
}, [itemCount, live]);
|
||||
// No auto-scroll: while it works, the live card at the top IS the news —
|
||||
// following the thread down used to scroll it out of view.
|
||||
|
||||
const retry = (agent?: string) => {
|
||||
setRetrying(true);
|
||||
@@ -193,6 +187,19 @@ export function ProjectWatch({
|
||||
<div className="space-y-6" aria-live="polite">
|
||||
{p.kickoff?.running && <SetupMessage kickoff={p.kickoff} />}
|
||||
|
||||
{p.run && status && runLive && !failed && !status.stalled && (
|
||||
<ProjectWatchLive
|
||||
projectId={projectId}
|
||||
provider={provider?.currentLabel ?? "The agent"}
|
||||
startedAt={p.run.startedAt}
|
||||
screen={working ? tail : null}
|
||||
fallbackHeadline={(working && tail && latestActivityLine(tail)) || status.label}
|
||||
tab={status.terminalReady ? (p.tab ?? null) : null}
|
||||
terminalHref={status.terminalReady ? (p.terminalHref ?? null) : null}
|
||||
autopilot={p.autopilot ?? null}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!p.run && !p.kickoff?.running && (
|
||||
<AssistantMessage who="Loki">
|
||||
<p>Nothing is running for this project yet.</p>
|
||||
@@ -225,10 +232,19 @@ export function ProjectWatch({
|
||||
)}
|
||||
|
||||
{p.run && status && (
|
||||
// The live message below already says "Working · 1 min" with its
|
||||
// own dots. Saying it here too, with a second spinner, put the same
|
||||
// fact on screen three times (operator, 2026-10-07): this line is
|
||||
// the run's history, so it says when it started.
|
||||
<ActivityGroup
|
||||
steps={steps}
|
||||
live={runLive && !status.stalled}
|
||||
summary={failed ? "Stopped" : runLive ? status.label : "Finished"}
|
||||
summary={
|
||||
failed
|
||||
? "Stopped"
|
||||
: runLive && p.run
|
||||
? `Started ${timeAgo(new Date(p.run.startedAt).getTime())}`
|
||||
: "Finished"
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -251,31 +267,14 @@ export function ProjectWatch({
|
||||
) : null,
|
||||
)}
|
||||
|
||||
{p.run && status && runLive && !failed && (
|
||||
<AssistantMessage who={provider?.currentLabel ?? "Agent"} agent>
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="pt-2.5">
|
||||
<TypingDots />
|
||||
</span>
|
||||
<span className="min-w-0 text-text-secondary wrap-anywhere">
|
||||
{status.stalled
|
||||
? status.nextAction
|
||||
: ((working && tail && latestActivityLine(tail)) ?? status.label)}
|
||||
</span>
|
||||
</div>
|
||||
{working && tail && tail.length > 0 && <ScreenFold lines={tail} />}
|
||||
{p.run && status && runLive && !failed && status.stalled && (
|
||||
<AssistantMessage who="Loki">
|
||||
<p>{status.nextAction}</p>
|
||||
{p.terminalHref && status.terminalReady && (
|
||||
// The agent's own conversation and its raw terminal are one page
|
||||
// with a switch; each link opens it on the view it names.
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1">
|
||||
<Link href={withTerminalView(p.terminalHref, "chat")} className="ui-chat-link">
|
||||
<MessagesSquare className="h-3.5 w-3.5" aria-hidden="true" /> Follow{" "}
|
||||
{provider?.currentLabel ?? "the agent"} live
|
||||
</Link>
|
||||
<Link href={withTerminalView(p.terminalHref, "terminal")} className="ui-chat-link">
|
||||
<SquareTerminal className="h-3.5 w-3.5" aria-hidden="true" /> Open the full terminal
|
||||
</Link>
|
||||
</div>
|
||||
<Link href={withTerminalView(p.terminalHref, "chat")} className="ui-chat-link">
|
||||
<MessagesSquare className="h-3.5 w-3.5" aria-hidden="true" /> See where{" "}
|
||||
{provider?.currentLabel ?? "the agent"} stopped
|
||||
</Link>
|
||||
)}
|
||||
</AssistantMessage>
|
||||
)}
|
||||
@@ -327,7 +326,6 @@ export function ProjectWatch({
|
||||
</p>
|
||||
</AssistantMessage>
|
||||
)}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* The top of Watch while an agent is working: Loki narrating the build in the
|
||||
* person's own terms, the story so far, and the two ways to drive it — steer
|
||||
* it with a sentence, or let it run on autopilot. Both feelings on one card:
|
||||
* you always know what is happening, and you choose how much to hold on
|
||||
* (operator, 2026-10-07: "the user always feels in control unless they choose
|
||||
* to let go … this is what makes us special").
|
||||
*
|
||||
* Narration: hooks/use-watch-narration over lib/watch-narration. Until the
|
||||
* first narration lands, the headline is the agent's own current step from
|
||||
* the screen, so the card never opens empty.
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { AlertCircle, ArrowUp, Check, Loader2, Sparkles } from "lucide-react";
|
||||
import { postJson } from "@/lib/api/fetch";
|
||||
import { timeAgo } from "@/lib/dates";
|
||||
import { withTerminalView } from "@/lib/fleet-context";
|
||||
import { useWatchNarration } from "@/hooks/use-watch-narration";
|
||||
import { ProjectAutopilotToggle } from "@/components/control/ProjectAutopilotToggle";
|
||||
import type { AutoInjectMode } from "@/config/beacon";
|
||||
|
||||
export function ProjectWatchLive({
|
||||
projectId,
|
||||
provider,
|
||||
startedAt,
|
||||
screen,
|
||||
fallbackHeadline,
|
||||
tab,
|
||||
terminalHref,
|
||||
autopilot,
|
||||
}: {
|
||||
projectId: string;
|
||||
provider: string;
|
||||
startedAt: string | null;
|
||||
/** The agent's screen as Watch last peeked it, or null before the first peek. */
|
||||
screen: string[] | null;
|
||||
/** What to say before Loki has narrated anything — the agent's own step. */
|
||||
fallbackHeadline: string;
|
||||
tab: string | null;
|
||||
terminalHref: string | null;
|
||||
autopilot: { override: AutoInjectMode | null; inherited: AutoInjectMode } | null;
|
||||
}) {
|
||||
const story = useWatchNarration(projectId, screen, true);
|
||||
const now = story.at(-1)?.narration ?? null;
|
||||
const earlier = story.slice(0, -1).reverse();
|
||||
const autopilotOn = (autopilot?.override ?? autopilot?.inherited) === "on";
|
||||
|
||||
return (
|
||||
<section className="ui-watch-live" aria-live="polite">
|
||||
<p className="ui-watch-live-kicker">
|
||||
<span className="ui-watch-live-dot" aria-hidden="true" />
|
||||
{provider} is working
|
||||
{startedAt && (
|
||||
<span className="text-text-muted">
|
||||
· started {timeAgo(new Date(startedAt).getTime())}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h2 key={now?.headline ?? fallbackHeadline} className="ui-watch-headline">
|
||||
{now?.headline ?? fallbackHeadline}
|
||||
</h2>
|
||||
{now?.detail && <p className="text-sm text-text-secondary">{now.detail}</p>}
|
||||
</div>
|
||||
|
||||
{now?.needsYou && (
|
||||
<div className="ui-callout-warning">
|
||||
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-status-warning" aria-hidden="true" />
|
||||
<div className="min-w-0 space-y-1">
|
||||
<p className="font-medium text-text-primary">It needs you</p>
|
||||
<p className="text-text-secondary">{now.needsYou}</p>
|
||||
{terminalHref && (
|
||||
<Link href={withTerminalView(terminalHref, "chat")} className="ui-chat-link">
|
||||
Answer it
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{earlier.length > 0 && (
|
||||
<ol className="ui-watch-story" aria-label="So far">
|
||||
{earlier.map((beat) => (
|
||||
<li key={`${beat.at}-${beat.narration.headline}`} className="ui-watch-story-item">
|
||||
<Check className="mt-0.5 h-4 w-4 shrink-0 text-status-positive" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1">{beat.narration.headline}</span>
|
||||
<span className="shrink-0 text-xs text-text-muted">{timeAgo(beat.at)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
{tab && <SteerBox tab={tab} />}
|
||||
|
||||
{autopilot && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-border-subtle pt-3">
|
||||
<ProjectAutopilotToggle
|
||||
projectId={projectId}
|
||||
currentOverride={autopilot.override}
|
||||
inheritedMode={autopilot.inherited}
|
||||
/>
|
||||
<p className="min-w-0 flex-1 text-xs text-text-secondary">
|
||||
{autopilotOn
|
||||
? "Autopilot is on — when this is done it picks the next step by itself."
|
||||
: "Autopilot is paused — it finishes this, then waits for you."}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{terminalHref && (
|
||||
<Link
|
||||
href={`${withTerminalView(terminalHref, "terminal")}&explain=1`}
|
||||
className="ui-chat-link"
|
||||
>
|
||||
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" /> Look closer — the agent's
|
||||
screen, explained
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** One sentence into the running session — steering without opening Terminal. */
|
||||
function SteerBox({ tab }: { tab: string }) {
|
||||
const [text, setText] = useState("");
|
||||
const [state, setState] = useState<"idle" | "sending" | "sent">("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const send = () => {
|
||||
const prompt = text.trim();
|
||||
if (!prompt || state === "sending") return;
|
||||
setState("sending");
|
||||
setError(null);
|
||||
postJson("/api/control/tab-inject", { tab, prompt })
|
||||
.then(async (res) => {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string; blocked?: boolean };
|
||||
if (!res.ok) throw new Error(body.error ?? `Could not send (HTTP ${res.status})`);
|
||||
if (body.blocked)
|
||||
throw new Error("Someone is typing in that session — try again in a moment.");
|
||||
setText("");
|
||||
setState("sent");
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
setError(e instanceof Error ? e.message : "Could not send");
|
||||
setState("idle");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<form
|
||||
className="ui-watch-steer"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
send();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
if (state === "sent") setState("idle");
|
||||
}}
|
||||
placeholder="Tell it something — “make the header green”"
|
||||
aria-label="Tell the agent something"
|
||||
maxLength={4000}
|
||||
className="ui-watch-steer-input"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!text.trim() || state === "sending"}
|
||||
className="ui-btn-primary ui-btn-icon shrink-0"
|
||||
aria-label="Send to the agent"
|
||||
>
|
||||
{state === "sending" ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<ArrowUp className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
{state === "sent" && (
|
||||
<p className="text-xs text-text-secondary">Sent — it reads it at its next step.</p>
|
||||
)}
|
||||
{error && <p className="ui-error text-xs">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { Bot, ChevronDown, Loader2, Sparkles } from "lucide-react";
|
||||
import { Bot, ChevronDown, Sparkles } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { timeAgo } from "@/lib/dates";
|
||||
import type { WatchItem } from "@/lib/project-watch";
|
||||
@@ -71,15 +71,7 @@ export function AssistantMessage({
|
||||
type Step = Extract<WatchItem, { type: "step" }>;
|
||||
|
||||
/** Every mechanical hop, folded into one line — open it for the detail. */
|
||||
export function ActivityGroup({
|
||||
steps,
|
||||
live,
|
||||
summary,
|
||||
}: {
|
||||
steps: Step[];
|
||||
live: boolean;
|
||||
summary: string;
|
||||
}) {
|
||||
export function ActivityGroup({ steps, summary }: { steps: Step[]; summary: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
if (steps.length === 0) return null;
|
||||
return (
|
||||
@@ -90,7 +82,6 @@ export function ActivityGroup({
|
||||
aria-expanded={open}
|
||||
className="ui-chat-activity"
|
||||
>
|
||||
{live && <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden="true" />}
|
||||
<span className="truncate">{summary}</span>
|
||||
<span className="shrink-0 text-text-muted">
|
||||
· {steps.length} step{steps.length === 1 ? "" : "s"}
|
||||
@@ -118,31 +109,6 @@ export function ActivityGroup({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent's raw screen, folded — the live line above already says what it
|
||||
* is doing; this is for the person who wants to see it for themselves.
|
||||
*/
|
||||
export function ScreenFold({ lines }: { lines: string[] }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
className="ui-chat-link"
|
||||
>
|
||||
{open ? "Hide screen" : "Show screen"}
|
||||
<ChevronDown
|
||||
className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-180")}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
{open && <pre className="ui-watch-tail">{lines.join("\n")}</pre>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Three breathing dots — the universal "it is typing" signal. */
|
||||
export function TypingDots() {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/modal";
|
||||
import { TERMINAL_RAIL_QUERY } from "@/config/terminal-modes";
|
||||
|
||||
/**
|
||||
* "What's going on?" — the one question a person watching an agent actually
|
||||
* has. A TUI is not readable by most people on a phone; the answer is two
|
||||
* sentences and the choices that follow — steer it, or leave it running
|
||||
* (operator, 2026-10-07).
|
||||
*
|
||||
* The Loki sheet opens on request only. It used to open by itself on phones
|
||||
* whenever the URL carried a run — every "Open the full terminal" tap — and
|
||||
* covered the session the person had just asked to see. The exception is a
|
||||
* person who asked: `?explain=1` is this question tapped on another page.
|
||||
*/
|
||||
export function useTerminalExplain(
|
||||
initialExplain: boolean,
|
||||
/** The rail can sit beside the session; the answer goes there, not a sheet. */
|
||||
railFits: boolean,
|
||||
openRail: () => void,
|
||||
) {
|
||||
const [sheetOpen, setSheetOpen] = useState(
|
||||
() =>
|
||||
initialExplain &&
|
||||
typeof window !== "undefined" &&
|
||||
!window.matchMedia(TERMINAL_RAIL_QUERY).matches,
|
||||
);
|
||||
// Each tap bumps `request`; the rail answers each value once and reports it,
|
||||
// so a sheet that remounts the rail does not ask the same question again.
|
||||
const [request, setRequest] = useState(initialExplain ? 1 : 0);
|
||||
const [answered, setAnswered] = useState(0);
|
||||
return {
|
||||
sheetOpen,
|
||||
setSheetOpen,
|
||||
pending: request > answered ? request : 0,
|
||||
onAnswered: setAnswered,
|
||||
ask: () => {
|
||||
setRequest((n) => n + 1);
|
||||
if (railFits) openRail();
|
||||
else setSheetOpen(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function TerminalExplainButton({ onClick }: { onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="ui-btn-secondary w-full shrink-0 justify-center gap-2"
|
||||
>
|
||||
<Sparkles className="h-4 w-4" aria-hidden="true" />
|
||||
What's going on?
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The Loki rail as a bottom sheet, where it cannot sit beside the session.
|
||||
* lg:hidden — on wide screens the same rail is in the split instead, and one
|
||||
* React element must never be mounted in both. */
|
||||
export function TerminalLokiSheet({
|
||||
onClose,
|
||||
children,
|
||||
}: {
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="lg:hidden">
|
||||
<Modal
|
||||
onClose={onClose}
|
||||
position="bottom-mobile"
|
||||
size="lg"
|
||||
padded={false}
|
||||
className="ui-sheet"
|
||||
>
|
||||
<div className="ui-term-loki-sheet">{children}</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState, type MutableRefObject } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from "react";
|
||||
import Link from "next/link";
|
||||
import { ArrowUpRight, Loader2, Sparkles } from "lucide-react";
|
||||
import { ChatThread } from "@bitbaum/chatkit/react";
|
||||
import { useSessionAsk } from "@/hooks/use-session-ask";
|
||||
import { ProviderSwitch } from "@/components/agents/ProviderSwitch";
|
||||
import { fleetSurfaceHref } from "@/lib/fleet-context";
|
||||
import { presentTerminalRun, railStatusLines, type TerminalRunView } from "@/lib/terminal-run-view";
|
||||
import {
|
||||
presentTerminalRun,
|
||||
railStatusLines,
|
||||
SESSION_LOST_LABEL,
|
||||
type TerminalPtyState,
|
||||
type TerminalRunView,
|
||||
} from "@/lib/terminal-run-view";
|
||||
import { screenText } from "@/lib/terminal-screen";
|
||||
import {
|
||||
SUMMARY_MAX_CHARS,
|
||||
@@ -31,13 +37,20 @@ export function TerminalLokiRail({
|
||||
project,
|
||||
tab,
|
||||
runId,
|
||||
ptyLive,
|
||||
ptyState,
|
||||
projectId,
|
||||
canSwitchAgent,
|
||||
onSwitchAgent,
|
||||
readScreenRef,
|
||||
askOnly = false,
|
||||
explain,
|
||||
}: {
|
||||
/** "What's going on?" asked outside the rail (the phone button, a Watch
|
||||
* deep link). Each new `pending` value is answered once, as soon as the
|
||||
* session's screen is attached — asking before that would explain an empty
|
||||
* box — and reported back, so a sheet that remounts the rail does not ask
|
||||
* the same question again. */
|
||||
explain?: { pending: number; onAnswered: (request: number) => void };
|
||||
/** The page already has a box that writes into the session (the
|
||||
* conversation view's composer): this panel then only asks Loki, so the
|
||||
* screen never shows two composers for the same session. */
|
||||
@@ -45,7 +58,7 @@ export function TerminalLokiRail({
|
||||
project: string | null;
|
||||
tab: string | null;
|
||||
runId: string | null;
|
||||
ptyLive: boolean;
|
||||
ptyState: TerminalPtyState;
|
||||
/** user_projects id — lets the chooser exclude the agent that just died. */
|
||||
projectId: string | null;
|
||||
canSwitchAgent: boolean;
|
||||
@@ -109,13 +122,36 @@ export function TerminalLokiRail({
|
||||
const summarize = () => {
|
||||
if (!project) return;
|
||||
const screen = screenText(screenLines(), SUMMARY_MAX_CHARS);
|
||||
const run = view ? presentTerminalRun(view, ptyLive) : null;
|
||||
const run = view ? presentTerminalRun(view, ptyState) : null;
|
||||
void session.ask(summaryPrompt(project), {
|
||||
attachments: [screenAttachment(screen || "(the terminal is empty)", run)],
|
||||
shown: SUMMARY_REQUEST,
|
||||
});
|
||||
};
|
||||
|
||||
const explainRequest = explain?.pending ?? 0;
|
||||
const onExplained = explain?.onAnswered;
|
||||
const answered = useRef(0);
|
||||
useEffect(() => {
|
||||
if (!project || explainRequest <= answered.current) return;
|
||||
const go = () => {
|
||||
answered.current = explainRequest;
|
||||
summarize();
|
||||
onExplained?.(explainRequest);
|
||||
};
|
||||
if (ptyState !== "connecting") {
|
||||
go();
|
||||
return;
|
||||
}
|
||||
// Still attaching (or the conversation view, which never reports live):
|
||||
// give the screen a moment, then answer with what there is.
|
||||
const t = window.setTimeout(go, 4_000);
|
||||
return () => window.clearTimeout(t);
|
||||
// summarize reads refs and the latest view; re-running on its identity
|
||||
// would ask again on every poll.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [explainRequest, ptyState, project]);
|
||||
|
||||
if (!project) {
|
||||
return (
|
||||
<aside className="ui-term-loki">
|
||||
@@ -129,7 +165,7 @@ export function TerminalLokiRail({
|
||||
);
|
||||
}
|
||||
|
||||
const presented = view ? presentTerminalRun(view, ptyLive) : null;
|
||||
const presented = view ? presentTerminalRun(view, ptyState) : null;
|
||||
const lines = presented ? railStatusLines(presented) : { summary: null, next: null };
|
||||
const diagnostic =
|
||||
view?.stalled && view.diagnostic && view.diagnostic !== view.nextAction
|
||||
@@ -150,11 +186,14 @@ export function TerminalLokiRail({
|
||||
type="button"
|
||||
onClick={summarize}
|
||||
disabled={session.sending}
|
||||
title="Summarize what this session shows, with next steps you can send"
|
||||
title="What the agent is doing, in plain words — and what you can do next"
|
||||
aria-label="What's going on?"
|
||||
className="ui-term-pane-btn"
|
||||
>
|
||||
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
Summarize
|
||||
{/* Icon-only on the narrowest phones, where the label beside the
|
||||
run badge and the open-chat button would push the header wide. */}
|
||||
<span className="max-[400px]:sr-only">What's going on?</span>
|
||||
</button>
|
||||
<Link
|
||||
href={fleetSurfaceHref("chat", project)}
|
||||
@@ -186,6 +225,14 @@ export function TerminalLokiRail({
|
||||
<p className="text-sm font-medium text-text-primary">{lines.summary}</p>
|
||||
)}
|
||||
{lines.next && <p className="text-xs text-text-secondary">{lines.next}</p>}
|
||||
{presented?.label === SESSION_LOST_LABEL && (
|
||||
<Link
|
||||
href={fleetSurfaceHref("profile", project)}
|
||||
className="ui-btn-secondary mt-1 self-start"
|
||||
>
|
||||
Open the project
|
||||
</Link>
|
||||
)}
|
||||
{diagnostic && <p className="text-micro text-text-tertiary">{diagnostic}</p>}
|
||||
</div>
|
||||
)}
|
||||
@@ -256,7 +303,7 @@ export function TerminalLokiRail({
|
||||
defaultMode={askOnly ? "ask" : "inject"}
|
||||
ask={session}
|
||||
draft={draft}
|
||||
ptyLive={ptyLive || Boolean(view?.lastProgressAt)}
|
||||
ptyLive={ptyState === "live" || Boolean(view?.lastProgressAt)}
|
||||
density="compact"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -39,6 +39,7 @@ export function TerminalPageClient({ local }: { local: boolean }) {
|
||||
initialSource={initialSource}
|
||||
initialTab={initialTab}
|
||||
initialRunId={initialRunId}
|
||||
initialExplain={searchParams.get("explain") === "1"}
|
||||
/>
|
||||
)}
|
||||
</TerminalMobileShell>
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "@/config/terminal-modes";
|
||||
import type { TerminalContext } from "@/app/api/terminal/context/route";
|
||||
import { TerminalView } from "./TerminalView";
|
||||
import { TerminalExplainButton, TerminalLokiSheet, useTerminalExplain } from "./TerminalExplain";
|
||||
import { TerminalTabStrip } from "./TerminalTabStrip";
|
||||
import { TerminalSessionBar, TerminalSourceBar } from "./TerminalModeBar";
|
||||
import { TerminalComposer } from "./TerminalComposer";
|
||||
@@ -38,7 +39,6 @@ import { TerminalSessionSheet } from "./TerminalSessionSheet";
|
||||
import { TerminalMobileDock } from "./TerminalMobileDock";
|
||||
import { TerminalLokiRail } from "./TerminalLokiRail";
|
||||
import { baseProjectKey, isDerivedRunTab } from "@/lib/run-tab";
|
||||
import { Modal } from "@/components/ui/modal";
|
||||
import { runnerTransport } from "./terminal-transport";
|
||||
import { ClaudeChatView } from "./ClaudeChatView";
|
||||
import { TerminalOfflineActions } from "./TerminalOfflineActions";
|
||||
@@ -142,6 +142,7 @@ export function TerminalSurface({
|
||||
initialSource,
|
||||
initialTab,
|
||||
initialRunId = null,
|
||||
initialExplain = false,
|
||||
}: {
|
||||
local: boolean;
|
||||
immersive?: boolean;
|
||||
@@ -153,6 +154,9 @@ export function TerminalSurface({
|
||||
initialTab?: string | null;
|
||||
/** Same orchestration run Feedback Watch is following (`?run=`). */
|
||||
initialRunId?: string | null;
|
||||
/** `?explain=1` — arrived from a "What's going on?" tap elsewhere: open
|
||||
* Loki and answer it as soon as the session is on screen. */
|
||||
initialExplain?: boolean;
|
||||
}) {
|
||||
// "shell" — a Loki-owned bash PTY — is only offered where one can
|
||||
// actually be provisioned. On the hosted control plane it is absent rather
|
||||
@@ -356,15 +360,6 @@ export function TerminalSurface({
|
||||
const deck = useTerminalDeck();
|
||||
const keyboardInset = useKeyboardInset();
|
||||
const [sheetOpen, setSheetOpen] = useState(false);
|
||||
// Auto-open the Loki sheet only where the rail is not beside the session.
|
||||
// Reusing one React element in both the split and the modal would unmount it
|
||||
// from the visible desktop pane (the modal is lg:hidden).
|
||||
const [lokiSheetOpen, setLokiSheetOpen] = useState(
|
||||
() =>
|
||||
Boolean(initialRunId) &&
|
||||
typeof window !== "undefined" &&
|
||||
!window.matchMedia(TERMINAL_RAIL_QUERY).matches,
|
||||
);
|
||||
// The rail beside the session (lg+). Closing it hands its columns to the
|
||||
// terminal; the choice is remembered, like the input mode.
|
||||
const [railOpen, setRailOpen] = useLocalStorageState<boolean>(
|
||||
@@ -376,6 +371,7 @@ export function TerminalSurface({
|
||||
// Whether the rail can sit beside the session at this width at all. Below
|
||||
// it the rail is a sheet, and the toggle opens that instead.
|
||||
const railFits = useMediaQuery(TERMINAL_RAIL_QUERY);
|
||||
const explainer = useTerminalExplain(initialExplain, railFits, () => setRailOpen(true));
|
||||
const [liveState, setLiveState] = useState<TerminalLiveState>("connecting");
|
||||
// The attached session's rendered screen, for the rail's AI summary.
|
||||
const readScreenRef = useRef<((rows: number) => string[]) | null>(null);
|
||||
@@ -539,12 +535,13 @@ export function TerminalSurface({
|
||||
project={projectKey}
|
||||
tab={activeTab}
|
||||
runId={initialRunId}
|
||||
ptyLive={liveState === "live"}
|
||||
ptyState={liveState}
|
||||
projectId={tabContext?.projectId ?? null}
|
||||
canSwitchAgent={!agentSwitchDisabledReason}
|
||||
onSwitchAgent={(id) => void switchAgent(id)}
|
||||
readScreenRef={readScreenRef}
|
||||
askOnly={view === "chat"}
|
||||
explain={explainer}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
@@ -554,7 +551,7 @@ export function TerminalSurface({
|
||||
const railShown = Boolean(projectKey) && railOpen && railFits && !immersive;
|
||||
const toggleRail = () => {
|
||||
if (railFits) setRailOpen((open) => !open);
|
||||
else setLokiSheetOpen(true);
|
||||
else explainer.setSheetOpen(true);
|
||||
};
|
||||
const paneActions = (
|
||||
<TerminalPaneActions
|
||||
@@ -595,7 +592,7 @@ export function TerminalSurface({
|
||||
projectKey
|
||||
? () => {
|
||||
setSheetOpen(false);
|
||||
setLokiSheetOpen(true);
|
||||
explainer.setSheetOpen(true);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
@@ -790,6 +787,10 @@ export function TerminalSurface({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeTab && projectKey && !railShown && !(railFits && immersive) && (
|
||||
<TerminalExplainButton onClick={explainer.ask} />
|
||||
)}
|
||||
|
||||
{/* Desktop composers. The phone's live in the dock below, alongside the
|
||||
key deck, so there is exactly one stack of controls under the screen
|
||||
rather than a composer here and a keyboard somewhere else. While the
|
||||
@@ -821,18 +822,10 @@ export function TerminalSurface({
|
||||
)}
|
||||
|
||||
{sheet}
|
||||
{lokiSheetOpen && projectKey && (
|
||||
<div className="lg:hidden">
|
||||
<Modal
|
||||
onClose={() => setLokiSheetOpen(false)}
|
||||
position="bottom-mobile"
|
||||
size="lg"
|
||||
padded={false}
|
||||
className="ui-sheet"
|
||||
>
|
||||
<div className="ui-term-loki-sheet">{renderLokiRail()}</div>
|
||||
</Modal>
|
||||
</div>
|
||||
{explainer.sheetOpen && projectKey && (
|
||||
<TerminalLokiSheet onClose={() => explainer.setSheetOpen(false)}>
|
||||
{renderLokiRail()}
|
||||
</TerminalLokiSheet>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { postJson } from "@/lib/api/fetch";
|
||||
import {
|
||||
NARRATE_MAX_LINES,
|
||||
pushNarration,
|
||||
shouldNarrate,
|
||||
type Narration,
|
||||
} from "@/lib/watch-narration";
|
||||
|
||||
export type StoryBeat = { narration: Narration; at: number };
|
||||
|
||||
/**
|
||||
* Loki's running narration of a live build, from the screen Watch already
|
||||
* peeks. Asks only when the screen has moved and the last answer is at least
|
||||
* half a minute old (lib/watch-narration → shouldNarrate); a failed or empty
|
||||
* answer keeps the story as it was.
|
||||
*/
|
||||
export function useWatchNarration(projectId: string, screen: string[] | null, live: boolean) {
|
||||
const [story, setStory] = useState<StoryBeat[]>([]);
|
||||
const last = useRef<{ key: string | null; at: number | null; inFlight: boolean }>({
|
||||
key: null,
|
||||
at: null,
|
||||
inFlight: false,
|
||||
});
|
||||
|
||||
// Unmount only. A new screen arrives every few seconds; cancelling the
|
||||
// answer in flight each time would mean no narration ever landed.
|
||||
const mounted = useRef(true);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const screenKey = screen ? screen.slice(-NARRATE_MAX_LINES).join("\n") : "";
|
||||
const previous = story.at(-1)?.narration.headline ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!live || !screen) return;
|
||||
const now = Date.now();
|
||||
if (
|
||||
!shouldNarrate({
|
||||
screenKey,
|
||||
lastKey: last.current.key,
|
||||
lastAt: last.current.at,
|
||||
now,
|
||||
inFlight: last.current.inFlight,
|
||||
})
|
||||
)
|
||||
return;
|
||||
last.current = { key: screenKey, at: now, inFlight: true };
|
||||
postJson(`/api/projects/${projectId}/watch/narrate`, {
|
||||
screen: screen.slice(-NARRATE_MAX_LINES),
|
||||
previous,
|
||||
})
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((body: { narration?: Narration | null } | null) => {
|
||||
if (!mounted.current || !body?.narration) return;
|
||||
const beat: StoryBeat = { narration: body.narration, at: Date.now() };
|
||||
setStory((s) => pushNarration(s, beat));
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
last.current = { ...last.current, inFlight: false };
|
||||
});
|
||||
// `screen` is read through screenKey; `previous` rides along with the ask.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [screenKey, live, projectId]);
|
||||
|
||||
return story;
|
||||
}
|
||||
+202
-24
@@ -143,47 +143,225 @@ export function humanizeRunFailure(
|
||||
|
||||
// ── Live tail ────────────────────────────────────────────────────────────────
|
||||
|
||||
// CSI / OSC escape sequences and the stray control bytes a TUI leaves behind.
|
||||
const ANSI_RE =
|
||||
/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]|[\x00-\x08\x0b-\x1f\x7f]/g;
|
||||
/** Enough history for a full screen; the start of a slice may land mid-line. */
|
||||
const SCREEN_SOURCE_MAX = 200_000;
|
||||
|
||||
/**
|
||||
* Replay a terminal's raw output into the lines it actually shows.
|
||||
*
|
||||
* A peek is the PTY's byte buffer, not a picture of the screen. A coding CLI
|
||||
* redraws in place — carriage return, cursor up, erase line, write again — so
|
||||
* deleting the escape codes (what this used to do) leaves every frame of every
|
||||
* redraw concatenated: the Watch "screen" read "Actioning…●✢4*✶75✻ ✻Actioning…
|
||||
* 5✻Actioning…●✶*86✢" down a whole phone (operator, 2026-10-07). This applies
|
||||
* the moves instead of dropping them: a small cursor model that understands
|
||||
* CR, LF, backspace, tab, cursor up/down/left/right/column/position and the
|
||||
* erase-line / erase-screen sequences. Colour and mode sequences are ignored;
|
||||
* anything else unknown is skipped rather than printed.
|
||||
*/
|
||||
export function renderTerminalText(raw: string): string[] {
|
||||
let input = raw;
|
||||
if (input.length > SCREEN_SOURCE_MAX) {
|
||||
input = input.slice(-SCREEN_SOURCE_MAX);
|
||||
const nl = input.indexOf("\n");
|
||||
if (nl >= 0) input = input.slice(nl + 1);
|
||||
}
|
||||
const rows: string[][] = [[]];
|
||||
let r = 0;
|
||||
let c = 0;
|
||||
let saved: [number, number] = [0, 0];
|
||||
const row = (i: number) => {
|
||||
while (rows.length <= i) rows.push([]);
|
||||
return rows[i]!;
|
||||
};
|
||||
const put = (ch: string) => {
|
||||
const line = row(r);
|
||||
while (line.length < c) line.push(" ");
|
||||
line[c] = ch;
|
||||
c += 1;
|
||||
};
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i]!;
|
||||
if (ch === "\x1b") {
|
||||
const next = input[i + 1];
|
||||
if (next === "[") {
|
||||
let j = i + 2;
|
||||
while (j < input.length && /[0-?]/.test(input[j]!)) j++;
|
||||
while (j < input.length && /[ -/]/.test(input[j]!)) j++;
|
||||
const final = input[j];
|
||||
const params = input.slice(i + 2, j).replace(/^[?>=]/, "");
|
||||
const nums = params.split(";").map((n) => Number.parseInt(n, 10));
|
||||
const n = Number.isFinite(nums[0]) && nums[0]! > 0 ? nums[0]! : 1;
|
||||
const p0 = Number.isFinite(nums[0]) ? nums[0]! : 0;
|
||||
switch (final) {
|
||||
case "A":
|
||||
r = Math.max(0, r - n);
|
||||
break;
|
||||
case "B":
|
||||
case "E":
|
||||
r += n;
|
||||
if (final === "E") c = 0;
|
||||
break;
|
||||
case "F":
|
||||
r = Math.max(0, r - n);
|
||||
c = 0;
|
||||
break;
|
||||
case "C":
|
||||
c += n;
|
||||
break;
|
||||
case "D":
|
||||
c = Math.max(0, c - n);
|
||||
break;
|
||||
case "G":
|
||||
c = n - 1;
|
||||
break;
|
||||
case "H":
|
||||
case "f": {
|
||||
// Absolute positions are relative to the visible screen, whose
|
||||
// height a buffer does not record; anchor to the newest rows.
|
||||
const top = Math.max(0, rows.length - 40);
|
||||
r = top + n - 1;
|
||||
c = Number.isFinite(nums[1]) && nums[1]! > 0 ? nums[1]! - 1 : 0;
|
||||
break;
|
||||
}
|
||||
case "K": {
|
||||
const line = row(r);
|
||||
if (p0 === 0) line.length = Math.min(line.length, c);
|
||||
else if (p0 === 1) for (let k = 0; k <= c && k < line.length; k++) line[k] = " ";
|
||||
else line.length = 0;
|
||||
break;
|
||||
}
|
||||
case "J":
|
||||
if (p0 === 2 || p0 === 3) {
|
||||
rows.length = 0;
|
||||
rows.push([]);
|
||||
r = 0;
|
||||
c = 0;
|
||||
} else if (p0 === 0) {
|
||||
row(r).length = Math.min(row(r).length, c);
|
||||
rows.length = r + 1;
|
||||
}
|
||||
break;
|
||||
case "s":
|
||||
saved = [r, c];
|
||||
break;
|
||||
case "u":
|
||||
[r, c] = saved;
|
||||
break;
|
||||
default:
|
||||
break; // colours, modes, scroll regions: nothing to draw
|
||||
}
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
if (next === "]") {
|
||||
// OSC: up to BEL or ST.
|
||||
let j = i + 2;
|
||||
while (
|
||||
j < input.length &&
|
||||
input[j] !== "\x07" &&
|
||||
!(input[j] === "\x1b" && input[j + 1] === "\\")
|
||||
)
|
||||
j++;
|
||||
i = input[j] === "\x07" ? j : j + 1;
|
||||
continue;
|
||||
}
|
||||
if (next === "7") saved = [r, c];
|
||||
else if (next === "8") [r, c] = saved;
|
||||
// Two-byte escapes (charset selects take a third byte).
|
||||
i += next === "(" || next === ")" ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\n") {
|
||||
r += 1;
|
||||
c = 0;
|
||||
row(r);
|
||||
} else if (ch === "\r") c = 0;
|
||||
else if (ch === "\b") c = Math.max(0, c - 1);
|
||||
else if (ch === "\t") c = (Math.floor(c / 8) + 1) * 8;
|
||||
else if (ch < " " || ch === "\x7f") continue;
|
||||
else put(ch);
|
||||
}
|
||||
return rows.map((line) => line.join("").replace(/\s+$/g, ""));
|
||||
}
|
||||
|
||||
/**
|
||||
* The last few meaningful lines of an agent's screen, as plain text.
|
||||
* Box-drawing borders and blank lines are dropped: on a phone the frame is
|
||||
* noise and the words are the point.
|
||||
*/
|
||||
export function tailForWatch(screen: string, lines = 12): string[] {
|
||||
return screen
|
||||
.replace(ANSI_RE, "")
|
||||
.split(/\r?\n/)
|
||||
export function tailForWatch(screen: string, lines = 14): string[] {
|
||||
return renderTerminalText(screen)
|
||||
.map((l) => l.replace(/[│┃║╭╮╯╰─━═┌┐└┘├┤┬┴┼]+/g, " ").replace(/\s+$/g, ""))
|
||||
.filter((l) => l.trim().length > 0)
|
||||
.slice(-lines);
|
||||
}
|
||||
|
||||
// Lines a coding CLI draws around its work rather than as it: the input box,
|
||||
// key hints, permission-mode banners, model/usage footers.
|
||||
// key hints, permission-mode banners, model/usage footers, tips.
|
||||
const CHROME_LINE =
|
||||
/^\s*>|for shortcuts|esc to (interrupt|cancel)|bypass permissions|auto-accept|accept edits|shift\+tab|ctrl\+|context left|tokens? used|^\s*\?\s/i;
|
||||
/^\s*[>›❯]|for shortcuts|esc to (interrupt|cancel)|bypass permissions|auto[- ]accept|auto mode|accept edits|shift\+tab|ctrl\+|context left|tokens? used|^\s*\?\s|^\s*tip:/i;
|
||||
const LEADING_GLYPHS = /^[\s✻✽✶✳✢✦·⏺●○◐◓◑◒⎿└*•+\-⠀-⣿]+/u;
|
||||
// "✶ Actioning… (3m 37s · ↓ 6.6k tokens)": the spinner's word is a random
|
||||
// gerund ("Actioning", "Pondering") — it says THAT it works, not WHAT.
|
||||
const SPINNER_LINE = /^[A-Z][a-z]+(?:ing)?…\s*(?:\(.*\))?$/;
|
||||
// A detail under an event (" ⎿ $ cd …", a wrapped continuation).
|
||||
const DETAIL_LINE = /^\s{2,}|^\s*⎿/u;
|
||||
|
||||
const TOOL_VERB: Record<string, string> = {
|
||||
Read: "Reading",
|
||||
Write: "Writing",
|
||||
Edit: "Editing",
|
||||
MultiEdit: "Editing",
|
||||
Update: "Editing",
|
||||
Create: "Creating",
|
||||
Bash: "Running",
|
||||
Grep: "Searching for",
|
||||
Search: "Searching for",
|
||||
Glob: "Finding",
|
||||
WebFetch: "Reading",
|
||||
WebSearch: "Searching the web for",
|
||||
Task: "Delegating",
|
||||
};
|
||||
|
||||
/** "Write(src/app/page.tsx)" → "Writing src/app/page.tsx". */
|
||||
function humanizeToolCall(line: string): string {
|
||||
const m = /^([A-Z][A-Za-z]+)\((.*)\)$/.exec(line);
|
||||
if (!m) return line;
|
||||
const verb = TOOL_VERB[m[1]!];
|
||||
return verb ? `${verb} ${m[2]!.trim()}` : line;
|
||||
}
|
||||
|
||||
function cleanActivity(raw: string): string {
|
||||
return raw
|
||||
.replace(/\s*\([^)]*(esc to|tokens|\d+s)[^)]*\)\s*$/i, "")
|
||||
.replace(LEADING_GLYPHS, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The one line that says what the agent is doing right now ("Writing
|
||||
* src/app/page.tsx"), read bottom-up from the tail and cleaned of spinner
|
||||
* glyphs and "(12s · esc to interrupt)" suffixes. Watch headlines it as plain
|
||||
* text and folds the raw screen behind a tap, the way Claude and ChatGPT show
|
||||
* one live step instead of a terminal. Null when nothing readable is on screen.
|
||||
* src/app/page.tsx", "Running 1 shell command…"), read bottom-up from the
|
||||
* tail. Prefers an event headline (a line at the left edge) over its indented
|
||||
* detail, and skips the spinner's decorative word and the input chrome. Watch
|
||||
* headlines it as plain text and folds the screen behind a tap, the way
|
||||
* Claude and ChatGPT show one live step instead of a terminal. Null when
|
||||
* nothing readable is on screen.
|
||||
*/
|
||||
export function latestActivityLine(tail: string[]): string | null {
|
||||
for (let i = tail.length - 1; i >= 0; i--) {
|
||||
const raw = tail[i]!;
|
||||
const cleaned = raw
|
||||
.replace(/\s*\([^)]*(esc to|tokens|\d+s)[^)]*\)\s*$/i, "")
|
||||
.replace(LEADING_GLYPHS, "")
|
||||
.trim();
|
||||
if (!/[A-Za-z]{2}/.test(cleaned)) continue;
|
||||
if (CHROME_LINE.test(cleaned)) continue;
|
||||
return cleaned.length > 120 ? `${cleaned.slice(0, 117)}…` : cleaned;
|
||||
}
|
||||
return null;
|
||||
const pick = (allowDetail: boolean): string | null => {
|
||||
for (let i = tail.length - 1; i >= 0; i--) {
|
||||
const raw = tail[i]!;
|
||||
if (!allowDetail && DETAIL_LINE.test(raw)) continue;
|
||||
const cleaned = cleanActivity(raw);
|
||||
if (!/[A-Za-z]{2}/.test(cleaned)) continue;
|
||||
if (CHROME_LINE.test(cleaned)) continue;
|
||||
if (SPINNER_LINE.test(cleaned)) continue;
|
||||
const human = humanizeToolCall(cleaned);
|
||||
return human.length > 120 ? `${human.slice(0, 117)}…` : human;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return pick(false) ?? pick(true);
|
||||
}
|
||||
@@ -31,22 +31,35 @@ export type TerminalRunView = {
|
||||
|
||||
export type TerminalRunPresentation = Pick<TerminalRunView, "label" | "stepSummary" | "nextAction">;
|
||||
|
||||
/** What the terminal knows about its own byte stream. Mirrors
|
||||
* TerminalView's onLive states; `idle` means no session is selected. */
|
||||
export type TerminalPtyState = "live" | "connecting" | "stalled" | "idle";
|
||||
|
||||
export const SESSION_LOST_LABEL = "Not responding";
|
||||
|
||||
/** A durable run row can outlive its PTY (runner restart, crash, or manual
|
||||
* stop). The terminal knows whether bytes can actually flow, so it must not
|
||||
* repeat the run ledger's old “Working / generating” claim when no session is
|
||||
* attached. */
|
||||
* repeat the run ledger's old "Working / generating" claim when the session
|
||||
* has stopped answering.
|
||||
*
|
||||
* "Connecting" is NOT that. This used to take a boolean, and every state but
|
||||
* "live" read as gone — so opening Terminal on a phone (where the Loki sheet
|
||||
* opened on top of the session) announced "Session ended — its agent terminal
|
||||
* is gone" for the seconds it took to attach, over a session that was
|
||||
* running fine (operator, 2026-10-07). Until the stream has had its chance,
|
||||
* the ledger's word stands. */
|
||||
export function presentTerminalRun(
|
||||
view: TerminalRunView,
|
||||
ptyLive: boolean,
|
||||
pty: TerminalPtyState,
|
||||
): TerminalRunPresentation {
|
||||
if (ptyLive || view.phase !== FEEDBACK_WORK_PHASE.WORKING) {
|
||||
if (pty !== "stalled" || view.phase !== FEEDBACK_WORK_PHASE.WORKING) {
|
||||
return view;
|
||||
}
|
||||
return {
|
||||
label: "Session ended",
|
||||
stepSummary: "No live terminal session",
|
||||
label: SESSION_LOST_LABEL,
|
||||
stepSummary: "The agent's screen stopped answering",
|
||||
nextAction:
|
||||
"The run record is still open, but its agent terminal is gone. Start this project again or return to Feedback and Retry.",
|
||||
"Usually the builder restarting — it reconnects by itself. If it stays like this, open the project and send the task again.",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -17,19 +17,29 @@ export const SUMMARY_MAX_CHARS = 12_000;
|
||||
/** Lines of the answer that are actions start with this marker. */
|
||||
const ACTION_MARKER = "→";
|
||||
|
||||
export const SUMMARY_REQUEST = "Summarize this session";
|
||||
/** What the person sees as their own message — the button's words. */
|
||||
export const SUMMARY_REQUEST = "What's going on?";
|
||||
|
||||
/**
|
||||
* The instruction sent with the screen. The `→` contract is what lets the
|
||||
* panel turn each action into a one-tap inject.
|
||||
*
|
||||
* Written for the person the button is for: someone looking at a terminal on
|
||||
* a phone who cannot read it and should not have to. The answer gives them
|
||||
* both of the things the product promises — the steering wheel (the `→`
|
||||
* steps, each one tap) and permission to let go (the Autopilot line says,
|
||||
* honestly, whether it can carry on without them). "Summarize this session"
|
||||
* produced a log digest for an engineer (operator, 2026-10-07).
|
||||
*/
|
||||
export function summaryPrompt(project: string): string {
|
||||
return [
|
||||
`${SUMMARY_REQUEST} for ${project}. The attached file is the agent's terminal as it looks now.`,
|
||||
"Reply in this shape, nothing else:",
|
||||
"1. Up to three short bullets: what the agent did, what it is doing now, and anything blocked, failing or waiting on me.",
|
||||
`2. Then up to three next steps I can send the agent, one per line, each starting with "${ACTION_MARKER} " and written as the instruction itself.`,
|
||||
"Plain words, no preamble. If the screen shows nothing useful, say so in one line.",
|
||||
`What's going on with ${project}? The attached file is the coding agent's terminal as it looks right now.`,
|
||||
"Answer for someone who is not a programmer, in this shape and nothing else:",
|
||||
"1. If anything is failing, stuck or waiting on me, say that first, in one sentence, with what I need to do.",
|
||||
"2. One or two sentences: what the agent is building right now and how far along it is. Name what I will see (a page, a feature, a fix), not file names or commands, unless that is all the screen shows.",
|
||||
'3. One line starting "Autopilot: " — can it keep going without me? Either "nothing needs you, it carries on by itself" or exactly what will stop it.',
|
||||
`4. Up to three things I could tell it next, one per line, each starting with "${ACTION_MARKER} " and written as the instruction itself, the most useful first.`,
|
||||
"Short, plain, warm. No preamble, no headings. If the screen shows nothing useful, say so in one line.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Watch narrates the build by itself.
|
||||
*
|
||||
* "It should say something the user would think: wow, this is exactly what I
|
||||
* want" (operator, 2026-10-07). A terminal answers "what bytes is the agent
|
||||
* printing"; a person watching wants "what is it making for me, and do I need
|
||||
* to do anything". So while a run is live, Watch hands the agent's screen to
|
||||
* a fast model every half-minute or so and shows one plain headline — "Adding
|
||||
* the Team page in Italian, German and French" — with past headlines stacking
|
||||
* up underneath as the story of the build.
|
||||
*
|
||||
* This is the pure half: the prompt, the reading of the answer, and when a new
|
||||
* narration is worth asking for. The route (/api/projects/[id]/watch/narrate)
|
||||
* only adds auth, the AI budget and the model call.
|
||||
*/
|
||||
import { safeParseModelJson } from "@/lib/ai/model-json";
|
||||
|
||||
export type Narration = {
|
||||
/** What it is doing now, as the person would say it. ≤ 90 chars. */
|
||||
headline: string;
|
||||
/** What that means for them — one sentence, or null. */
|
||||
detail: string | null;
|
||||
/** Something only the person can answer, or null. Never invented. */
|
||||
needsYou: string | null;
|
||||
};
|
||||
|
||||
/** Screen lines sent per narration — the newest; enough for one step. */
|
||||
export const NARRATE_MAX_LINES = 40;
|
||||
export const NARRATE_MAX_LINE_CHARS = 300;
|
||||
/** Never more often than this per viewer, however busy the screen is. */
|
||||
export const NARRATE_MIN_INTERVAL_MS = 30_000;
|
||||
/** Past headlines kept on screen as "So far". */
|
||||
export const NARRATE_HISTORY = 5;
|
||||
|
||||
export const NARRATION_SYSTEM = [
|
||||
"You narrate a coding agent's work for the person who owns the project. They are not a programmer and are watching on a phone.",
|
||||
"You get: the project, what they asked for, the headline you gave last time, and the agent's terminal as it looks now.",
|
||||
'Answer with JSON only: {"headline": string, "detail": string | null, "needsYou": string | null}.',
|
||||
"headline: what the agent is doing right now, in the person's terms — the page, feature or fix they will see. Present tense, starts with a verb, at most 12 words. No file names, commands, tool names or jargon unless the screen shows nothing else.",
|
||||
"detail: one short sentence on what that means for them or what comes next. null if there is nothing worth adding.",
|
||||
"needsYou: only if the screen shows the agent asking a question, waiting for approval, or stopped on an error it cannot fix alone — then say plainly what they need to do. Otherwise null. Never invent one.",
|
||||
"If the work has not moved since the last headline, return the same headline.",
|
||||
].join("\n");
|
||||
|
||||
export function narrationPrompt(input: {
|
||||
project: string;
|
||||
asked: string | null;
|
||||
previous: string | null;
|
||||
screen: string[];
|
||||
}): string {
|
||||
const asked = (input.asked ?? "").trim();
|
||||
return [
|
||||
`Project: ${input.project}`,
|
||||
`They asked: ${asked ? asked.slice(0, 1200) : "(not recorded)"}`,
|
||||
`Last headline: ${input.previous ?? "(none yet)"}`,
|
||||
"Terminal now:",
|
||||
"```",
|
||||
...input.screen.slice(-NARRATE_MAX_LINES).map((l) => l.slice(0, NARRATE_MAX_LINE_CHARS)),
|
||||
"```",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const text = (v: unknown, max: number): string | null => {
|
||||
if (typeof v !== "string") return null;
|
||||
const t = v.replace(/\s+/g, " ").trim();
|
||||
if (!t || /^(null|none|n\/a|-)$/i.test(t)) return null;
|
||||
return t.length > max ? `${t.slice(0, max - 1)}…` : t;
|
||||
};
|
||||
|
||||
/** The model's answer, or null when it gave nothing a person should read. */
|
||||
export function parseNarration(raw: string): Narration | null {
|
||||
const json = safeParseModelJson<Record<string, unknown>>(raw);
|
||||
if (!json) return null;
|
||||
const headline = text(json.headline, 90);
|
||||
if (!headline) return null;
|
||||
return {
|
||||
headline,
|
||||
detail: text(json.detail, 200),
|
||||
needsYou: text(json.needsYou, 200),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask again only when the screen moved and the last answer is old enough —
|
||||
* a person watching for ten minutes costs ~20 small calls, not one per poll.
|
||||
*/
|
||||
export function shouldNarrate(input: {
|
||||
screenKey: string;
|
||||
lastKey: string | null;
|
||||
lastAt: number | null;
|
||||
now: number;
|
||||
inFlight: boolean;
|
||||
}): boolean {
|
||||
if (input.inFlight || !input.screenKey) return false;
|
||||
if (input.lastAt === null) return true;
|
||||
if (input.screenKey === input.lastKey) return false;
|
||||
return input.now - input.lastAt >= NARRATE_MIN_INTERVAL_MS;
|
||||
}
|
||||
|
||||
/** A new headline joins the story; a repeat only refreshes the current one. */
|
||||
export function pushNarration<T extends { narration: Narration; at: number }>(
|
||||
story: T[],
|
||||
next: T,
|
||||
): T[] {
|
||||
const last = story.at(-1);
|
||||
if (last && last.narration.headline === next.narration.headline) {
|
||||
return [...story.slice(0, -1), next];
|
||||
}
|
||||
return [...story, next].slice(-(NARRATE_HISTORY + 1));
|
||||
}
|
||||
Reference in new issue
Block a user