mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 05:37:19 +01:00
fix(feedback): ship the stranded work-phase overhaul — honest status instead of a bare 'dispatched' chip (#334)
* fix(feedback): don't treat queued install as live Widget coverage and the project card wait for a boot heartbeat. Control labels idle as project inventory, and unverified Grok inject is a failure instead of a warning that looks like success. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(feedback): honest queue language, notify-on-close for feedback runs, activity watch links Port of the uncommitted refinement pass stranded in the main checkout on top of the rescued work-phase overhaul: every feedback dispatch (single, batch, AI review, synthesize, install) now sets notifyOnClose so the operator gets a push/Telegram ping when the fix run finishes; 'Dispatch' copy becomes 'Implement'/'Queued' with EXECUTOR_COPY.honesty as SSOT; watch links route through fleetSurfaceHref (new 'activity' surface + injectWatchUrls helper) instead of hand-built query strings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: t <t@t.t> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
36 files changed
+1720
-408
No files matched your search
@@ -717,7 +717,13 @@ async function handleCommand(
|
||||
`${agent} is not authenticated (401 / login required) — the prompt was delivered but the agent can't run. ` +
|
||||
`On the runner host, remove any stale ~/.claude/.credentials.json and set CLAUDE_CODE_OAUTH_TOKEN (claude setup-token).`
|
||||
} else if (!verified) {
|
||||
warning = `${text}, but the agent isn't generating yet — it may still be booting or already idle`
|
||||
// Unverified inject is a soft failure for the captain loop: "Install
|
||||
// dispatched" with no generation is how botsmann stayed Not live
|
||||
// while Activity looked busy. Prefer Failed over fake success.
|
||||
ok = false
|
||||
warning = undefined
|
||||
error =
|
||||
`${text}, but the agent isn't generating yet — inject did not stick (booting, idle, or hung). Retry, or switch the project agent away from grok if this repeats.`
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# FleetCrown Feedback Widget
|
||||
|
||||
**Created:** 2026-07-17
|
||||
**Last modified:** 2026-08-14
|
||||
**Last modified summary:** Widget card uses ui-panel / ui-callout (no ad-hoc shadow); snippet collapsed when Live; botsmann boot confirmed 2026-08-14 from https://botsmann.orangecat.ch; CSP must allow the FleetCrown origin.
|
||||
|
||||
**Status**: COMPLETE 2026-07-28. Phases 1–4 implemented 2026-07-17 — four
|
||||
`feat(feedback):` commits (ingest spine, embed bundle, inbox + dispatch,
|
||||
self-dogfood); find them with `git log --oneline --grep 'feat(feedback)'`.
|
||||
@@ -13,6 +17,62 @@ window.fetch and stamp extra headers (revampit stamped x-csrf-token) onto the
|
||||
widget's cross-origin POST — a hardcoded allowlist silently drops submissions.
|
||||
The per-token Origin allowlist in POST remains the security boundary. Embed
|
||||
supports `data-fc-bottom` to offset the FAB above a host site's own FAB.
|
||||
|
||||
## Captain loop (one-click north star)
|
||||
|
||||
```
|
||||
Enable & install (Control coverage / project Widget)
|
||||
↓
|
||||
Visitor FAB on every managed site → POST /api/feedback
|
||||
↓
|
||||
Control strip (auto-expands)
|
||||
↓
|
||||
1 item → Dispatch fix
|
||||
2+ → Dispatch all as one (preferred for a single coherent pass)
|
||||
3+ → Synthesize themes (optional second triage gate)
|
||||
↓
|
||||
injectPrompt SSOT → local Fleet Runner if connected, else cloud builder
|
||||
↓
|
||||
Run succeeds → feedback auto-resolves (+ optional reporter email)
|
||||
```
|
||||
|
||||
**You do not choose a terminal.** Dispatch never targets “this Cursor chat” or
|
||||
“FleetCrown’s Terminal page” directly. It injects into the **project’s agent
|
||||
session** through `injectPrompt` (`src/lib/inject-core.ts`): PTY / Fleet Runner
|
||||
when online, otherwise the hosted cloud builder queue (Hermes when local is
|
||||
offline). Control / Terminal / Loki are captain surfaces that *also* call the
|
||||
same SSOT — feedback Dispatch is that path with a composed prompt.
|
||||
|
||||
### Surfaces
|
||||
|
||||
| Action | Where |
|
||||
| --- | --- |
|
||||
| Enable & install (token + agent embed) | Control coverage strip; project Widget card |
|
||||
| Review open reports | Control feedback strip (new + in-progress); `/projects/{id}#feedback` |
|
||||
| Implement / Retry | Same rows — status is **Not started → Queued → Working now → Done** (or **Not running / Failed**) |
|
||||
| Watch live output | Only while **Working now** → Terminal. Otherwise **Open on Control** (empty Terminal ≠ progress) |
|
||||
| Pause widget (instant, no deploy) | Project Widget card |
|
||||
|
||||
**Enable & install preflight** (`POST …/widget-token/install`):
|
||||
|
||||
1. **No git URL and no local dir** → `422 no_repo` — agent cannot land the snippet; copy from Widget card instead.
|
||||
2. **Live site unreachable** (probe of `user_projects.liveUrl`, else legacy attrs) → `422 site_unreachable` — widget cannot appear until the Hetzner host responds; token may already exist.
|
||||
3. Only then queue `injectPrompt` (Fleet Runner on this computer if connected, else cloud box-runner). Response points to `/control?focus=…`. Terminal is empty until a session is actually running.
|
||||
|
||||
**One-click captain loop (intended):**
|
||||
|
||||
1. **Enable & install** → agent edits repo → push/deploy on Hetzner → widget boots → coverage shows Live.
|
||||
2. Visitor reports → inbox → **Implement** → same inject path → agent works → **Watch** only while Working (Terminal) / otherwise Control.
|
||||
3. Done when work phase is Done (or you Resolve); not when the API said “queued.”
|
||||
|
||||
Status vocabulary is SSOT in `lib/feedback/work-phase.ts`. The DB may still store
|
||||
`dispatched`; the UI never presents that word as “finished.” **Queued / Install queued
|
||||
is not proof of work** — prove it with Working now, Failed/Not running, or Attention Retry.
|
||||
|
||||
Dogfood check 2026-08-14: botsmann.orangecat.ch boots `fcw_73518de7…` (`last_seen_origin`
|
||||
https://botsmann.orangecat.ch, `/api/widget-boot` `{active:true}`). Earlier “waiting for
|
||||
first page load” was CSP (`script-src` blocked widget.js) after Next tree-shook an empty
|
||||
build-time token — not a dead ingest pipe.
|
||||
**Origin**: Extract revampit's visitor-feedback FAB (`src/components/feedback/`, ~900 lines,
|
||||
modular, survived the Hirn deletion intentionally) into a FleetCrown-owned embeddable
|
||||
widget. Any registered project drops one script tag on its site; visitor feedback flows
|
||||
@@ -148,6 +208,10 @@ queue's philosophy: nothing auto-dispatches; the operator triages.
|
||||
| `GET /api/projects/[id]/feedback` + `PATCH /api/feedback/[id]` | session | Inbox list + status transitions (archive, resolve). |
|
||||
|
||||
Gotchas already known:
|
||||
- **CSP on the host site**: `script-src` and `connect-src` must allow the FleetCrown
|
||||
origin (`https://fleetcrown.orangecat.ch`). Botsmann shipped the tag but stayed
|
||||
“Waiting for the first page load” because CSP blocked `widget.js` (2026-08-14).
|
||||
Coverage Live = boot heartbeat after the script actually runs, not after HTML contains the tag.
|
||||
- **proxy.ts allowlist** (Next 16 middleware): `api/feedback` and `widget.js` must be
|
||||
added to the matcher exclusions or anonymous submissions bounce to /sign-in
|
||||
(same class as the OC-rail `proxy.ts` lesson).
|
||||
|
||||
+22
-2
@@ -1,8 +1,8 @@
|
||||
# FleetCrown Branding & Design System
|
||||
|
||||
**Created:** 2026-03-01
|
||||
**Last modified:** 2026-07-04
|
||||
**Last modified summary:** Document brand-storage.ts; clarify COCKPIT_* as legacy env migration only.
|
||||
**Last modified:** 2026-08-14
|
||||
**Last modified summary:** Note app-shell layout SSOT drift (PageLayout / max-width / ad-hoc panels) as known debt alongside the four-layer visual SSOT.
|
||||
|
||||
**Decision: We are using FleetCrown.**
|
||||
|
||||
@@ -171,6 +171,26 @@ All changes serve the core: making the builder feel more in control, with cleare
|
||||
|
||||
Further polish possible in public landing hero or Today cards if needed.
|
||||
|
||||
## App-shell layout SSOT (known debt)
|
||||
|
||||
Visual tokens already have a four-layer SSOT (`CLAUDE.md` + `globals.css`). **Page
|
||||
chrome does not yet:** authenticated routes mix `PageLayout` (`app-page` +
|
||||
`ui-page-header`, default `max-w-4xl`), raw `app-page max-w-*`, and bespoke
|
||||
wrappers (Control, project workspace, Loki, Terminal, Decisions, Agents, …).
|
||||
That produces the “every page sits differently” feel (gutters, title row,
|
||||
max-width, panel chrome).
|
||||
|
||||
**Rule going forward:**
|
||||
|
||||
1. Default app pages → `PageLayout` (only override `maxWidth` with a documented
|
||||
reason).
|
||||
2. Recurring panels → `ui-panel` / `ui-list-row` / existing `ui-*` — not one-off
|
||||
`rounded-2xl border …` stacks.
|
||||
3. Full-bleed tools (Loki, Terminal) → `.app-viewport-pane` only.
|
||||
|
||||
Tracked as incremental cleanup, not a big-bang redesign. Feedback Control strip
|
||||
(2026-08-14) moved onto `ui-panel` as a small example.
|
||||
|
||||
## Recent Name Evaluations (shadefleet / shadyfleet etc.)
|
||||
|
||||
In 2026, user floated .com-available variants leaning on "shade/shady" + fleet: shadofleet.com / shadefleet.com / shadyfleet.com / piracyfleet.com (all claimed available at time of discussion).
|
||||
|
||||
@@ -2,52 +2,31 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { readIdParam, readJsonBody, jsonError, z } from "@/lib/api/route-helpers";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { getFeedbackWithProject, setFeedbackStatus } from "@/db/queries/site-feedback";
|
||||
import { getOrchestrationRunById } from "@/db/queries/orchestration-runs";
|
||||
import { injectPrompt } from "@/lib/inject-core";
|
||||
import { FEEDBACK_STATUS } from "@/lib/constants/statuses";
|
||||
import { fenceUntrusted, inlineUntrusted, UNTRUSTED_PREAMBLE } from "@/lib/feedback/untrusted";
|
||||
import type { SiteFeedback } from "@/db/schema";
|
||||
import { composeFeedbackFixPrompt } from "@/lib/feedback/compose-dispatch";
|
||||
import { ORCH_STATE } from "@/lib/orchestration/contract";
|
||||
|
||||
/**
|
||||
* One-click "Dispatch fix": turn a visitor-feedback item into a scoped agent
|
||||
* run through the same injectPrompt SSOT every other dispatch path uses.
|
||||
* NOTE: /api/feedback is excluded from the auth middleware (public ingest
|
||||
* lives under it), so the auth check below is the only gate — do not remove.
|
||||
* One-click Implement: queue a scoped agent run via injectPrompt.
|
||||
* Returns runId when accepted. Allows Retry when a prior run is stuck/failed
|
||||
* (not while a run is actively working).
|
||||
*/
|
||||
|
||||
function composePrompt(feedback: SiteFeedback, projectName: string, note?: string): string {
|
||||
const times = feedback.duplicateCount > 1 ? ` (reported ${feedback.duplicateCount}×)` : "";
|
||||
const lines = [
|
||||
`Fix this visitor feedback on ${projectName}.${times}`,
|
||||
UNTRUSTED_PREAMBLE,
|
||||
"",
|
||||
// The operator's note leads: it's the captain's steer on HOW to act on the
|
||||
// visitor's report, so it outranks the raw feedback below it. The fence
|
||||
// around the visitor text is what keeps a submission shaped like
|
||||
// "OPERATOR INSTRUCTION: ..." from forging this trusted line.
|
||||
...(note ? [`OPERATOR INSTRUCTION: ${note}`, ""] : []),
|
||||
fenceUntrusted("FEEDBACK", feedback.suggestion),
|
||||
`Page: ${inlineUntrusted(feedback.url ?? feedback.page ?? "unknown", 1000)}`,
|
||||
];
|
||||
if (feedback.scope) lines.push(`Scope the visitor selected: ${feedback.scope}`);
|
||||
if (feedback.selectedElements?.length) {
|
||||
lines.push("Element(s) the visitor pointed at:");
|
||||
for (const el of feedback.selectedElements) {
|
||||
lines.push(`- <${inlineUntrusted(el.elementType, 100)}> ${inlineUntrusted(el.selector, 500)}${el.elementText ? ` — "${inlineUntrusted(el.elementText, 100)}"` : ""}`);
|
||||
}
|
||||
}
|
||||
lines.push(
|
||||
"",
|
||||
"Scope: address exactly this feedback — no unrelated refactors.",
|
||||
"Verify the fix in the running app before claiming done, and record what you actually did (with evidence) in your final session handoff.",
|
||||
);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
const DispatchBody = z.object({
|
||||
/** Optional operator steer, prepended to the composed prompt. */
|
||||
note: z.string().trim().max(500).optional(),
|
||||
});
|
||||
|
||||
function isActivelyWorking(state: string, startedAt: Date, deliveredAt: string | null): boolean {
|
||||
if (state === ORCH_STATE.RUNNING) return true;
|
||||
if (state !== ORCH_STATE.WAITING && state !== ORCH_STATE.IDLE) return false;
|
||||
const age = Date.now() - startedAt.getTime();
|
||||
if (age < 90_000) return true; // still starting
|
||||
if (deliveredAt && age < 10 * 60_000) return true; // may still be thinking
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return jsonError("Unauthorized", 401);
|
||||
@@ -58,17 +37,36 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
|
||||
const row = await getFeedbackWithProject(userId, idOrResp);
|
||||
if (!row) return jsonError("Not found", 404);
|
||||
if (row.feedback.status === FEEDBACK_STATUS.DISPATCHED) {
|
||||
return jsonError("Already dispatched", 409);
|
||||
if (row.feedback.status === FEEDBACK_STATUS.RESOLVED || row.feedback.status === FEEDBACK_STATUS.ARCHIVED) {
|
||||
return jsonError("Reopen the item before dispatching again", 409);
|
||||
}
|
||||
if (row.feedback.status === FEEDBACK_STATUS.DISPATCHED && row.feedback.dispatchedRunId) {
|
||||
const run = await getOrchestrationRunById(userId, row.feedback.dispatchedRunId);
|
||||
if (run) {
|
||||
const deliveredAt = (run.payload as { deliveredAt?: string } | null)?.deliveredAt ?? null;
|
||||
if (isActivelyWorking(run.state, run.startedAt, deliveredAt)) {
|
||||
return jsonError("Already working on this — open Control to watch", 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { status, body } = await injectPrompt(
|
||||
{ tab: row.projectName, customPrompt: composePrompt(row.feedback, row.projectName, dataOrResp.note || undefined) },
|
||||
{
|
||||
tab: row.projectName,
|
||||
customPrompt: composeFeedbackFixPrompt(row.feedback, row.projectName, dataOrResp.note || undefined),
|
||||
notifyOnClose: true,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
if (status < 400) {
|
||||
const runId = typeof body.runId === "string" ? body.runId : undefined;
|
||||
await setFeedbackStatus(userId, idOrResp, FEEDBACK_STATUS.DISPATCHED, runId);
|
||||
}
|
||||
return NextResponse.json(body, { status });
|
||||
return NextResponse.json(
|
||||
{
|
||||
...body,
|
||||
workLabel: status < 400 ? "Queued" : undefined,
|
||||
},
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { jsonOk, jsonError } from "@/lib/api/route-helpers";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { listWidgetCoverage } from "@/db/queries/widget-tokens";
|
||||
|
||||
/**
|
||||
* Fleet-wide widget coverage for Control: which site-like projects are missing
|
||||
* an active live embed. Auth required (same pattern as /api/feedback/summary).
|
||||
*/
|
||||
export async function GET() {
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) return jsonError("Unauthorized", 401);
|
||||
const coverage = await listWidgetCoverage(userId);
|
||||
return jsonOk({
|
||||
coverage,
|
||||
needsAttention: coverage.filter((c) => c.needsAttention),
|
||||
});
|
||||
}
|
||||
@@ -60,7 +60,11 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
if (!token) return jsonError("Enable the feedback widget first — the AI reviewer files its findings through the widget API", 400);
|
||||
|
||||
const { status, body } = await injectPrompt(
|
||||
{ tab: project.name, customPrompt: composeReviewPrompt(dataOrResp.url, project.name, token.token) },
|
||||
{
|
||||
tab: project.name,
|
||||
customPrompt: composeReviewPrompt(dataOrResp.url, project.name, token.token),
|
||||
notifyOnClose: true,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
return NextResponse.json(body, { status });
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { readIdParam, readJsonBody, jsonError, z } from "@/lib/api/route-helpers";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { getProjectCore } from "@/db/queries/projects";
|
||||
import { listProjectFeedback, markFeedbackDispatchedBulk } from "@/db/queries/site-feedback";
|
||||
import { injectPrompt } from "@/lib/inject-core";
|
||||
import { FEEDBACK_SOURCE, FEEDBACK_STATUS } from "@/lib/constants/statuses";
|
||||
import { composeFeedbackBatchFixPrompt } from "@/lib/feedback/compose-dispatch";
|
||||
|
||||
/**
|
||||
* One-click "Implement all as one": collapse every NEW visitor/AI-review item
|
||||
* into a single injectPrompt for this project. Prefer this when N≥2 and you
|
||||
* want one agent pass; use Synthesize when N is large and you want theme
|
||||
* briefs back in the inbox first. Human gate preserved — nothing runs without
|
||||
* this POST.
|
||||
*/
|
||||
|
||||
const Body = z.object({
|
||||
note: z.string().trim().max(500).optional(),
|
||||
/** Optional subset; default = all NEW non-synthesizer rows. */
|
||||
ids: z.array(z.string().uuid()).max(60).optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return jsonError("Unauthorized", 401);
|
||||
const idOrResp = await readIdParam(params);
|
||||
if (idOrResp instanceof NextResponse) return idOrResp;
|
||||
const dataOrResp = await readJsonBody(req, Body);
|
||||
if (dataOrResp instanceof NextResponse) return dataOrResp;
|
||||
|
||||
const project = await getProjectCore(userId, idOrResp);
|
||||
if (!project) return jsonError("Project not found", 404);
|
||||
|
||||
let items = (await listProjectFeedback(userId, idOrResp)).filter(
|
||||
(f) => f.status === FEEDBACK_STATUS.NEW && f.source !== FEEDBACK_SOURCE.SYNTHESIZER,
|
||||
);
|
||||
if (dataOrResp.ids?.length) {
|
||||
const want = new Set(dataOrResp.ids);
|
||||
items = items.filter((f) => want.has(f.id));
|
||||
}
|
||||
if (items.length === 0) return jsonError("No new feedback to dispatch", 400);
|
||||
if (items.length === 1) {
|
||||
return jsonError("Use Implement on the single row — batch is for 2+ items", 400);
|
||||
}
|
||||
|
||||
const prompt = composeFeedbackBatchFixPrompt(items, project.name, dataOrResp.note || undefined);
|
||||
const { status, body } = await injectPrompt(
|
||||
{ tab: project.name, customPrompt: prompt, notifyOnClose: true },
|
||||
userId,
|
||||
);
|
||||
if (status < 400) {
|
||||
const runId = typeof body.runId === "string" ? body.runId : undefined;
|
||||
await markFeedbackDispatchedBulk(userId, items.map((f) => f.id), runId);
|
||||
}
|
||||
return NextResponse.json({ ...body, dispatchedCount: items.length }, { status });
|
||||
}
|
||||
@@ -2,17 +2,20 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { readIdParam, jsonOk, jsonError } from "@/lib/api/route-helpers";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { getFeedbackLoopMetrics, listProjectFeedback } from "@/db/queries/site-feedback";
|
||||
import { attachFeedbackWork } from "@/lib/feedback/attach-work";
|
||||
|
||||
/** Per-project feedback inbox (visitor submissions from the embed widget)
|
||||
* plus the loop metrics (resolved count, median report→fix). */
|
||||
* plus the loop metrics (resolved count, median report→fix). Each row
|
||||
* includes `work` — honest phase/label (not started / queued / working / …). */
|
||||
export async function GET(_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 [feedback, metrics] = await Promise.all([
|
||||
const [raw, metrics] = await Promise.all([
|
||||
listProjectFeedback(userId, idOrResp),
|
||||
getFeedbackLoopMetrics(userId, idOrResp).catch(() => null),
|
||||
]);
|
||||
const feedback = await attachFeedbackWork(userId, raw);
|
||||
return jsonOk({ feedback, metrics });
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { injectPrompt } from "@/lib/inject-core";
|
||||
import { appUrl } from "@/lib/email";
|
||||
import { FEEDBACK_SOURCE, FEEDBACK_STATUS } from "@/lib/constants/statuses";
|
||||
import { fenceUntrusted, UNTRUSTED_PREAMBLE } from "@/lib/feedback/untrusted";
|
||||
import { SYNTHESIZE_MIN_ITEMS } from "@/lib/feedback/compose-dispatch";
|
||||
import type { FeedbackListItem } from "@/db/queries/site-feedback";
|
||||
|
||||
/**
|
||||
@@ -18,10 +19,12 @@ import type { FeedbackListItem } from "@/db/queries/site-feedback";
|
||||
* / edit-and-dispatch / archive) as any row. 9 reports of one broken button
|
||||
* become one brief with "evidence: 9 submissions". Review-only run: the
|
||||
* operator still triages; nothing auto-dispatches.
|
||||
*
|
||||
* Prefer Dispatch-all-as-one (`dispatch-batch`) when you want one fix run now
|
||||
* without a second triage gate. Synthesize when volume is high and themes help.
|
||||
*/
|
||||
|
||||
export const SYNTHESIZER_CONTACT = "FleetCrown synthesizer";
|
||||
const MIN_ITEMS = 3;
|
||||
const MAX_ITEMS = 60;
|
||||
|
||||
function renderItem(f: FeedbackListItem): string {
|
||||
@@ -86,12 +89,16 @@ export async function POST(_req: NextRequest, { params }: { params: Promise<{ id
|
||||
&& f.source !== FEEDBACK_SOURCE.SYNTHESIZER
|
||||
&& f.contact !== SYNTHESIZER_CONTACT)
|
||||
.slice(0, MAX_ITEMS);
|
||||
if (items.length < MIN_ITEMS) {
|
||||
return jsonError(`Nothing to synthesize — needs at least ${MIN_ITEMS} new items`, 400);
|
||||
if (items.length < SYNTHESIZE_MIN_ITEMS) {
|
||||
return jsonError(`Nothing to synthesize — needs at least ${SYNTHESIZE_MIN_ITEMS} new items`, 400);
|
||||
}
|
||||
|
||||
const { status, body } = await injectPrompt(
|
||||
{ tab: project.name, customPrompt: composeSynthesizePrompt(items, project.name, token.token) },
|
||||
{
|
||||
tab: project.name,
|
||||
customPrompt: composeSynthesizePrompt(items, project.name, token.token),
|
||||
notifyOnClose: true,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
return NextResponse.json(body, { status });
|
||||
|
||||
@@ -2,21 +2,25 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { readIdParam, readJsonBody, jsonError, z } from "@/lib/api/route-helpers";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { getProjectCore } from "@/db/queries/projects";
|
||||
import { getActiveWidgetToken } from "@/db/queries/widget-tokens";
|
||||
import { getActiveWidgetToken, upsertWidgetToken } from "@/db/queries/widget-tokens";
|
||||
import { injectPrompt } from "@/lib/inject-core";
|
||||
import { injectWatchUrls } from "@/lib/fleet-context";
|
||||
import { appUrl } from "@/lib/email";
|
||||
import {
|
||||
resolveProjectPublicOrigin,
|
||||
resolveProjectRepoTarget,
|
||||
} from "@/lib/feedback/project-site";
|
||||
|
||||
/**
|
||||
* One-click widget install/uninstall for repo-linked projects (Phase 2 of the
|
||||
* widget one-click plan): dispatch an agent to add or remove the embed snippet
|
||||
* in the project's own codebase, through the same injectPrompt SSOT as every
|
||||
* other dispatch. The snippet is a dumb pointer, so "off instantly" stays the
|
||||
* Pause button — this is for actually landing/removing the code, verified and
|
||||
* PR'd like any other agent change.
|
||||
* One-click widget install/uninstall. Auto-enables the token when missing.
|
||||
* Uses Hetzner liveUrl (user_projects) as the site of truth — never a stale
|
||||
* legacy host. Refuses when there is no repo/dir for the agent to change.
|
||||
*/
|
||||
|
||||
const InstallBody = z.object({
|
||||
mode: z.enum(["install", "uninstall"]).default("install"),
|
||||
/** When true, queue the agent even if the live site probe failed (repo-only). */
|
||||
force: z.boolean().optional(),
|
||||
});
|
||||
|
||||
function snippetFor(token: string): string {
|
||||
@@ -24,10 +28,16 @@ function snippetFor(token: string): string {
|
||||
return `<script src="${base}/widget.js" data-fc-project="${token}" async></script>`;
|
||||
}
|
||||
|
||||
function composeInstallPrompt(projectName: string, token: string): string {
|
||||
function composeInstallPrompt(
|
||||
projectName: string,
|
||||
token: string,
|
||||
liveOrigin: string | null,
|
||||
siteNote: string | null,
|
||||
): string {
|
||||
return [
|
||||
`Install the FleetCrown feedback widget on ${projectName}'s public site.`,
|
||||
"",
|
||||
liveOrigin ? `\nLIVE SITE (Hetzner): ${liveOrigin}\n` : "",
|
||||
siteNote ? `\nSITE STATUS: ${siteNote}\n` : "",
|
||||
"THE SNIPPET (use exactly this — do not alter the token or attributes):",
|
||||
"```html",
|
||||
snippetFor(token),
|
||||
@@ -35,13 +45,13 @@ function composeInstallPrompt(projectName: string, token: string): string {
|
||||
"",
|
||||
"1. If this exact snippet (or an embed referencing the same widget.js + data-fc-project token) is already present anywhere in the codebase, do NOT add a second one — verify it renders and report that in your handoff.",
|
||||
"2. Otherwise add it once, in the site's root layout/template so it loads on every public page:",
|
||||
" - Next.js App Router: a small 'use client' component that appends the script tag in a useEffect (mounted from the root layout), or next/script with strategy=\"afterInteractive\" carrying the same src + data-fc-project attributes.",
|
||||
" - Next.js App Router: next/script with strategy=\"afterInteractive\" and the SAME data-fc-project token. Bake the token as a string literal (or ensure FLEETCROWN_FEEDBACK_TOKEN is present at `next build`). Runtime-only .env after deploy is NOT enough — Next tree-shakes an empty token and the Script never ships.",
|
||||
" - Plain HTML / other frameworks: the raw tag right before </body> in the base template.",
|
||||
"3. If the site already has its own floating action button in the bottom-right corner, add data-fc-bottom=\"88\" to the snippet so the widget FAB stacks above it instead of overlapping.",
|
||||
"4. Verify: run the site locally and confirm the page loads without console errors from the embed. (The FAB itself may stay hidden — rendering is server-gated per token — absence of the button is NOT a failure; absence of errors is the check.)",
|
||||
"5. Ship it the way this repo ships changes (branch + PR if that's the convention). Smallest possible diff — the embed and nothing else.",
|
||||
"6. HANDOFF: state the exact file(s) touched and the verification evidence.",
|
||||
].join("\n");
|
||||
"4. Verify: run the site locally and confirm the page loads without console errors from the embed. (The FAB itself may stay hidden — rendering is server-gated per token — absence of the button is NOT a failure; absence of errors is the check.) If the host has a Content-Security-Policy, add https://fleetcrown.orangecat.ch to script-src AND connect-src — otherwise the browser blocks widget.js even when the tag is in the HTML.",
|
||||
"5. Ship it the way this repo ships changes (branch + PR if that's the convention). Deploy is on Hetzner — push/merge so the box picks it up. Smallest possible diff — the embed and nothing else.",
|
||||
"6. HANDOFF: state the exact file(s) touched and the verification evidence. If you could not push or the live URL is down, say so plainly — do not claim the widget is live.",
|
||||
].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
function composeUninstallPrompt(projectName: string, token: string | null): string {
|
||||
@@ -58,6 +68,55 @@ function composeUninstallPrompt(projectName: string, token: string | null): stri
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
type SiteProbe = {
|
||||
ok: boolean;
|
||||
status: number | null;
|
||||
message: string;
|
||||
};
|
||||
|
||||
async function probeSite(origin: string | null): Promise<SiteProbe | null> {
|
||||
if (!origin) return null;
|
||||
try {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 8_000);
|
||||
const res = await fetch(origin, {
|
||||
method: "GET",
|
||||
redirect: "follow",
|
||||
signal: ctrl.signal,
|
||||
headers: { Accept: "text/html" },
|
||||
});
|
||||
clearTimeout(timer);
|
||||
if (res.status === 402) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 402,
|
||||
message: "Live site returned HTTP 402 (deployment disabled or unpaid host). The widget cannot appear until the site is reachable again.",
|
||||
};
|
||||
}
|
||||
if (res.status >= 500) {
|
||||
return {
|
||||
ok: false,
|
||||
status: res.status,
|
||||
message: `Live site returned HTTP ${res.status}. Fix hosting before expecting the widget to show.`,
|
||||
};
|
||||
}
|
||||
if (!res.ok && res.status !== 401 && res.status !== 403) {
|
||||
return {
|
||||
ok: false,
|
||||
status: res.status,
|
||||
message: `Live site returned HTTP ${res.status}.`,
|
||||
};
|
||||
}
|
||||
return { ok: true, status: res.status, message: "Live site responded." };
|
||||
} catch {
|
||||
return {
|
||||
ok: false,
|
||||
status: null,
|
||||
message: "Live site did not respond. Widget cannot be verified there until it is reachable.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return jsonError("Unauthorized", 401);
|
||||
@@ -69,19 +128,90 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
const project = await getProjectCore(userId, idOrResp);
|
||||
if (!project) return jsonError("Project not found", 404);
|
||||
|
||||
// Install needs the token (the snippet embeds it); uninstall works from
|
||||
// generic markers even after a revoke.
|
||||
const token = await getActiveWidgetToken(userId, idOrResp);
|
||||
const watch = injectWatchUrls(project.name);
|
||||
const repo = await resolveProjectRepoTarget(userId, idOrResp);
|
||||
const gitUrl = project.gitUrl || repo.gitUrl;
|
||||
const dirPath = repo.dirPath;
|
||||
|
||||
// Agent needs a repo clone URL and/or a local dir on the runner.
|
||||
if (dataOrResp.mode === "install" && !gitUrl && !dirPath) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "No git URL and no local project directory — Enable & install cannot land the snippet. Add the GitHub URL on the project, or paste the widget snippet manually from the project Widget card.",
|
||||
...watch,
|
||||
code: "no_repo",
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const liveOrigin = await resolveProjectPublicOrigin(userId, idOrResp);
|
||||
|
||||
let token = await getActiveWidgetToken(userId, idOrResp);
|
||||
if (dataOrResp.mode === "install" && !token) {
|
||||
token = await upsertWidgetToken(userId, idOrResp, {
|
||||
origins: liveOrigin ? [liveOrigin] : undefined,
|
||||
});
|
||||
} else if (
|
||||
dataOrResp.mode === "install"
|
||||
&& token
|
||||
&& liveOrigin
|
||||
&& (!token.origins?.length || token.origins.every((o) => /\.vercel\.app$/i.test(new URL(o).hostname)))
|
||||
) {
|
||||
// Replace stale legacy hosts with the Hetzner live URL so ingest/boot work.
|
||||
token = await upsertWidgetToken(userId, idOrResp, {
|
||||
origins: [liveOrigin],
|
||||
});
|
||||
}
|
||||
|
||||
const siteProbe = dataOrResp.mode === "install" ? await probeSite(liveOrigin) : null;
|
||||
|
||||
if (
|
||||
dataOrResp.mode === "install"
|
||||
&& siteProbe
|
||||
&& !siteProbe.ok
|
||||
&& !dataOrResp.force
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: siteProbe.message,
|
||||
siteProbe,
|
||||
...watch,
|
||||
code: "site_unreachable",
|
||||
tokenReady: !!token,
|
||||
hint: "Fix the live site on the box, then click Enable & install again. Or open the project Widget card and copy the snippet by hand.",
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
const siteNote = siteProbe && !siteProbe.ok ? siteProbe.message : null;
|
||||
const prompt =
|
||||
dataOrResp.mode === "install"
|
||||
? token
|
||||
? composeInstallPrompt(project.name, token.token)
|
||||
? composeInstallPrompt(project.name, token.token, liveOrigin, siteNote)
|
||||
: null
|
||||
: composeUninstallPrompt(project.name, token?.token ?? null);
|
||||
if (!prompt) {
|
||||
return jsonError("Enable the widget first — the install snippet embeds the project token", 400);
|
||||
return jsonError("Could not enable the widget token for this project", 400);
|
||||
}
|
||||
|
||||
const { status, body } = await injectPrompt({ tab: project.name, customPrompt: prompt }, userId);
|
||||
return NextResponse.json(body, { status });
|
||||
const { status, body } = await injectPrompt(
|
||||
{ tab: project.name, customPrompt: prompt, notifyOnClose: true },
|
||||
userId,
|
||||
);
|
||||
return NextResponse.json(
|
||||
{
|
||||
...body,
|
||||
tokenCreated: dataOrResp.mode === "install" && !!token,
|
||||
siteProbe,
|
||||
liveOrigin,
|
||||
...watch,
|
||||
nextStep:
|
||||
status < 400
|
||||
? "Queued for this project. Watch Control and Activity. Terminal only shows a session once the agent is actually running. You get a notification when the run finishes."
|
||||
: undefined,
|
||||
},
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
@@ -22,8 +22,9 @@ export default function FeedbackWidgetDocsPage() {
|
||||
<h2 className="ui-public-prose-h2">1. Enable it on a project</h2>
|
||||
<p>
|
||||
Open the project's page in FleetCrown, scroll to <strong>Visitor feedback</strong>,
|
||||
and click <strong>Widget → Enable widget</strong>. That mints a project token and shows
|
||||
the embed snippet:
|
||||
and click <strong>Enable & install via agent</strong> (or from Control, use the
|
||||
fleet coverage strip). That mints a project token and dispatches an agent to embed the
|
||||
snippet. Prefer that one click over copy-paste unless you are wiring a site by hand.
|
||||
</p>
|
||||
<pre className="ui-public-code-block">
|
||||
<code>{`<script src="https://fleetcrown.orangecat.ch/widget.js"
|
||||
@@ -106,18 +107,23 @@ export default function FeedbackWidgetDocsPage() {
|
||||
</p>
|
||||
<ul className="list-disc pl-6 space-y-2">
|
||||
<li>
|
||||
<strong>Dispatch fix</strong> — composes a scoped prompt from the report (text, URL,
|
||||
selectors) and sends an agent at it. The pencil icon lets you prepend your own
|
||||
instruction to the prompt.
|
||||
<strong>Dispatch fix</strong> — one report → one scoped agent run. Routes through
|
||||
FleetCrown's <code>injectPrompt</code> SSOT: local Fleet Runner when connected,
|
||||
otherwise the cloud builder. You do not pick a terminal.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Dispatch all as one</strong> (2+ new items) — one agent pass covering the
|
||||
whole pile. Prefer this when you want a single coherent fix run now.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Synthesize themes</strong> (3+ new items) — an agent clusters the pile into
|
||||
structured briefs filed back into the same inbox; you then Dispatch the brief. Use
|
||||
when volume is high and themes help before fixing.
|
||||
</li>
|
||||
<li>
|
||||
<strong>AI review</strong> — an agent opens any page of your site in a headless
|
||||
browser (desktop + mobile) and files findings into the same inbox.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Synthesize</strong> (at 5+ new items) — an agent clusters the pile into
|
||||
structured briefs: theme, evidence, proposed change, where.
|
||||
</li>
|
||||
<li>
|
||||
A <strong>daily digest</strong> clusters busy inboxes into themes and files each as a
|
||||
draft on <Link href="/approvals" className="ui-public-link">Approvals</Link> — with
|
||||
|
||||
@@ -114,7 +114,9 @@ export function AttentionBar({
|
||||
|
||||
{groupedFailures.map((group) => {
|
||||
const f = group.representative;
|
||||
const verb = f.unverified ? "delivered" : "failed";
|
||||
// "delivered" was polite fiction when verified=false — the prompt hit a
|
||||
// PTY but the agent never generated. Say that plainly.
|
||||
const verb = f.unverified ? "queued, not confirmed working" : "failed";
|
||||
return (
|
||||
<div key={f.id} className="ui-callout-negative justify-between">
|
||||
<div className="flex items-start gap-3 min-w-0">
|
||||
@@ -133,6 +135,15 @@ export function AttentionBar({
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{f.tab !== "unknown" && (
|
||||
<a
|
||||
href={`/control?focus=${encodeURIComponent(f.tab)}`}
|
||||
className="ui-btn-ghost ui-btn-xs text-micro"
|
||||
title={`Focus ${f.tab} on Control — Terminal stays empty unless a session is actually running`}
|
||||
>
|
||||
Open on Control
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
onClick={() => retry(group)}
|
||||
disabled={retrying.has(f.id)}
|
||||
|
||||
@@ -324,8 +324,14 @@ export function ControlFleetStatus({
|
||||
{ready} awaiting input
|
||||
</span>
|
||||
)}
|
||||
<span className={cn("ui-control-fleet-chip", staleClass)} title={staleTitle ?? COUNT_SCOPE_TITLE}>
|
||||
{idle} idle
|
||||
<span
|
||||
className={cn("ui-control-fleet-chip", staleClass)}
|
||||
title={
|
||||
staleTitle
|
||||
?? "How many fleet projects have no agent session right now. Unrelated to Cloud/builder online — that is the runner, not project work."
|
||||
}
|
||||
>
|
||||
{idle} projects idle
|
||||
</span>
|
||||
{/* "All clear" only when nothing needs you and nothing is live — and
|
||||
never while stale, when 0/0/0 means "the runner stopped reporting",
|
||||
|
||||
@@ -15,6 +15,7 @@ import { ControlFleetStatus } from "./ControlFleetStatus";
|
||||
import { AttentionBar } from "./AttentionBar";
|
||||
import { AgentEscalations } from "./AgentEscalations";
|
||||
import { FleetFeedbackStrip } from "./FleetFeedbackStrip";
|
||||
import { FleetWidgetCoverageStrip } from "./FleetWidgetCoverageStrip";
|
||||
import { RunnerStatusBanner } from "./RunnerStatusBanner";
|
||||
import { APP_NAME } from "@/config/brand";
|
||||
import {
|
||||
@@ -159,7 +160,6 @@ export function ControlPanel() {
|
||||
: null;
|
||||
|
||||
const failedCount = data?.failedCommands?.length ?? 0;
|
||||
const projectOverrideCount = data?.projects.filter((project) => project.autoInjectModeOverride !== null).length ?? 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (!snapshots?.length) return;
|
||||
@@ -383,12 +383,12 @@ export function ControlPanel() {
|
||||
setSelectedTab(match.project.tab);
|
||||
document.getElementById("control-projects")?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}}
|
||||
projectOverrideCount={projectOverrideCount}
|
||||
/>}
|
||||
|
||||
<AttentionBar items={attention} failedCommands={data?.failedCommands} onFocusProject={setSelectedTab} />
|
||||
{data.projects.length > 0 && <AgentEscalations />}
|
||||
|
||||
<FleetWidgetCoverageStrip />
|
||||
<FleetFeedbackStrip />
|
||||
|
||||
<ProjectOperationsView
|
||||
@@ -404,18 +404,13 @@ export function ControlPanel() {
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Workspaces panel — collapsed-by-default on every breakpoint when the
|
||||
runner is offline or never-seen. The Projects grid above already
|
||||
shows every registered project's last-known state; in offline mode
|
||||
this panel duplicates the same fact in a different layout (caught in
|
||||
dogfood: Projects list + Terminal workspaces both rendering FleetCrown
|
||||
with identical status read as broken). When the runner is live the
|
||||
panel auto-opens on desktop so the quick send-to-any-tab affordance
|
||||
stays one click away. */}
|
||||
{/* Workspaces panel — collapsed by default. Projects already shows
|
||||
per-project state; auto-opening this duplicated the same facts in a
|
||||
second layout (dogfood: read as broken / demo chrome). Open when you
|
||||
need Zellij quick-send or peek — not on every Control visit. */}
|
||||
<details
|
||||
ref={liveDetailsRef}
|
||||
className="ui-control-live-details"
|
||||
open={!runnerNeverSeen && !runnerOffline}
|
||||
>
|
||||
<summary className="ui-control-live-details-summary">
|
||||
<span>Workspaces</span>
|
||||
|
||||
@@ -1,41 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Archive, Check, ChevronDown, Loader2, MessageSquare, Rocket } from "lucide-react";
|
||||
import { Archive, Check, ChevronDown, Layers, Loader2, MessageSquare, Rocket } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useFetch } from "@/hooks/use-fetch";
|
||||
import { patchJson, postJson, throwApiError } from "@/lib/api/fetch";
|
||||
import { compactRelativeDate } from "@/lib/dates";
|
||||
import { FEEDBACK_STATUS } from "@/lib/constants/statuses";
|
||||
import type { FeedbackListItem, ProjectFeedbackSummary } from "@/db/queries/site-feedback";
|
||||
import { SYNTHESIZE_MIN_ITEMS } from "@/lib/feedback/compose-dispatch";
|
||||
import { deriveFeedbackWork, FEEDBACK_WORK_PHASE } from "@/lib/feedback/work-phase";
|
||||
import type { FeedbackListItemWithWork } from "@/lib/feedback/attach-work";
|
||||
import type { ProjectFeedbackSummary } from "@/db/queries/site-feedback";
|
||||
import { FeedbackWorkBadge } from "@/components/feedback/FeedbackWorkBadge";
|
||||
|
||||
/**
|
||||
* Fleet-wide feedback lens on /control: projects with NEW visitor feedback,
|
||||
* busiest first. The strip is also an inbox, not just a signpost — clicking a
|
||||
* project chip expands its NEW items inline with Dispatch fix / Resolve /
|
||||
* Archive per row, so the report→fix loop closes without leaving Control.
|
||||
* (Before, the only affordance was a link to the project page, where the
|
||||
* inbox sits below the full run history — six steps for the most common
|
||||
* action on this screen.) The project link remains for the full inbox
|
||||
* (screenshots, widget setup, AI review). Renders nothing when clear.
|
||||
* Fleet-wide feedback lens on /control. Shows NEW + in-progress (not resolved)
|
||||
* so Implement → Queued → Working → Done is visible without vanishing rows.
|
||||
*/
|
||||
export function FleetFeedbackStrip() {
|
||||
// The loop metrics ("13 resolved, median 6d report→fix") were dropped from
|
||||
// this strip 2026-08-13 — vanity stats in an action surface (user: "seems
|
||||
// like noise"). They still render on each project's feedback inbox.
|
||||
const { data, refetch } = useFetch<{ summary: ProjectFeedbackSummary[] }>("/api/feedback/summary");
|
||||
const summary = data?.summary ?? [];
|
||||
const [openProjectId, setOpenProjectId] = useState<string | null>(null);
|
||||
// undefined = no manual choice yet → auto-open the first project;
|
||||
// null = user explicitly closed; string = user's pick. Derived instead of
|
||||
// a setState-in-effect so the first render already shows the open panel.
|
||||
const [selection, setSelection] = useState<string | null | undefined>(undefined);
|
||||
const openProjectId = selection === undefined ? summary[0]?.projectId ?? null : selection;
|
||||
const setOpenProjectId = (next: (prev: string | null) => string | null) =>
|
||||
setSelection(next(openProjectId));
|
||||
|
||||
if (summary.length === 0) return null;
|
||||
const open = summary.find((s) => s.projectId === openProjectId) ?? null;
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border-l-2 border-accent-primary border-t border-r border-b border-border-subtle bg-surface-base">
|
||||
<div className="ui-panel border-l-2 border-l-accent-primary">
|
||||
<div className="flex items-start gap-3 px-4 py-3">
|
||||
<MessageSquare className="h-3.5 w-3.5 shrink-0 mt-0.5 text-accent-text" aria-hidden="true" />
|
||||
<MessageSquare className="mt-0.5 h-3.5 w-3.5 shrink-0 text-accent-text" aria-hidden="true" />
|
||||
<div className="flex min-w-0 flex-wrap gap-2">
|
||||
<span className="mt-0.5 shrink-0 text-xs font-medium text-text-secondary">New feedback:</span>
|
||||
<span className="mt-0.5 shrink-0 text-xs font-medium text-text-secondary">Feedback:</span>
|
||||
{summary.map((s) => (
|
||||
<button
|
||||
key={s.projectId}
|
||||
@@ -46,10 +48,10 @@ export function FleetFeedbackStrip() {
|
||||
"ui-tap flex shrink-0 items-center gap-1.5 text-xs font-medium text-text-primary underline-offset-2 transition-colors hover:underline",
|
||||
openProjectId === s.projectId && "text-accent-text",
|
||||
)}
|
||||
title={`Latest ${compactRelativeDate(s.latestAt)} — triage ${s.projectName}'s new reports right here`}
|
||||
title={`Latest ${compactRelativeDate(s.latestAt)} — ${s.newCount} new`}
|
||||
>
|
||||
{s.projectName}
|
||||
<span className="ui-badge">{s.newCount}</span>
|
||||
<span>{s.projectName}</span>
|
||||
<span className="ui-badge">{s.newCount} new</span>
|
||||
<ChevronDown className={cn("h-3 w-3 opacity-50 transition-transform", openProjectId === s.projectId && "rotate-180")} />
|
||||
</button>
|
||||
))}
|
||||
@@ -67,9 +69,6 @@ export function FleetFeedbackStrip() {
|
||||
);
|
||||
}
|
||||
|
||||
/** The NEW items of one project, triagable in place. Compact on purpose —
|
||||
* screenshots, notes, widget setup, and resolved history stay on the
|
||||
* project page; this surface exists to clear the inbox fast. */
|
||||
function InlineFeedbackTriage({
|
||||
projectId,
|
||||
projectName,
|
||||
@@ -79,10 +78,30 @@ function InlineFeedbackTriage({
|
||||
projectName: string;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
const feedbackFetch = useFetch<{ feedback: FeedbackListItem[] }>(`/api/projects/${projectId}/feedback`);
|
||||
const feedbackFetch = useFetch<{ feedback: FeedbackListItemWithWork[] }>(`/api/projects/${projectId}/feedback`);
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [batchBusy, setBatchBusy] = useState(false);
|
||||
const [synthBusy, setSynthBusy] = useState(false);
|
||||
const [synthDone, setSynthDone] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const items = (feedbackFetch.data?.feedback ?? []).filter((f) => f.status === FEEDBACK_STATUS.NEW);
|
||||
|
||||
// Open work stays visible: new + anything not resolved/archived.
|
||||
const items = (feedbackFetch.data?.feedback ?? [])
|
||||
.filter((f) => f.status === FEEDBACK_STATUS.NEW || f.status === FEEDBACK_STATUS.DISPATCHED)
|
||||
.map((f) => ({ ...f, work: f.work ?? deriveFeedbackWork(f.status, null) }));
|
||||
const newItems = items.filter((f) => f.status === FEEDBACK_STATUS.NEW);
|
||||
const controlHref = `/control?focus=${encodeURIComponent(projectName)}`;
|
||||
const terminalHref = `/terminal?source=server&tab=${encodeURIComponent(projectName)}`;
|
||||
|
||||
useEffect(() => {
|
||||
const live = items.some(
|
||||
(f) => f.work.phase === FEEDBACK_WORK_PHASE.QUEUED || f.work.phase === FEEDBACK_WORK_PHASE.WORKING,
|
||||
);
|
||||
if (!live) return;
|
||||
const t = window.setInterval(() => feedbackFetch.refetch(), 8_000);
|
||||
return () => window.clearInterval(t);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [items.map((f) => f.work.phase).join("|")]);
|
||||
|
||||
async function act(id: string, run: () => Promise<Response>, fallback: string) {
|
||||
setBusyId(id);
|
||||
@@ -99,65 +118,161 @@ function InlineFeedbackTriage({
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatchAll() {
|
||||
setBatchBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await postJson(`/api/projects/${projectId}/feedback/dispatch-batch`, {});
|
||||
if (!res.ok) await throwApiError(res, "Implement all failed");
|
||||
feedbackFetch.refetch();
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Implement all failed");
|
||||
} finally {
|
||||
setBatchBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function synthesize() {
|
||||
setSynthBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await postJson(`/api/projects/${projectId}/feedback/synthesize`, {});
|
||||
if (!res.ok) await throwApiError(res, "Synthesize failed");
|
||||
setSynthDone(true);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Synthesize failed");
|
||||
} finally {
|
||||
setSynthBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-t border-border-subtle px-4 pb-3 pt-2">
|
||||
{error && <p className="ui-error mb-2">{error}</p>}
|
||||
{newItems.length >= 2 && (
|
||||
<div className="mb-2 flex flex-wrap items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={dispatchAll}
|
||||
disabled={batchBusy || busyId !== null}
|
||||
className="ui-btn-save gap-1.5"
|
||||
title="One agent run for every not-started report"
|
||||
>
|
||||
{batchBusy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Implement all ({newItems.length})
|
||||
</button>
|
||||
{newItems.length >= SYNTHESIZE_MIN_ITEMS && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={synthesize}
|
||||
disabled={synthBusy || synthDone}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title="Cluster into theme briefs"
|
||||
>
|
||||
{synthBusy ? <Loader2 className="ui-spinner-xs" /> : <Layers className="h-3.5 w-3.5" />}
|
||||
{synthDone ? "Synthesis queued" : "Synthesize themes"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{feedbackFetch.loading ? (
|
||||
<div className="flex items-center gap-2 py-3 text-xs text-text-tertiary">
|
||||
<Loader2 className="ui-spinner-xs" /> Loading {projectName}'s new reports…
|
||||
<Loader2 className="ui-spinner-xs" /> Loading {projectName}'s feedback…
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<p className="py-2 text-xs text-text-muted">Inbox clear — nothing new for {projectName}.</p>
|
||||
<p className="py-2 text-xs text-text-muted">Nothing open for {projectName}.</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border-subtle">
|
||||
{items.map((f) => (
|
||||
<div key={f.id} className="flex flex-col gap-2 py-2.5 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-start gap-2">
|
||||
<span className="ui-dot-warning mt-1.5 shrink-0" aria-hidden="true" />
|
||||
<p className="min-w-0 text-sm leading-relaxed text-text-primary line-clamp-2">{f.suggestion}</p>
|
||||
{f.duplicateCount > 1 && (
|
||||
<span className="ui-badge shrink-0" title={`Reported ${f.duplicateCount} times`}>×{f.duplicateCount}</span>
|
||||
{items.map((f) => {
|
||||
const work = f.work;
|
||||
return (
|
||||
<div key={f.id} className="flex flex-col gap-2 py-2.5 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-start gap-2">
|
||||
<span
|
||||
className={
|
||||
work.phase === FEEDBACK_WORK_PHASE.WORKING || work.phase === FEEDBACK_WORK_PHASE.DONE
|
||||
? "ui-dot-positive mt-1.5 shrink-0"
|
||||
: work.phase === FEEDBACK_WORK_PHASE.FAILED || work.phase === FEEDBACK_WORK_PHASE.STUCK
|
||||
? "ui-dot-negative mt-1.5 shrink-0"
|
||||
: "ui-dot-warning mt-1.5 shrink-0"
|
||||
}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<p className="min-w-0 text-sm leading-relaxed text-text-primary line-clamp-2">{f.suggestion}</p>
|
||||
<FeedbackWorkBadge work={work} />
|
||||
</div>
|
||||
<p className="mt-0.5 truncate pl-4 text-xs text-text-tertiary">
|
||||
{[f.page || f.url, f.scope, compactRelativeDate(f.createdAt)].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
{work.detail && (
|
||||
<p className="mt-0.5 pl-4 text-xs text-text-secondary line-clamp-2">{work.detail}</p>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-0.5 truncate pl-4 text-xs text-text-tertiary">
|
||||
{[f.page || f.url, compactRelativeDate(f.createdAt)].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
<div className="flex shrink-0 items-center gap-1.5 pl-4 sm:pl-0">
|
||||
{work.phase === FEEDBACK_WORK_PHASE.NOT_STARTED ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => postJson(`/api/feedback/${f.id}/dispatch`, {}), "Implement failed")}
|
||||
disabled={busyId === f.id || batchBusy}
|
||||
className="ui-btn-save gap-1.5"
|
||||
>
|
||||
{busyId === f.id ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Implement
|
||||
</button>
|
||||
) : work.phase === FEEDBACK_WORK_PHASE.STUCK || work.phase === FEEDBACK_WORK_PHASE.FAILED ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => postJson(`/api/feedback/${f.id}/dispatch`, {}), "Retry failed")}
|
||||
disabled={busyId === f.id || batchBusy}
|
||||
className="ui-btn-save gap-1.5"
|
||||
>
|
||||
{busyId === f.id ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Retry
|
||||
</button>
|
||||
) : null}
|
||||
{(work.phase === FEEDBACK_WORK_PHASE.QUEUED
|
||||
|| work.phase === FEEDBACK_WORK_PHASE.WORKING
|
||||
|| work.phase === FEEDBACK_WORK_PHASE.STUCK
|
||||
|| work.phase === FEEDBACK_WORK_PHASE.FAILED
|
||||
|| work.phase === FEEDBACK_WORK_PHASE.DONE) && (
|
||||
<a
|
||||
href={work.phase === FEEDBACK_WORK_PHASE.WORKING ? terminalHref : controlHref}
|
||||
className="ui-btn-secondary gap-1.5 text-xs"
|
||||
title={
|
||||
work.phase === FEEDBACK_WORK_PHASE.WORKING
|
||||
? "Live agent session"
|
||||
: "Open this project on Control — Terminal is empty until a session is actually running"
|
||||
}
|
||||
>
|
||||
{work.phase === FEEDBACK_WORK_PHASE.WORKING ? "Watch" : "Open on Control"}
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => patchJson(`/api/feedback/${f.id}`, { status: FEEDBACK_STATUS.RESOLVED }), "Update failed")}
|
||||
disabled={busyId === f.id || batchBusy}
|
||||
className="ui-btn-icon"
|
||||
title="Mark resolved"
|
||||
aria-label="Mark resolved"
|
||||
>
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => patchJson(`/api/feedback/${f.id}`, { status: FEEDBACK_STATUS.ARCHIVED }), "Update failed")}
|
||||
disabled={busyId === f.id || batchBusy}
|
||||
className="ui-btn-icon"
|
||||
title="Archive"
|
||||
aria-label="Archive"
|
||||
>
|
||||
<Archive className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5 pl-4 sm:pl-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => postJson(`/api/feedback/${f.id}/dispatch`, {}), "Dispatch failed")}
|
||||
disabled={busyId === f.id}
|
||||
className="ui-btn-save gap-1.5"
|
||||
title="Send to an agent as a fix task"
|
||||
>
|
||||
{busyId === f.id ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Dispatch fix
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => patchJson(`/api/feedback/${f.id}`, { status: FEEDBACK_STATUS.RESOLVED }), "Update failed")}
|
||||
disabled={busyId === f.id}
|
||||
className="ui-btn-icon"
|
||||
title="Mark resolved"
|
||||
aria-label="Mark resolved"
|
||||
>
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act(f.id, () => patchJson(`/api/feedback/${f.id}`, { status: FEEDBACK_STATUS.ARCHIVED }), "Update failed")}
|
||||
disabled={busyId === f.id}
|
||||
className="ui-btn-icon"
|
||||
title="Archive"
|
||||
aria-label="Archive"
|
||||
>
|
||||
<Archive className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{/* text-text-tertiary rendered this at 3.13:1 on the card surface —
|
||||
@@ -169,7 +284,7 @@ function InlineFeedbackTriage({
|
||||
href={`/projects/${projectId}#feedback`}
|
||||
className="mt-1 inline-block text-xs text-text-secondary underline underline-offset-2 decoration-border-subtle hover:decoration-current"
|
||||
>
|
||||
Full inbox — screenshots, history, widget setup →
|
||||
Full inbox →
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Code2, Loader2, Rocket } from "lucide-react";
|
||||
import { useFetch } from "@/hooks/use-fetch";
|
||||
import { postJson } from "@/lib/api/fetch";
|
||||
import type { WidgetCoverageItem } from "@/db/queries/widget-tokens";
|
||||
|
||||
type InstallOutcome = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fleet widget coverage: sites missing a live embed. Enable & install must
|
||||
* fail honestly (no git URL, site paused) — never "queued" into an empty Terminal.
|
||||
*/
|
||||
export function FleetWidgetCoverageStrip() {
|
||||
const { data, refetch, loading } = useFetch<{
|
||||
coverage: WidgetCoverageItem[];
|
||||
needsAttention: WidgetCoverageItem[];
|
||||
}>("/api/feedback/widget-coverage");
|
||||
const needs = data?.needsAttention ?? [];
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [outcomes, setOutcomes] = useState<Record<string, InstallOutcome>>({});
|
||||
|
||||
if (loading || needs.length === 0) return null;
|
||||
|
||||
async function enableAndInstall(projectId: string, projectName: string) {
|
||||
setBusyId(projectId);
|
||||
setOutcomes((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[projectId];
|
||||
return next;
|
||||
});
|
||||
try {
|
||||
const res = await postJson(`/api/projects/${projectId}/widget-token/install`, { mode: "install" });
|
||||
const body = (await res.json().catch(() => ({}))) as {
|
||||
error?: string;
|
||||
hint?: string;
|
||||
nextStep?: string;
|
||||
code?: string;
|
||||
};
|
||||
if (!res.ok) {
|
||||
setOutcomes((prev) => ({
|
||||
...prev,
|
||||
[projectId]: {
|
||||
ok: false,
|
||||
message: [body.error, body.hint].filter(Boolean).join(" ") || "Install could not start.",
|
||||
},
|
||||
}));
|
||||
return;
|
||||
}
|
||||
setOutcomes((prev) => ({
|
||||
...prev,
|
||||
[projectId]: {
|
||||
ok: true,
|
||||
message:
|
||||
body.nextStep
|
||||
|| `Queued for ${projectName}. Stay on Control — if Attention shows Retry, the agent never started.`,
|
||||
},
|
||||
}));
|
||||
refetch();
|
||||
} catch (e) {
|
||||
setOutcomes((prev) => ({
|
||||
...prev,
|
||||
[projectId]: {
|
||||
ok: false,
|
||||
message: e instanceof Error ? e.message : "Install could not start.",
|
||||
},
|
||||
}));
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ui-panel border-l-2 border-l-accent-primary">
|
||||
<div className="flex items-start gap-3 px-4 py-3">
|
||||
<Code2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-accent-text" aria-hidden="true" />
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<p className="text-xs font-medium text-text-secondary">
|
||||
Widget not on live site ({needs.length})
|
||||
</p>
|
||||
<p className="text-micro text-text-tertiary">
|
||||
Criteria: has a public URL, and no recent widget boot heartbeat (or token missing/paused).
|
||||
</p>
|
||||
<ul className="divide-y divide-border-subtle">
|
||||
{needs.map((p) => {
|
||||
const outcome = outcomes[p.projectId];
|
||||
const reason = !p.hasToken
|
||||
? "not enabled"
|
||||
: p.tokenStatus !== "active"
|
||||
? "token paused"
|
||||
: "token on — never seen a boot from the live site";
|
||||
const controlHref = `/control?focus=${encodeURIComponent(p.projectName)}`;
|
||||
return (
|
||||
<li key={p.projectId} className="flex flex-col gap-2 py-2.5">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-text-primary">{p.projectName}</p>
|
||||
<p className="truncate text-xs text-text-tertiary">
|
||||
{[reason, p.productionUrl || p.gitUrl || "no git URL"].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
{!p.gitUrl && !p.productionUrl && (
|
||||
<p className="mt-0.5 text-xs text-status-negative">
|
||||
No git URL — one-click install cannot land code. Add the repo URL or paste the snippet from the project Widget card.
|
||||
</p>
|
||||
)}
|
||||
{!p.gitUrl && p.productionUrl && (
|
||||
<p className="mt-0.5 text-xs text-status-negative">
|
||||
No git URL on this project — Enable & install needs the repo (or a local dir on the runner). Paste the snippet from the Widget card as a fallback.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => enableAndInstall(p.projectId, p.projectName)}
|
||||
disabled={busyId === p.projectId || !p.gitUrl}
|
||||
className="ui-btn-save gap-1.5"
|
||||
title={
|
||||
p.gitUrl
|
||||
? "Mint token if needed and queue an agent to embed the widget in the repo"
|
||||
: "Blocked — project has no git URL"
|
||||
}
|
||||
>
|
||||
{busyId === p.projectId ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Enable & install
|
||||
</button>
|
||||
<Link
|
||||
href={controlHref}
|
||||
className="text-xs text-text-tertiary underline-offset-2 hover:underline"
|
||||
title="Focus this project on Control (Terminal is empty until an agent session exists)"
|
||||
>
|
||||
Open on Control
|
||||
</Link>
|
||||
<Link
|
||||
href={`/projects/${p.projectId}#feedback`}
|
||||
className="text-xs text-text-tertiary underline-offset-2 hover:underline"
|
||||
>
|
||||
Widget card
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
{outcome && (
|
||||
<p className={outcome.ok ? "text-xs text-text-secondary" : "ui-error"}>
|
||||
{outcome.message}
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -93,7 +93,7 @@ export function IntentButtonPanel({
|
||||
isRunning: boolean;
|
||||
autoContinueEnabled: boolean;
|
||||
sending: string | null;
|
||||
/** Transient "✓ Dispatched" confirmation. Set on confirmed-successful
|
||||
/** Transient "✓ Queued" confirmation. Set on confirmed-successful
|
||||
* send; consumers render the ✓ glyph on the matching button until the
|
||||
* hook auto-clears it. UX audit gap: post-200 silence on every dispatch
|
||||
* read as "did it actually do anything?" — this closes the loop. */
|
||||
@@ -191,6 +191,9 @@ export function IntentButtonPanel({
|
||||
if (t.startsWith("setup (run, read outputs)")) continue;
|
||||
if (t.includes("picked ") && t.includes(" (t")) continue; // the accountability line
|
||||
if (/\bwaiting for instructions\b/.test(t)) continue;
|
||||
// Nav / marketing chrome accidentally captured as "prompts" — not reusable intent.
|
||||
if (/\b(features|how it works|pricing|for pros|adopt|sign in|log in)\b/.test(t) && t.length < 120) continue;
|
||||
if (/^used \d+×/.test(t)) continue;
|
||||
cleanedCounts.set(clean, (cleanedCounts.get(clean) ?? 0) + r.count);
|
||||
}
|
||||
const recentPrompts = [...cleanedCounts.entries()]
|
||||
@@ -208,7 +211,7 @@ export function IntentButtonPanel({
|
||||
|
||||
return (
|
||||
<div className="space-y-3 ui-card-section">
|
||||
<PromptInput {...inputProps} placeholder={isRunning ? "Send interrupt…" : "What should the agent work on? e.g. summarize this repo"} />
|
||||
<PromptInput {...inputProps} placeholder={isRunning ? "Send interrupt…" : "What should the agent work on?"} />
|
||||
{queue.length > 0 && (
|
||||
<QueueList queue={queue} blockedReason={queueBlockedReason} onSend={onSendFromQueue} onRemove={onRemoveFromQueue} onReorder={onReorderInQueue} onEdit={onEditInQueue} onMerge={onMergeQueue} merging={merging} onMergeItems={onMergeItemsInQueue} />
|
||||
)}
|
||||
@@ -217,7 +220,7 @@ export function IntentButtonPanel({
|
||||
{!bannerActive && primary && (
|
||||
<div className="space-y-2 border-t border-border-subtle pt-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="ui-kicker">Quick dispatch</p>
|
||||
<p className="ui-kicker">Send to agent</p>
|
||||
<ExecutorHonestyChip honesty={dispatchHonesty} />
|
||||
</div>
|
||||
{/* Primary CTA: Next best — full width, visually elevated.
|
||||
@@ -236,15 +239,9 @@ export function IntentButtonPanel({
|
||||
{sending === primary.id
|
||||
? "…"
|
||||
: justSent?.id === primary.id
|
||||
? `✓ Dispatched`
|
||||
? `✓ Queued`
|
||||
: `${primary.label} →`}
|
||||
</button>
|
||||
{/* What the button DOES, visible — first-time users had to hover
|
||||
the tooltip (or find the prompt-library card) to learn that
|
||||
this dispatches immediately with no preview. */}
|
||||
<p className="text-micro leading-relaxed text-text-muted">
|
||||
The agent re-reads the repo's ground truth, picks the highest-impact task, and runs it — dispatches immediately.
|
||||
</p>
|
||||
|
||||
{/* Secondary intents: compact chips + More toggle.
|
||||
On phones, these three (Test & fix / Quality / Commit) plus the
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FEEDBACK_WORK_PHASE, type FeedbackWorkView } from "@/lib/feedback/work-phase";
|
||||
|
||||
/** Honest status chip for feedback work — never says "dispatched". */
|
||||
export function FeedbackWorkBadge({ work }: { work: FeedbackWorkView }) {
|
||||
const tone =
|
||||
work.phase === FEEDBACK_WORK_PHASE.WORKING
|
||||
? "ui-tag-positive"
|
||||
: work.phase === FEEDBACK_WORK_PHASE.DONE
|
||||
? "ui-tag-positive"
|
||||
: work.phase === FEEDBACK_WORK_PHASE.FAILED || work.phase === FEEDBACK_WORK_PHASE.STUCK
|
||||
? "ui-tag-negative"
|
||||
: work.phase === FEEDBACK_WORK_PHASE.QUEUED
|
||||
? "ui-tag-warning"
|
||||
: "ui-tag";
|
||||
|
||||
return (
|
||||
<span className={cn(tone, "shrink-0")} title={work.detail ?? work.label}>
|
||||
{work.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import Link from "next/link";
|
||||
import { Loader2, Play, Wrench } from "lucide-react";
|
||||
import { postJson } from "@/lib/api/fetch";
|
||||
import { fleetSurfaceHref } from "@/lib/fleet-context";
|
||||
import { EXECUTOR_COPY } from "@/config/executor-copy";
|
||||
import type { ProjectDispatchKind } from "@/lib/project-dispatch";
|
||||
|
||||
// Re-exported for existing importers (AskLokiButton) — SSOT lives in lib/project-dispatch.
|
||||
@@ -39,17 +40,28 @@ export function useProjectDispatch(projectId: string) {
|
||||
return { state, dispatch };
|
||||
}
|
||||
|
||||
/** Inline confirmation shown after a successful dispatch: where to watch it. */
|
||||
/** Inline confirmation after a successful queue: where to watch, and that
|
||||
* a notification fires when the run finishes. Terminal is not the watch
|
||||
* surface until a session is actually running. */
|
||||
export function DispatchedNote({ workspaceKey }: { workspaceKey: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-xs text-status-positive">
|
||||
Dispatched
|
||||
<span className="inline-flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-status-positive">
|
||||
{EXECUTOR_COPY.honesty.queued}
|
||||
<Link
|
||||
href={fleetSurfaceHref("terminal", workspaceKey)}
|
||||
href={fleetSurfaceHref("control", workspaceKey)}
|
||||
className="text-accent-text underline-offset-2 hover:underline"
|
||||
>
|
||||
watch in Terminal
|
||||
Control
|
||||
</Link>
|
||||
<Link
|
||||
href={fleetSurfaceHref("activity", workspaceKey)}
|
||||
className="text-accent-text underline-offset-2 hover:underline"
|
||||
>
|
||||
Activity
|
||||
</Link>
|
||||
<span className="text-text-muted">
|
||||
{EXECUTOR_COPY.honesty.notificationWhenDone} {EXECUTOR_COPY.honesty.watchQueued}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -78,7 +90,7 @@ export function FixSignalButton({
|
||||
{state.phase === "sending"
|
||||
? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
|
||||
: <Wrench className="h-3.5 w-3.5" aria-hidden="true" />}
|
||||
{state.phase === "sending" ? "Dispatching…" : "Fix"}
|
||||
{state.phase === "sending" ? "Queuing…" : "Fix"}
|
||||
</button>
|
||||
{state.phase === "error" && <span className="ui-error text-xs">{state.message}</span>}
|
||||
</span>
|
||||
@@ -107,7 +119,7 @@ export function RunNextStepButton({
|
||||
{state.phase === "sending"
|
||||
? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
|
||||
: <Play className="h-3.5 w-3.5" aria-hidden="true" />}
|
||||
{state.phase === "sending" ? "Dispatching…" : "Run next step"}
|
||||
{state.phase === "sending" ? "Queuing…" : "Run next step"}
|
||||
</button>
|
||||
{state.phase === "error" && <span className="ui-error text-xs">{state.message}</span>}
|
||||
</span>
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Archive, Check, Code2, Copy, Layers, Loader2, MessageSquare, Pause, PenLine, Play, RefreshCw, Rocket, ScanEye, Star, Undo2, X } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Archive, Check, Code2, Copy, ExternalLink, Layers, Loader2, Pause, PenLine, Play, RefreshCw, Rocket, ScanEye, Star, Undo2, X } from "lucide-react";
|
||||
import { useFetch } from "@/hooks/use-fetch";
|
||||
import { useClipboard } from "@/hooks/use-clipboard";
|
||||
import { deleteJson, patchJson, postJson, throwApiError } from "@/lib/api/fetch";
|
||||
import { compactDurationHours, compactRelativeDate } from "@/lib/dates";
|
||||
import { FEEDBACK_SOURCE, FEEDBACK_STATUS, type FeedbackStatus } from "@/lib/constants/statuses";
|
||||
import { SYNTHESIZE_MIN_ITEMS } from "@/lib/feedback/compose-dispatch";
|
||||
import { deriveFeedbackWork, FEEDBACK_WORK_PHASE } from "@/lib/feedback/work-phase";
|
||||
import type { FeedbackListItem, FeedbackLoopMetrics } from "@/db/queries/site-feedback";
|
||||
import type { FeedbackListItemWithWork } from "@/lib/feedback/attach-work";
|
||||
import { FeedbackWorkBadge } from "@/components/feedback/FeedbackWorkBadge";
|
||||
import { fleetSurfaceHref } from "@/lib/fleet-context";
|
||||
import { EXECUTOR_COPY } from "@/config/executor-copy";
|
||||
import { DispatchedNote } from "@/components/projects/ProjectActionButtons";
|
||||
|
||||
type WidgetTokenInfo = {
|
||||
token: string;
|
||||
@@ -21,12 +29,12 @@ type WidgetTokenInfo = {
|
||||
/**
|
||||
* Visitor-feedback inbox for one project — submissions from the embeddable
|
||||
* widget (docs/architecture/feedback-widget.md). The one thing that matters
|
||||
* per row is "Dispatch fix": feedback becomes fleet work without leaving the
|
||||
* per row is Implement: feedback becomes fleet work without leaving the
|
||||
* row. The empty state IS the widget setup card — discovery and activation
|
||||
* in one place.
|
||||
*/
|
||||
export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
const feedbackFetch = useFetch<{ feedback: FeedbackListItem[]; metrics: FeedbackLoopMetrics | null }>(`/api/projects/${projectId}/feedback`);
|
||||
export function ProjectFeedbackSection({ projectId, projectName }: { projectId: string; projectName: string }) {
|
||||
const feedbackFetch = useFetch<{ feedback: FeedbackListItemWithWork[]; metrics: FeedbackLoopMetrics | null }>(`/api/projects/${projectId}/feedback`);
|
||||
const tokenFetch = useFetch<{ token: WidgetTokenInfo | null }>(`/api/projects/${projectId}/widget-token`);
|
||||
const [setupOpen, setSetupOpen] = useState(false);
|
||||
const [reviewOpen, setReviewOpen] = useState(false);
|
||||
@@ -34,6 +42,7 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [synthesizing, setSynthesizing] = useState(false);
|
||||
const [synthesized, setSynthesized] = useState(false);
|
||||
const [batchBusy, setBatchBusy] = useState(false);
|
||||
|
||||
const items = (feedbackFetch.data?.feedback ?? []).filter(
|
||||
(f) => f.status !== FEEDBACK_STATUS.ARCHIVED,
|
||||
@@ -43,6 +52,18 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
const token = tokenFetch.data?.token ?? null;
|
||||
const showSetup = setupOpen || (!tokenFetch.loading && !token);
|
||||
|
||||
// Keep work labels honest while something is in flight.
|
||||
useEffect(() => {
|
||||
const live = items.some((f) => {
|
||||
const w = "work" in f && f.work ? f.work.phase : null;
|
||||
return w === FEEDBACK_WORK_PHASE.QUEUED || w === FEEDBACK_WORK_PHASE.WORKING;
|
||||
});
|
||||
if (!live) return;
|
||||
const t = window.setInterval(() => feedbackFetch.refetch(), 8_000);
|
||||
return () => window.clearInterval(t);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- poll while any row is live; refetch identity is stable enough
|
||||
}, [items.map((f) => ("work" in f && f.work ? f.work.phase : f.status)).join("|")]);
|
||||
|
||||
async function act(id: string, run: () => Promise<Response>, fallback: string) {
|
||||
setBusyId(id);
|
||||
setError(null);
|
||||
@@ -58,7 +79,7 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
}
|
||||
|
||||
const dispatchFix = (id: string, note?: string) =>
|
||||
act(id, () => postJson(`/api/feedback/${id}/dispatch`, note ? { note } : {}), "Dispatch failed");
|
||||
act(id, () => postJson(`/api/feedback/${id}/dispatch`, note ? { note } : {}), "Could not queue the fix");
|
||||
|
||||
// High-volume inbox: shift the unit of action from item to theme. An agent
|
||||
// clusters the NEW items into briefs and files them back into this inbox.
|
||||
@@ -75,6 +96,20 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
setSynthesizing(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatchAll() {
|
||||
setBatchBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await postJson(`/api/projects/${projectId}/feedback/dispatch-batch`, {});
|
||||
if (!res.ok) await throwApiError(res, "Implement all failed");
|
||||
feedbackFetch.refetch();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Implement all failed");
|
||||
} finally {
|
||||
setBatchBusy(false);
|
||||
}
|
||||
}
|
||||
const setStatus = (id: string, status: FeedbackStatus) =>
|
||||
act(id, () => patchJson(`/api/feedback/${id}`, { status }), "Update failed");
|
||||
|
||||
@@ -94,20 +129,32 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{token && newCount >= 5 && (
|
||||
{token && items.length >= 2 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={dispatchAll}
|
||||
disabled={batchBusy || busyId !== null}
|
||||
className="ui-btn-save gap-1.5"
|
||||
title="One agent run covering every new report (local Fleet Runner or cloud builder)"
|
||||
>
|
||||
{batchBusy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3.5 w-3.5" />}
|
||||
Implement all as one
|
||||
</button>
|
||||
)}
|
||||
{token && newCount >= SYNTHESIZE_MIN_ITEMS && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={synthesize}
|
||||
disabled={synthesizing || synthesized}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title="Dispatch an agent to cluster the new items into structured briefs, filed back into this inbox"
|
||||
title="Queue an agent to cluster the new items into structured briefs, filed back into this inbox"
|
||||
>
|
||||
{synthesizing ? <Loader2 className="ui-spinner-xs" /> : <Layers className="h-3.5 w-3.5" />}
|
||||
{synthesized ? "Synthesis dispatched" : "Synthesize"}
|
||||
{synthesized ? "Synthesis queued" : "Synthesize"}
|
||||
</button>
|
||||
)}
|
||||
{token && (
|
||||
<button type="button" onClick={() => setReviewOpen((v) => !v)} className="ui-btn-secondary gap-1.5" title="Dispatch an agent to visually review a page and file findings here">
|
||||
<button type="button" onClick={() => setReviewOpen((v) => !v)} className="ui-btn-secondary gap-1.5" title="Queue an agent to visually review a page and file findings here">
|
||||
<ScanEye className="h-3.5 w-3.5" />
|
||||
AI review
|
||||
</button>
|
||||
@@ -122,14 +169,22 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
{reviewOpen && token && (
|
||||
<AiReviewCard
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
defaultUrl={items.find((f) => f.url)?.url ?? ""}
|
||||
onClose={() => setReviewOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{synthesized && (
|
||||
<p className="mb-3">
|
||||
<DispatchedNote workspaceKey={projectName} />
|
||||
</p>
|
||||
)}
|
||||
|
||||
{showSetup && (
|
||||
<WidgetSetupCard
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
token={token}
|
||||
loading={tokenFetch.loading}
|
||||
onChanged={() => {
|
||||
@@ -160,6 +215,7 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
<FeedbackRow
|
||||
key={f.id}
|
||||
feedback={f}
|
||||
projectName={projectName}
|
||||
busy={busyId === f.id}
|
||||
onDispatch={(note) => dispatchFix(f.id, note)}
|
||||
onResolve={() => setStatus(f.id, FEEDBACK_STATUS.RESOLVED)}
|
||||
@@ -176,6 +232,7 @@ export function ProjectFeedbackSection({ projectId }: { projectId: string }) {
|
||||
|
||||
function FeedbackRow({
|
||||
feedback: f,
|
||||
projectName,
|
||||
busy,
|
||||
onDispatch,
|
||||
onResolve,
|
||||
@@ -183,7 +240,8 @@ function FeedbackRow({
|
||||
onReopen,
|
||||
onFeature,
|
||||
}: {
|
||||
feedback: FeedbackListItem;
|
||||
feedback: FeedbackListItemWithWork | FeedbackListItem;
|
||||
projectName: string;
|
||||
busy: boolean;
|
||||
onDispatch: (note?: string) => void;
|
||||
onResolve: () => void;
|
||||
@@ -195,6 +253,15 @@ function FeedbackRow({
|
||||
// the dispatch prompt. Plain Dispatch stays one-click.
|
||||
const [noteOpen, setNoteOpen] = useState(false);
|
||||
const [note, setNote] = useState("");
|
||||
const work = "work" in f && f.work ? f.work : deriveFeedbackWork(f.status, null);
|
||||
const controlHref = fleetSurfaceHref("control", projectName);
|
||||
const terminalHref = fleetSurfaceHref("terminal", projectName);
|
||||
const watchLive = work.phase === FEEDBACK_WORK_PHASE.WORKING;
|
||||
const progressHref = watchLive ? terminalHref : controlHref;
|
||||
const progressLabel = watchLive ? "Watch" : "Open on Control";
|
||||
const progressTitle = watchLive
|
||||
? (work.detail ?? "Live agent session")
|
||||
: "Open this project on Control — Terminal is empty until a session is actually running";
|
||||
// Agent-filed rows get a typed badge instead of their magic contact string.
|
||||
const agentBadge =
|
||||
f.source === FEEDBACK_SOURCE.AI_REVIEW ? "AI review"
|
||||
@@ -205,33 +272,36 @@ function FeedbackRow({
|
||||
f.scope,
|
||||
!agentBadge && f.contact,
|
||||
compactRelativeDate(f.createdAt),
|
||||
// Resolution evidence: WHAT closed this row, not just that it's green.
|
||||
f.status === FEEDBACK_STATUS.RESOLVED && f.resolvedAt && `resolved ${compactRelativeDate(f.resolvedAt)}`,
|
||||
f.status === FEEDBACK_STATUS.RESOLVED && f.dispatchedRunId && `by run ${f.dispatchedRunId.slice(0, 8)}`,
|
||||
].filter(Boolean);
|
||||
|
||||
const dotClass =
|
||||
work.phase === FEEDBACK_WORK_PHASE.WORKING || work.phase === FEEDBACK_WORK_PHASE.DONE
|
||||
? "ui-dot-positive mt-1.5"
|
||||
: work.phase === FEEDBACK_WORK_PHASE.FAILED || work.phase === FEEDBACK_WORK_PHASE.STUCK
|
||||
? "ui-dot-negative mt-1.5"
|
||||
: work.phase === FEEDBACK_WORK_PHASE.QUEUED || work.phase === FEEDBACK_WORK_PHASE.NOT_STARTED
|
||||
? "ui-dot-warning mt-1.5"
|
||||
: "ui-dot-neutral mt-1.5";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 py-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-start gap-2">
|
||||
<span
|
||||
className={
|
||||
f.status === FEEDBACK_STATUS.NEW
|
||||
? "ui-dot-warning mt-1.5"
|
||||
: f.status === FEEDBACK_STATUS.RESOLVED
|
||||
? "ui-dot-positive mt-1.5"
|
||||
: "ui-dot-neutral mt-1.5"
|
||||
}
|
||||
aria-label={`Status: ${f.status}`}
|
||||
/>
|
||||
<span className={dotClass} aria-label={work.label} />
|
||||
<p className="min-w-0 text-sm leading-relaxed text-text-primary">{f.suggestion}</p>
|
||||
<FeedbackWorkBadge work={work} />
|
||||
{agentBadge && <span className="ui-tag shrink-0">{agentBadge}</span>}
|
||||
{f.duplicateCount > 1 && (
|
||||
<span className="ui-badge shrink-0" title={`Reported ${f.duplicateCount} times`}>×{f.duplicateCount}</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 pl-4 text-xs text-text-tertiary">{meta.join(" · ")}</p>
|
||||
{work.detail && (
|
||||
<p className="mt-0.5 pl-4 text-xs text-text-secondary">{work.detail}</p>
|
||||
)}
|
||||
{f.selectedElements && f.selectedElements.length > 0 && (
|
||||
<p className="mt-0.5 truncate pl-4 font-mono text-micro text-text-muted">
|
||||
{f.selectedElements.map((el) => el.selector).join(" ")}
|
||||
@@ -256,16 +326,56 @@ function FeedbackRow({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5 pl-4 sm:pl-0">
|
||||
{f.status === FEEDBACK_STATUS.DISPATCHED ? (
|
||||
{work.phase === FEEDBACK_WORK_PHASE.NOT_STARTED ? (
|
||||
<>
|
||||
<span className="ui-tag">dispatched</span>
|
||||
<button type="button" onClick={() => onDispatch()} disabled={busy} className="ui-btn-save gap-1.5" title="Ask the agent to fix this">
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Implement
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNoteOpen((v) => !v)}
|
||||
disabled={busy}
|
||||
className="ui-btn-icon"
|
||||
title="Add an instruction, then implement"
|
||||
aria-label="Add an instruction"
|
||||
aria-expanded={noteOpen}
|
||||
>
|
||||
<PenLine className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button type="button" onClick={onResolve} disabled={busy} className="ui-btn-icon" title="Mark resolved" aria-label="Mark resolved">
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</>
|
||||
) : work.phase === FEEDBACK_WORK_PHASE.QUEUED || work.phase === FEEDBACK_WORK_PHASE.WORKING ? (
|
||||
<>
|
||||
<a href={progressHref} className="ui-btn-save gap-1" title={progressTitle}>
|
||||
{progressLabel}
|
||||
</a>
|
||||
<button type="button" onClick={onResolve} disabled={busy} className="ui-btn-secondary gap-1" title="Mark resolved">
|
||||
<Check className="h-3 w-3" /> Resolve
|
||||
</button>
|
||||
</>
|
||||
) : work.phase === FEEDBACK_WORK_PHASE.STUCK || work.phase === FEEDBACK_WORK_PHASE.FAILED ? (
|
||||
<>
|
||||
<a href={progressHref} className="ui-btn-secondary gap-1" title={progressTitle}>{progressLabel}</a>
|
||||
<button type="button" onClick={() => onDispatch()} disabled={busy} className="ui-btn-save gap-1.5" title="Queue again">
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Retry
|
||||
</button>
|
||||
<button type="button" onClick={onResolve} disabled={busy} className="ui-btn-icon" title="Mark resolved" aria-label="Mark resolved">
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</>
|
||||
) : work.phase === FEEDBACK_WORK_PHASE.DONE && f.status !== FEEDBACK_STATUS.RESOLVED ? (
|
||||
<>
|
||||
<button type="button" onClick={onResolve} disabled={busy} className="ui-btn-save gap-1">
|
||||
<Check className="h-3 w-3" /> Resolve
|
||||
</button>
|
||||
<a href={progressHref} className="ui-btn-secondary gap-1" title={progressTitle}>{progressLabel}</a>
|
||||
</>
|
||||
) : f.status === FEEDBACK_STATUS.RESOLVED ? (
|
||||
<>
|
||||
<span className="ui-tag-positive">resolved</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onFeature}
|
||||
@@ -278,28 +388,7 @@ function FeedbackRow({
|
||||
<Star className="h-3.5 w-3.5" fill={f.featuredAt ? "currentColor" : "none"} />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button type="button" onClick={() => onDispatch()} disabled={busy} className="ui-btn-save gap-1.5" title="Send to an agent as a fix task">
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Dispatch fix
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNoteOpen((v) => !v)}
|
||||
disabled={busy}
|
||||
className="ui-btn-icon"
|
||||
title="Add an instruction to the dispatch"
|
||||
aria-label="Add an instruction to the dispatch"
|
||||
aria-expanded={noteOpen}
|
||||
>
|
||||
<PenLine className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button type="button" onClick={onResolve} disabled={busy} className="ui-btn-icon" title="Mark resolved" aria-label="Mark resolved">
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
) : null}
|
||||
{f.status === FEEDBACK_STATUS.RESOLVED ? (
|
||||
<button type="button" onClick={onReopen} disabled={busy} className="ui-btn-icon" title="Reopen" aria-label="Reopen">
|
||||
<Undo2 className="h-3.5 w-3.5" />
|
||||
@@ -311,7 +400,7 @@ function FeedbackRow({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{noteOpen && f.status !== FEEDBACK_STATUS.DISPATCHED && f.status !== FEEDBACK_STATUS.RESOLVED && (
|
||||
{noteOpen && work.phase === FEEDBACK_WORK_PHASE.NOT_STARTED && (
|
||||
<div className="flex items-center gap-2 pl-4">
|
||||
<input
|
||||
type="text"
|
||||
@@ -331,7 +420,7 @@ function FeedbackRow({
|
||||
className="ui-btn-save gap-1.5"
|
||||
>
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3 w-3" />}
|
||||
Dispatch
|
||||
Implement
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -341,12 +430,14 @@ function FeedbackRow({
|
||||
|
||||
function WidgetSetupCard({
|
||||
projectId,
|
||||
projectName,
|
||||
token,
|
||||
loading,
|
||||
onChanged,
|
||||
onClose,
|
||||
}: {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
token: WidgetTokenInfo | null;
|
||||
loading: boolean;
|
||||
onChanged: () => void;
|
||||
@@ -354,21 +445,46 @@ function WidgetSetupCard({
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// One-click install/uninstall: dispatches an agent to land/remove the embed
|
||||
// in the project's own repo. Tracks which mode was dispatched this session.
|
||||
const [agentBusy, setAgentBusy] = useState(false);
|
||||
const [agentDone, setAgentDone] = useState<"install" | "uninstall" | null>(null);
|
||||
const [agentPhase, setAgentPhase] = useState<"idle" | "queued" | "failed">("idle");
|
||||
const [agentNote, setAgentNote] = useState<string | null>(null);
|
||||
const [moreOpen, setMoreOpen] = useState(false);
|
||||
const { copied, copy } = useClipboard();
|
||||
|
||||
const controlHref = fleetSurfaceHref("control", projectName);
|
||||
const terminalHref = fleetSurfaceHref("terminal", projectName);
|
||||
const activityHref = fleetSurfaceHref("activity", projectName);
|
||||
const site = token?.lastSeenOrigin ?? token?.origins?.[0] ?? null;
|
||||
const live = !!token?.lastSeenAt && token.status !== "paused";
|
||||
const paused = token?.status === "paused";
|
||||
|
||||
async function dispatchAgent(mode: "install" | "uninstall") {
|
||||
setAgentBusy(true);
|
||||
setError(null);
|
||||
setAgentNote(null);
|
||||
setAgentPhase("idle");
|
||||
try {
|
||||
const res = await postJson(`/api/projects/${projectId}/widget-token/install`, { mode });
|
||||
if (!res.ok) await throwApiError(res, `Could not dispatch the ${mode}`);
|
||||
setAgentDone(mode);
|
||||
const body = (await res.json().catch(() => ({}))) as {
|
||||
error?: string;
|
||||
hint?: string;
|
||||
nextStep?: string;
|
||||
watchUrl?: string;
|
||||
};
|
||||
if (!res.ok) {
|
||||
setAgentPhase("failed");
|
||||
setError([body.error, body.hint].filter(Boolean).join(" ") || `Could not start the ${mode}`);
|
||||
return;
|
||||
}
|
||||
setAgentPhase("queued");
|
||||
setAgentNote(
|
||||
body.nextStep
|
||||
|| `${EXECUTOR_COPY.honesty.watchQueued} ${EXECUTOR_COPY.honesty.notificationWhenDone}`,
|
||||
);
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : `Could not dispatch the ${mode}`);
|
||||
setAgentPhase("failed");
|
||||
setError(e instanceof Error ? e.message : `Could not start the ${mode}`);
|
||||
} finally {
|
||||
setAgentBusy(false);
|
||||
}
|
||||
@@ -394,137 +510,196 @@ function WidgetSetupCard({
|
||||
const setTokenStatus = (status: "active" | "paused") =>
|
||||
mutate(() => postJson(`/api/projects/${projectId}/widget-token`, { status }), "Could not update widget");
|
||||
|
||||
const paused = token?.status === "paused";
|
||||
const statusCallout = live
|
||||
? "ui-callout-positive flex-col sm:flex-row sm:items-center"
|
||||
: paused
|
||||
? "ui-callout-warning flex-col sm:flex-row sm:items-center"
|
||||
: "ui-callout-accent flex-col sm:flex-row sm:items-center";
|
||||
|
||||
return (
|
||||
<div className="ui-card-shell mb-4 p-4 sm:p-5">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-text-primary">
|
||||
<MessageSquare className="h-4 w-4" />
|
||||
Feedback widget
|
||||
<section className="ui-panel mb-5 p-5 sm:p-6">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h2 className="ui-page-title text-lg sm:text-xl">Feedback widget</h2>
|
||||
<p className="ui-page-subtitle">
|
||||
Visitors point at the broken element. Reports land here. One click sends the fix to the project agent.
|
||||
</p>
|
||||
</div>
|
||||
<p className="mt-1 text-xs leading-relaxed text-text-muted">
|
||||
One script tag on your site adds a feedback button — visitors can point at the exact
|
||||
element that's broken, and submissions land in this inbox ready to dispatch.
|
||||
</p>
|
||||
{onClose && (
|
||||
<button type="button" onClick={onClose} className="ui-btn-icon shrink-0" aria-label="Close widget setup">
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{onClose && (
|
||||
<button type="button" onClick={onClose} className="ui-btn-icon" aria-label="Close widget setup">
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="mt-3 flex items-center gap-2 text-xs text-text-tertiary">
|
||||
<Loader2 className="ui-spinner-xs" /> Loading…
|
||||
</div>
|
||||
) : token ? (
|
||||
<>
|
||||
<WidgetLiveStatus token={token} paused={paused} />
|
||||
<div className="mt-3 overflow-x-auto rounded-lg border border-border-subtle bg-surface-base p-3">
|
||||
<code className="whitespace-pre font-mono text-micro text-text-secondary">{token.snippet}</code>
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 text-xs text-text-tertiary">
|
||||
<Loader2 className="ui-spinner-xs" /> Loading…
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<button type="button" onClick={() => copy(token.snippet)} className="ui-btn-save gap-1.5">
|
||||
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
{copied ? "Copied" : "Copy snippet"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dispatchAgent("install")}
|
||||
disabled={agentBusy || agentDone === "install"}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title="Dispatch an agent to add the snippet to this project's codebase and ship it"
|
||||
>
|
||||
{agentBusy ? <Loader2 className="ui-spinner-xs" /> : agentDone === "install" ? <Check className="h-3.5 w-3.5" /> : <Rocket className="h-3.5 w-3.5" />}
|
||||
{agentDone === "install" ? "Install dispatched" : "Install via agent"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dispatchAgent("uninstall")}
|
||||
disabled={agentBusy || agentDone === "uninstall"}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title="Dispatch an agent to remove the embed from this project's codebase (Pause hides it instantly without a deploy)"
|
||||
>
|
||||
{agentDone === "uninstall" ? <Check className="h-3.5 w-3.5" /> : <Undo2 className="h-3.5 w-3.5" />}
|
||||
{agentDone === "uninstall" ? "Removal dispatched" : "Remove via agent"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTokenStatus(paused ? "active" : "paused")}
|
||||
disabled={busy}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title={paused ? "Show the widget on your site again" : "Hide the widget on your site instantly — no deploy needed"}
|
||||
>
|
||||
{paused ? <Play className="h-3.5 w-3.5" /> : <Pause className="h-3.5 w-3.5" />}
|
||||
{paused ? "Resume" : "Pause"}
|
||||
</button>
|
||||
<button type="button" onClick={rotate} disabled={busy} className="ui-btn-secondary gap-1.5" title="Mint a new token; the old snippet stops working">
|
||||
<RefreshCw className="h-3.5 w-3.5" /> Rotate
|
||||
</button>
|
||||
<button type="button" onClick={revoke} disabled={busy} className="ui-btn-danger">
|
||||
Disable
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="mt-3">
|
||||
<button type="button" onClick={create} disabled={busy} className="ui-btn-save gap-1.5">
|
||||
{busy ? <Loader2 className="ui-spinner-xs" /> : <Code2 className="h-3.5 w-3.5" />}
|
||||
Enable widget
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="mt-2 ui-error">{error}</p>}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className={statusCallout}>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium text-text-primary">
|
||||
{paused
|
||||
? "Paused on the live site"
|
||||
: live
|
||||
? `Live${site ? ` · ${site.replace(/^https:\/\//, "")}` : ""}`
|
||||
: token
|
||||
? "Token ready — not seen on the live site yet"
|
||||
: "Not enabled"}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-text-secondary">
|
||||
{paused
|
||||
? "Resume to show the FAB again — no deploy needed."
|
||||
: live
|
||||
? `Last boot ${compactRelativeDate(new Date(token!.lastSeenAt!))}`
|
||||
: token
|
||||
? `The script must run on ${site ?? "the live origin"} (CSP must allow fleetcrown.orangecat.ch). A boot heartbeat is Live — HTML containing the tag is not.`
|
||||
: "Enable a token, then add the script to the site (copy, or queue an agent)."}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!token ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dispatchAgent("install")}
|
||||
disabled={agentBusy}
|
||||
className="ui-btn-save gap-1.5"
|
||||
>
|
||||
{agentBusy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3.5 w-3.5" />}
|
||||
Enable & install
|
||||
</button>
|
||||
<button type="button" onClick={create} disabled={busy} className="ui-btn-secondary gap-1.5">
|
||||
Enable only
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button type="button" onClick={() => copy(token.snippet)} className="ui-btn-save gap-1.5">
|
||||
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
{copied ? "Copied" : "Copy snippet"}
|
||||
</button>
|
||||
{!live && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dispatchAgent("install")}
|
||||
disabled={agentBusy || agentPhase === "queued"}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
title="Queues an agent on Control. Does not mean the widget is live."
|
||||
>
|
||||
{agentBusy ? <Loader2 className="ui-spinner-xs" /> : <Rocket className="h-3.5 w-3.5" />}
|
||||
{agentPhase === "queued" ? "Install queued" : "Install via agent"}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{token && (
|
||||
<details className="ui-list-row" open={!live}>
|
||||
<summary className="cursor-pointer text-xs font-medium text-text-secondary">
|
||||
Snippet
|
||||
</summary>
|
||||
<code className="mt-2 block overflow-x-auto whitespace-pre font-mono text-micro leading-relaxed text-text-tertiary">
|
||||
{token.snippet}
|
||||
</code>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{(agentNote || agentPhase === "queued") && (
|
||||
<div className="ui-callout-warning flex-col items-stretch">
|
||||
<p className="text-xs font-medium text-text-primary">
|
||||
{agentPhase === "queued" ? "Queued — not confirmed working" : "Install"}
|
||||
</p>
|
||||
{agentNote && <p className="mt-1 text-xs leading-relaxed text-text-secondary">{agentNote}</p>}
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs">
|
||||
<Link href={activityHref} className="inline-flex items-center gap-1 text-accent-text underline-offset-2 hover:underline">
|
||||
Activity <ExternalLink className="h-3 w-3" />
|
||||
</Link>
|
||||
<Link href={controlHref} className="inline-flex items-center gap-1 text-accent-text underline-offset-2 hover:underline">
|
||||
Control <ExternalLink className="h-3 w-3" />
|
||||
</Link>
|
||||
<Link href={terminalHref} className="inline-flex items-center gap-1 text-text-tertiary underline-offset-2 hover:underline">
|
||||
Terminal · Cloud <ExternalLink className="h-3 w-3" />
|
||||
</Link>
|
||||
</div>
|
||||
<p className="mt-2 text-micro text-text-muted">
|
||||
{EXECUTOR_COPY.honesty.watchQueued} {EXECUTOR_COPY.honesty.notificationWhenDone} Activity shows every inject attempt and the real error.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{token && (
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-border-subtle pt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTokenStatus(paused ? "active" : "paused")}
|
||||
disabled={busy}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
>
|
||||
{paused ? <Play className="h-3.5 w-3.5" /> : <Pause className="h-3.5 w-3.5" />}
|
||||
{paused ? "Resume" : "Pause"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMoreOpen((v) => !v)}
|
||||
className="ui-btn-ghost text-xs text-text-tertiary"
|
||||
aria-expanded={moreOpen}
|
||||
>
|
||||
{moreOpen ? "Fewer actions" : "More"}
|
||||
</button>
|
||||
{moreOpen && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dispatchAgent("uninstall")}
|
||||
disabled={agentBusy}
|
||||
className="ui-btn-secondary gap-1.5"
|
||||
>
|
||||
<Undo2 className="h-3.5 w-3.5" />
|
||||
Remove via agent
|
||||
</button>
|
||||
<button type="button" onClick={rotate} disabled={busy} className="ui-btn-secondary gap-1.5">
|
||||
<RefreshCw className="h-3.5 w-3.5" /> Rotate token
|
||||
</button>
|
||||
<button type="button" onClick={revoke} disabled={busy} className="ui-btn-danger">
|
||||
Disable
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{error && <p className="ui-error">{error}</p>}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Observed truth only: "Live" means the widget's boot heartbeat actually
|
||||
* arrived from the site — never that we handed out a snippet. Every state
|
||||
* names its one next action.
|
||||
* arrived from the site — never that we handed out a snippet.
|
||||
*/
|
||||
function WidgetLiveStatus({ token, paused }: { token: WidgetTokenInfo; paused: boolean }) {
|
||||
const site = token.lastSeenOrigin ?? token.origins?.[0] ?? null;
|
||||
if (paused) {
|
||||
return (
|
||||
<p className="mt-3 flex items-center gap-2 text-xs text-text-secondary">
|
||||
<span className="ui-dot-warning" aria-hidden="true" />
|
||||
Paused — the widget is hidden on your site. Resume to show it again.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (!token.lastSeenAt) {
|
||||
return (
|
||||
<p className="mt-3 flex items-center gap-2 text-xs text-text-secondary">
|
||||
<span className="ui-dot-warning" aria-hidden="true" />
|
||||
Waiting for the first page load{site ? ` on ${site}` : ""} — add the snippet below to your site.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p className="mt-3 flex items-center gap-2 text-xs text-text-secondary">
|
||||
<span className="ui-dot-positive" aria-hidden="true" />
|
||||
Live{site ? ` on ${site}` : ""} · last seen {compactRelativeDate(new Date(token.lastSeenAt))}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function AiReviewCard({
|
||||
projectId,
|
||||
projectName,
|
||||
defaultUrl,
|
||||
onClose,
|
||||
}: {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
defaultUrl: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [url, setUrl] = useState(defaultUrl);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [dispatched, setDispatched] = useState(false);
|
||||
const [queued, setQueued] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function dispatchReview() {
|
||||
@@ -532,10 +707,10 @@ function AiReviewCard({
|
||||
setError(null);
|
||||
try {
|
||||
const res = await postJson(`/api/projects/${projectId}/feedback/ai-review`, { url });
|
||||
if (!res.ok) await throwApiError(res, "Could not dispatch the review");
|
||||
setDispatched(true);
|
||||
if (!res.ok) await throwApiError(res, "Could not queue the review");
|
||||
setQueued(true);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Could not dispatch the review");
|
||||
setError(e instanceof Error ? e.message : "Could not queue the review");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -551,7 +726,7 @@ function AiReviewCard({
|
||||
</div>
|
||||
<p className="mt-1 text-xs leading-relaxed text-text-muted">
|
||||
An agent opens the page in a headless browser, reviews it on desktop and mobile,
|
||||
and files each issue into this inbox — you triage and dispatch fixes as usual.
|
||||
and files each issue into this inbox — you triage and implement fixes as usual.
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" onClick={onClose} className="ui-btn-icon" aria-label="Close AI review">
|
||||
@@ -559,11 +734,10 @@ function AiReviewCard({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{dispatched ? (
|
||||
<p className="mt-3 flex items-center gap-1.5 text-xs text-text-secondary">
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
Review dispatched — findings land here when the agent finishes.
|
||||
</p>
|
||||
{queued ? (
|
||||
<div className="mt-3">
|
||||
<DispatchedNote workspaceKey={projectName} />
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="mt-3 flex flex-wrap items-center gap-2"
|
||||
|
||||
@@ -234,7 +234,7 @@ export function ProjectWorkspaceView({
|
||||
<DoneSection dossier={dossier} />
|
||||
</section>
|
||||
|
||||
{!dossier.readonly && <ProjectFeedbackSection projectId={project.id} />}
|
||||
{!dossier.readonly && <ProjectFeedbackSection projectId={project.id} projectName={project.name} />}
|
||||
|
||||
{!dossier.readonly && (
|
||||
<ProjectSettingsPanel
|
||||
|
||||
@@ -11,15 +11,18 @@ const FILTERS: {
|
||||
tone?: "warning";
|
||||
count: (stats: ProjectsPageStats) => number;
|
||||
hidden?: (stats: ProjectsPageStats) => boolean;
|
||||
title?: string;
|
||||
}[] = [
|
||||
{ id: null, label: "All", icon: FolderKanban, count: (s) => s.total },
|
||||
{
|
||||
id: "attention",
|
||||
label: "Attention",
|
||||
label: "Site issues",
|
||||
icon: AlertTriangle,
|
||||
tone: "warning",
|
||||
count: (s) => s.attention,
|
||||
hidden: (s) => s.attention === 0,
|
||||
title:
|
||||
"Live URL down, or attrs: security_vulnerability / broken_features / deployment_issue. Not a general “needs work” list.",
|
||||
},
|
||||
{
|
||||
id: "next-step",
|
||||
@@ -66,6 +69,7 @@ export function ProjectsSummary({
|
||||
type="button"
|
||||
onClick={() => onFilter(active ? null : chip.id)}
|
||||
aria-pressed={active}
|
||||
title={chip.title}
|
||||
className={cn(
|
||||
"ui-projects-filter-chip",
|
||||
active && "ui-projects-filter-chip-active",
|
||||
|
||||
@@ -109,10 +109,13 @@ export function ProjectsWorkspace({ projects }: { projects: ProjectGridRow[] })
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{showAttentionCards && (
|
||||
<section className="space-y-2" aria-label="Projects needing attention">
|
||||
<section className="space-y-2" aria-label="Projects with site or risk flags">
|
||||
{attention.length > 1 && (
|
||||
<h2 className="ui-projects-section-label">Needs attention</h2>
|
||||
<h2 className="ui-projects-section-label">Site / risk flags</h2>
|
||||
)}
|
||||
<p className="text-xs text-text-tertiary">
|
||||
Only projects with a down live URL or an explicit flag (security / broken feature / deploy issue). Not a general priority list.
|
||||
</p>
|
||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
|
||||
{attention.map((project) => (
|
||||
<ProjectGridCard key={project.id} project={project} />
|
||||
@@ -125,7 +128,7 @@ export function ProjectsWorkspace({ projects }: { projects: ProjectGridRow[] })
|
||||
<section aria-label="All projects">
|
||||
{showAttentionCards && (
|
||||
<h2 className="ui-projects-section-label mb-2">
|
||||
{pageFilter || debouncedQuery ? "Matching projects" : "All others"}
|
||||
{pageFilter || debouncedQuery ? "Matching projects" : "Fleet"}
|
||||
</h2>
|
||||
)}
|
||||
<div className="ui-projects-list flex flex-col">
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
projectFromFleetRoute,
|
||||
readRememberedFleetProject,
|
||||
rememberFleetProject,
|
||||
type FleetSurfaceId,
|
||||
type FleetWorkspaceSurfaceId,
|
||||
} from "@/lib/fleet-context";
|
||||
|
||||
const ICONS = {
|
||||
@@ -20,7 +20,7 @@ const ICONS = {
|
||||
chat: MessageSquare,
|
||||
control: SlidersHorizontal,
|
||||
terminal: SquareTerminal,
|
||||
} satisfies Record<FleetSurfaceId, typeof MessageSquare>;
|
||||
} satisfies Record<FleetWorkspaceSurfaceId, typeof MessageSquare>;
|
||||
|
||||
function subscribeToFleetProject(onStoreChange: () => void) {
|
||||
window.addEventListener(FLEET_PROJECT_EVENT, onStoreChange);
|
||||
|
||||
@@ -308,7 +308,15 @@ export function TerminalSurface({
|
||||
// Three honest states, in priority order: gated (this account may not use
|
||||
// this builder) → offline (allowed, nothing connected) → online-but-idle
|
||||
// (allowed and connected, just nothing running → offer the next step).
|
||||
const hint = gatedMessage ?? (offline ? copy.offlineHint : copy.emptyHint);
|
||||
// Deep link ?tab=X with no session is the common Install/Implement Watch
|
||||
// dead-end — say so plainly instead of a generic empty cloud.
|
||||
const tabHint = initialTab && !offline && !gatedMessage
|
||||
? `No live agent session for “${initialTab}”. If you just clicked Implement or Install, open Control — Attention shows Retry when the prompt never started. Terminal only shows sessions that are actually running.`
|
||||
: null;
|
||||
const hint = gatedMessage ?? (offline ? copy.offlineHint : (tabHint ?? copy.emptyHint));
|
||||
const controlHref = initialTab
|
||||
? `/control?focus=${encodeURIComponent(initialTab)}`
|
||||
: "/control";
|
||||
return (
|
||||
<div className="ui-empty-page">
|
||||
<MonitorSmartphone className="h-6 w-6 text-text-muted" aria-hidden="true" />
|
||||
@@ -317,7 +325,7 @@ export function TerminalSurface({
|
||||
</p>
|
||||
<p className="max-w-md text-center text-xs text-text-muted">{hint}</p>
|
||||
{!gatedMessage && !offline && (
|
||||
<>
|
||||
<>
|
||||
<TerminalLaunch
|
||||
projects={context?.launchable ?? []}
|
||||
agents={agents}
|
||||
@@ -325,8 +333,8 @@ export function TerminalSurface({
|
||||
channel={channel}
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap justify-center gap-2">
|
||||
<Link href={controlHref} className="ui-btn-secondary">Open on Control</Link>
|
||||
<Link href="/loki" className="ui-btn-secondary">Ask Loki</Link>
|
||||
<Link href="/control" className="ui-btn-secondary">Control</Link>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -60,7 +60,7 @@ export const EXECUTOR_COPY = {
|
||||
/** Cloud web app always queues; this means a live builder will drain it. */
|
||||
queuedWithBuilderOnline: "With builder — starting shortly",
|
||||
queuedWithBuilderOnlineLong:
|
||||
"a builder is online and will claim it shortly. Use Control for state, or open Cloud terminal / This computer to watch and type in the agent session.",
|
||||
"a builder is online and will claim it shortly. Use Control for state, or open Cloud terminal / This computer to watch and type in the agent session. You get a notification when the run finishes.",
|
||||
|
||||
onboarding: {
|
||||
stepTitle: "You're ready to build",
|
||||
@@ -141,6 +141,8 @@ export const EXECUTOR_COPY = {
|
||||
// the chip only truthfully knows the builder is connected. Post-dispatch
|
||||
// confirmations keep their own "starting shortly" copy where it IS true.
|
||||
builderStarting: "Builder online",
|
||||
notificationWhenDone: "Notification when this run finishes.",
|
||||
watchQueued: "Watch Control for state. Terminal only while a session is running.",
|
||||
},
|
||||
|
||||
terminal: {
|
||||
@@ -157,7 +159,7 @@ export const EXECUTOR_COPY = {
|
||||
"Agents on the cloud builder (box-runner). Pick a project tab, click to focus, and type — keystrokes go straight to the agent PTY. Ctrl+C, arrows, and paste work.",
|
||||
cloudLoading: "Looking for agents on the cloud builder…",
|
||||
cloudEmpty: "Nothing running on the cloud builder.",
|
||||
cloudEmptyHint: "Start an agent below, or dispatch from Loki — running sessions appear here so you can type into them.",
|
||||
cloudEmptyHint: "Start an agent below, or dispatch from Control (Implement) or Loki. When an agent session actually starts, it appears here — an empty Terminal means nothing is running for this tab yet.",
|
||||
cloudOfflineHint: "The cloud builder (box-runner on Hetzner) is offline right now.",
|
||||
// Connected to the peek stream but no screen frames arrived → the runner is
|
||||
// wedged (e.g. its outbound fetch is failing). Honest, actionable — not a
|
||||
@@ -167,7 +169,7 @@ export const EXECUTOR_COPY = {
|
||||
thisComputerHelp:
|
||||
"Interactive view of agents on this computer via the desktop app. Same keystroke path as Cloud — click the terminal and type.",
|
||||
thisComputerEmpty: "Nothing running on this computer.",
|
||||
thisComputerEmptyHint: "Start an agent below, or dispatch from Loki — the live session shows up here.",
|
||||
thisComputerEmptyHint: "Start an agent below, or dispatch from Control or Loki — the live session shows up here only while an agent is running.",
|
||||
thisComputerOfflineHint: "Connect Fleet Runner on this computer to this account.",
|
||||
thisComputerLoading: "Looking for agents on this computer…",
|
||||
},
|
||||
|
||||
@@ -173,6 +173,16 @@ export async function getOrchestrationRunById(userId: string, id: string) {
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** Batch lookup for feedback work-phase enrichment. */
|
||||
export async function getOrchestrationRunsByIds(userId: string, ids: string[]) {
|
||||
if (ids.length === 0) return new Map<string, typeof orchestrationRuns.$inferSelect>();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(orchestrationRuns)
|
||||
.where(and(eq(orchestrationRuns.userId, userId), inArray(orchestrationRuns.id, ids)));
|
||||
return new Map(rows.map((r) => [r.id, r]));
|
||||
}
|
||||
|
||||
export async function cleanupStaleOrchestrationRuns(userId?: string) {
|
||||
// Did this run's project produce a handoff AFTER the run started? project_states
|
||||
// holds the box-pushed session state; a ready_at / session_updated_at newer
|
||||
|
||||
@@ -93,6 +93,13 @@ function fifoEligibilitySql() {
|
||||
AND r.finished_at IS NULL
|
||||
AND r.started_at > NOW() - INTERVAL '1 minute' * ${STALE_RUN_MINUTES}
|
||||
AND r.payload->>'sessionTab' IS NULL
|
||||
-- Orphan open runs (no unexecuted pending command) must not block the
|
||||
-- queue forever — that was the "Install queued → empty Terminal" wedge.
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM pending_commands pc
|
||||
WHERE pc.executed_at IS NULL
|
||||
AND pc.payload->>'runId' = r.id::text
|
||||
)
|
||||
AND (r.started_at, r.id) < (
|
||||
SELECT own.started_at, own.id FROM orchestration_runs own
|
||||
WHERE own.id = (${pendingCommands.payload}->>'runId')::uuid
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { and, eq, isNull, lt, or, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { entities, widgetTokens, type WidgetToken } from "@/db/schema";
|
||||
import { entities, userProjects, widgetTokens, type WidgetToken } from "@/db/schema";
|
||||
import { ENTITY_TYPE, WIDGET_TOKEN_STATUS, type WidgetTokenStatus } from "@/lib/constants/statuses";
|
||||
import { fetchAttributesByEntityIds } from "./utils";
|
||||
import { resolveProjectPublicOrigin } from "@/lib/feedback/project-site";
|
||||
|
||||
/**
|
||||
* Default a new token's origin allowlist from the project's registered prod
|
||||
* URL — the user made this decision once when they registered the project;
|
||||
* don't ask again at enable time. Same attr precedence as getProjectLinks.
|
||||
* Default a new token's origin allowlist from the project's live site
|
||||
* (user_projects.liveUrl first — Hetzner SSOT — then legacy attrs).
|
||||
*/
|
||||
async function defaultOriginsFromProject(projectId: string): Promise<string[] | null> {
|
||||
const attrs = (await fetchAttributesByEntityIds([projectId])).get(projectId) ?? {};
|
||||
const raw = attrs["production_url"] ?? attrs["url"];
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return [new URL(raw.startsWith("http") ? raw : `https://${raw}`).origin];
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
async function defaultOriginsFromProject(userId: string, projectId: string): Promise<string[] | null> {
|
||||
const origin = await resolveProjectPublicOrigin(userId, projectId);
|
||||
return origin ? [origin] : null;
|
||||
}
|
||||
|
||||
/** Token prefix — makes a leaked string instantly identifiable as a
|
||||
@@ -82,7 +76,7 @@ export async function upsertWidgetToken(userId: string, projectId: string, input
|
||||
const existing = await getActiveWidgetToken(userId, projectId);
|
||||
const origins = input.origins?.filter(Boolean)
|
||||
?? existing?.origins
|
||||
?? await defaultOriginsFromProject(projectId);
|
||||
?? await defaultOriginsFromProject(userId, projectId);
|
||||
const status = input.status ?? existing?.status ?? WIDGET_TOKEN_STATUS.ACTIVE;
|
||||
|
||||
if (existing && !input.rotate) {
|
||||
@@ -111,3 +105,91 @@ export async function revokeWidgetToken(userId: string, projectId: string): Prom
|
||||
.returning({ id: widgetTokens.id });
|
||||
return Boolean(revoked);
|
||||
}
|
||||
|
||||
const LIVE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export type WidgetCoverageItem = {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
hasToken: boolean;
|
||||
tokenStatus: string | null;
|
||||
lastSeenAt: string | null;
|
||||
lastSeenOrigin: string | null;
|
||||
productionUrl: string | null;
|
||||
gitUrl: string | null;
|
||||
/** Boot heartbeat within the last 7 days. */
|
||||
live: boolean;
|
||||
/** Missing token, paused, or never/not recently seen on a site-like project. */
|
||||
needsAttention: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fleet lens: which public sites should carry the feedback widget, and which
|
||||
* are missing / not live. Site-like = has user_projects.liveUrl or legacy
|
||||
* production_url/url — never gitUrl alone. Prefer liveUrl (Hetzner) over
|
||||
* stale entity attrs.
|
||||
*/
|
||||
export async function listWidgetCoverage(userId: string): Promise<WidgetCoverageItem[]> {
|
||||
const projects = await db
|
||||
.select({ id: entities.id, name: entities.name, gitUrl: entities.gitUrl })
|
||||
.from(entities)
|
||||
.where(and(eq(entities.userId, userId), eq(entities.type, ENTITY_TYPE.PROJECT)));
|
||||
|
||||
if (projects.length === 0) return [];
|
||||
|
||||
const [tokens, ups] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(widgetTokens)
|
||||
.where(and(eq(widgetTokens.userId, userId), isNull(widgetTokens.revokedAt))),
|
||||
db
|
||||
.select({
|
||||
entityProjectId: userProjects.entityProjectId,
|
||||
liveUrl: userProjects.liveUrl,
|
||||
gitUrl: userProjects.gitUrl,
|
||||
})
|
||||
.from(userProjects)
|
||||
.where(eq(userProjects.userId, userId)),
|
||||
]);
|
||||
const tokenByProject = new Map(tokens.map((t) => [t.projectId, t]));
|
||||
const upByEntity = new Map(
|
||||
ups.filter((u) => u.entityProjectId).map((u) => [u.entityProjectId!, u]),
|
||||
);
|
||||
const attrs = await fetchAttributesByEntityIds(projects.map((p) => p.id));
|
||||
const now = Date.now();
|
||||
|
||||
return projects
|
||||
.map((p) => {
|
||||
const t = tokenByProject.get(p.id);
|
||||
const up = upByEntity.get(p.id);
|
||||
const a = attrs.get(p.id) ?? {};
|
||||
const raw = up?.liveUrl ?? a.production_url ?? a.url ?? null;
|
||||
let productionUrl: string | null = null;
|
||||
if (raw) {
|
||||
try {
|
||||
productionUrl = new URL(raw.startsWith("http") ? raw : `https://${raw}`).origin;
|
||||
} catch {
|
||||
productionUrl = null;
|
||||
}
|
||||
}
|
||||
const live = !!(t?.lastSeenAt && now - t.lastSeenAt.getTime() < LIVE_WINDOW_MS);
|
||||
const siteLike = !!productionUrl;
|
||||
const needsAttention =
|
||||
siteLike && (!t || t.status !== WIDGET_TOKEN_STATUS.ACTIVE || !live);
|
||||
return {
|
||||
projectId: p.id,
|
||||
projectName: p.name,
|
||||
hasToken: !!t,
|
||||
tokenStatus: t?.status ?? null,
|
||||
lastSeenAt: t?.lastSeenAt?.toISOString() ?? null,
|
||||
lastSeenOrigin: t?.lastSeenOrigin ?? null,
|
||||
productionUrl,
|
||||
gitUrl: up?.gitUrl ?? p.gitUrl ?? null,
|
||||
live,
|
||||
needsAttention,
|
||||
};
|
||||
})
|
||||
.filter((p) => !!p.productionUrl)
|
||||
.sort((a, b) => Number(b.needsAttention) - Number(a.needsAttention) || a.projectName.localeCompare(b.projectName));
|
||||
}
|
||||
|
||||
@@ -81,6 +81,10 @@ export type EventStatus = (typeof EVENT_STATUS)[keyof typeof EVENT_STATUS];
|
||||
* Site-feedback inbox status — visitor feedback via the embeddable widget.
|
||||
* Nothing auto-dispatches; the operator triages.
|
||||
* Flow: new → dispatched → resolved, or new → archived.
|
||||
*
|
||||
* UI must NOT show the word "dispatched" as if work finished. Derive
|
||||
* FeedbackWorkView (lib/feedback/work-phase.ts): Not started / Queued /
|
||||
* Working now / Not running / Failed / Done.
|
||||
*/
|
||||
export const FEEDBACK_STATUS = {
|
||||
NEW: "new",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { getOrchestrationRunsByIds } from "@/db/queries/orchestration-runs";
|
||||
import type { FeedbackListItem } from "@/db/queries/site-feedback";
|
||||
import {
|
||||
deriveFeedbackWork,
|
||||
type FeedbackWorkView,
|
||||
type FeedbackRunSnapshot,
|
||||
} from "@/lib/feedback/work-phase";
|
||||
import type { OrchestrationState } from "@/lib/orchestration/contract";
|
||||
|
||||
export type FeedbackListItemWithWork = FeedbackListItem & { work: FeedbackWorkView };
|
||||
|
||||
/** Attach honest work-phase to inbox rows from linked orchestration runs. */
|
||||
export async function attachFeedbackWork(
|
||||
userId: string,
|
||||
items: FeedbackListItem[],
|
||||
): Promise<FeedbackListItemWithWork[]> {
|
||||
const runIds = [...new Set(items.map((i) => i.dispatchedRunId).filter((id): id is string => !!id))];
|
||||
const runs = await getOrchestrationRunsByIds(userId, runIds);
|
||||
|
||||
return items.map((item) => {
|
||||
const row = item.dispatchedRunId ? runs.get(item.dispatchedRunId) : undefined;
|
||||
const snap: FeedbackRunSnapshot | null = row
|
||||
? {
|
||||
id: row.id,
|
||||
state: row.state as OrchestrationState,
|
||||
outcome: row.outcome ?? null,
|
||||
startedAt: row.startedAt,
|
||||
finishedAt: row.finishedAt,
|
||||
deliveredAt: (row.payload as { deliveredAt?: string } | null)?.deliveredAt ?? null,
|
||||
error: (row.payload as { error?: string } | null)?.error ?? null,
|
||||
}
|
||||
: null;
|
||||
return { ...item, work: deriveFeedbackWork(item.status, snap) };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Prompt composition for feedback → agent dispatch.
|
||||
* SSOT so single-row Implement and batch "Implement all as one" stay aligned.
|
||||
*/
|
||||
import { fenceUntrusted, inlineUntrusted, UNTRUSTED_PREAMBLE } from "@/lib/feedback/untrusted";
|
||||
|
||||
export type FeedbackPromptFields = {
|
||||
suggestion: string;
|
||||
duplicateCount: number;
|
||||
url: string | null;
|
||||
page: string | null;
|
||||
scope: string | null;
|
||||
selectedElements: Array<{ elementType: string; elementText: string; selector: string }> | null;
|
||||
};
|
||||
|
||||
function renderElements(feedback: FeedbackPromptFields): string[] {
|
||||
if (!feedback.selectedElements?.length) return [];
|
||||
const lines = ["Element(s) the visitor pointed at:"];
|
||||
for (const el of feedback.selectedElements) {
|
||||
lines.push(
|
||||
`- <${inlineUntrusted(el.elementType, 100)}> ${inlineUntrusted(el.selector, 500)}${el.elementText ? ` — "${inlineUntrusted(el.elementText, 100)}"` : ""}`,
|
||||
);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** One visitor report → one scoped fix prompt. */
|
||||
export function composeFeedbackFixPrompt(
|
||||
feedback: FeedbackPromptFields,
|
||||
projectName: string,
|
||||
note?: string,
|
||||
): string {
|
||||
const times = feedback.duplicateCount > 1 ? ` (reported ${feedback.duplicateCount}×)` : "";
|
||||
const lines = [
|
||||
`Fix this visitor feedback on ${projectName}.${times}`,
|
||||
UNTRUSTED_PREAMBLE,
|
||||
"",
|
||||
...(note ? [`OPERATOR INSTRUCTION: ${note}`, ""] : []),
|
||||
fenceUntrusted("FEEDBACK", feedback.suggestion),
|
||||
`Page: ${inlineUntrusted(feedback.url ?? feedback.page ?? "unknown", 1000)}`,
|
||||
];
|
||||
if (feedback.scope) lines.push(`Scope the visitor selected: ${feedback.scope}`);
|
||||
lines.push(...renderElements(feedback));
|
||||
lines.push(
|
||||
"",
|
||||
"Scope: address exactly this feedback — no unrelated refactors.",
|
||||
"Verify the fix in the running app before claiming done, and record what you actually did (with evidence) in your final session handoff.",
|
||||
);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Many NEW reports → one agent run. Prefer this over N separate Dispatch clicks
|
||||
* when the captain wants a single coherent pass (shared root cause or a small
|
||||
* pile). Synthesize (theme briefs back into the inbox) is the alternative when
|
||||
* volume is high and you want another triage gate first.
|
||||
*/
|
||||
export function composeFeedbackBatchFixPrompt(
|
||||
items: FeedbackPromptFields[],
|
||||
projectName: string,
|
||||
note?: string,
|
||||
): string {
|
||||
const lines = [
|
||||
`Fix these ${items.length} visitor-feedback items on ${projectName} in one pass.`,
|
||||
UNTRUSTED_PREAMBLE,
|
||||
"",
|
||||
...(note ? [`OPERATOR INSTRUCTION: ${note}`, ""] : []),
|
||||
"Address every item below. Prefer one coherent change set when items share a root cause; otherwise fix them independently, most recent first.",
|
||||
"Scope: only these reports — no unrelated refactors.",
|
||||
"Verify each fix in the running app before claiming done, and record evidence in your handoff.",
|
||||
"",
|
||||
];
|
||||
items.forEach((f, i) => {
|
||||
const times = f.duplicateCount > 1 ? ` (reported ${f.duplicateCount}×)` : "";
|
||||
lines.push(`### ${i + 1}/${items.length}${times}`);
|
||||
lines.push(fenceUntrusted("FEEDBACK", f.suggestion));
|
||||
lines.push(`Page: ${inlineUntrusted(f.url ?? f.page ?? "unknown", 1000)}`);
|
||||
if (f.scope) lines.push(`Scope: ${f.scope}`);
|
||||
lines.push(...renderElements(f));
|
||||
lines.push("");
|
||||
});
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** Minimum NEW visitor items before Synthesize (theme briefs) is useful. */
|
||||
export const SYNTHESIZE_MIN_ITEMS = 3;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { getUserProjectByEntityId } from "@/db/queries/user-projects";
|
||||
import { fetchAttributesByEntityIds } from "@/db/queries/utils";
|
||||
|
||||
/**
|
||||
* Public site origin for a project. SSOT precedence matches getProjectLinks:
|
||||
* user_projects.liveUrl (Hetzner / Caddy) wins over legacy entity attrs.
|
||||
* Never prefer a stale *.vercel.app attr when liveUrl is set.
|
||||
*/
|
||||
export async function resolveProjectPublicOrigin(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
): Promise<string | null> {
|
||||
const [up, attrsMap] = await Promise.all([
|
||||
getUserProjectByEntityId(userId, projectId),
|
||||
fetchAttributesByEntityIds([projectId]),
|
||||
]);
|
||||
const attrs = attrsMap.get(projectId) ?? {};
|
||||
const raw = up?.liveUrl || attrs.production_url || attrs.url || null;
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return new URL(raw.startsWith("http") ? raw : `https://${raw}`).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Repo the agent can change: entity column or linked user_projects row. */
|
||||
export async function resolveProjectRepoTarget(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
): Promise<{ gitUrl: string | null; dirPath: string | null }> {
|
||||
const up = await getUserProjectByEntityId(userId, projectId);
|
||||
return {
|
||||
gitUrl: up?.gitUrl ?? null,
|
||||
dirPath: up?.dirPath ?? null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Honest work-phase for visitor feedback — what the captain sees after
|
||||
* Dispatch. DB status stays new|dispatched|resolved|archived; this layer
|
||||
* answers: not started / queued / working / stuck / failed / done.
|
||||
*
|
||||
* "dispatched" alone is not a user-facing word — it lied by sounding finished.
|
||||
*/
|
||||
import { FEEDBACK_STATUS, type FeedbackStatus } from "@/lib/constants/statuses";
|
||||
import { ORCH_STATE, type OrchestrationState } from "@/lib/orchestration/contract";
|
||||
import { ORCHESTRATION_OUTCOME } from "@/db/schema/orchestration-runs";
|
||||
|
||||
export const FEEDBACK_WORK_PHASE = {
|
||||
NOT_STARTED: "not_started",
|
||||
QUEUED: "queued",
|
||||
WORKING: "working",
|
||||
STUCK: "stuck",
|
||||
FAILED: "failed",
|
||||
DONE: "done",
|
||||
ARCHIVED: "archived",
|
||||
} as const;
|
||||
export type FeedbackWorkPhase = (typeof FEEDBACK_WORK_PHASE)[keyof typeof FEEDBACK_WORK_PHASE];
|
||||
|
||||
export type FeedbackWorkView = {
|
||||
phase: FeedbackWorkPhase;
|
||||
/** Short status word for the badge — never "dispatched". */
|
||||
label: string;
|
||||
/** One line of what to do / what happened. */
|
||||
detail: string | null;
|
||||
};
|
||||
|
||||
export type FeedbackRunSnapshot = {
|
||||
id: string;
|
||||
state: OrchestrationState;
|
||||
outcome: string | null;
|
||||
startedAt: Date;
|
||||
finishedAt: Date | null;
|
||||
deliveredAt: string | null;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
const STARTING_MS = 90_000;
|
||||
const THINKING_MS = 10 * 60_000;
|
||||
|
||||
export function deriveFeedbackWork(
|
||||
status: FeedbackStatus,
|
||||
run: FeedbackRunSnapshot | null,
|
||||
): FeedbackWorkView {
|
||||
if (status === FEEDBACK_STATUS.ARCHIVED) {
|
||||
return { phase: FEEDBACK_WORK_PHASE.ARCHIVED, label: "Archived", detail: null };
|
||||
}
|
||||
if (status === FEEDBACK_STATUS.RESOLVED) {
|
||||
return { phase: FEEDBACK_WORK_PHASE.DONE, label: "Done", detail: null };
|
||||
}
|
||||
if (status === FEEDBACK_STATUS.NEW) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.NOT_STARTED,
|
||||
label: "Not started",
|
||||
detail: "No agent has been asked to fix this yet.",
|
||||
};
|
||||
}
|
||||
|
||||
// status === dispatched
|
||||
if (!run) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.QUEUED,
|
||||
label: "Queued",
|
||||
detail: "Prompt accepted — no run record yet. Watch Control or Activity.",
|
||||
};
|
||||
}
|
||||
|
||||
if (run.state === ORCH_STATE.RUNNING) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.WORKING,
|
||||
label: "Working now",
|
||||
detail: "Agent is generating. Watch Terminal for live output. You get a notification when the run finishes.",
|
||||
};
|
||||
}
|
||||
|
||||
if (run.state === ORCH_STATE.ERROR || run.outcome === ORCHESTRATION_OUTCOME.TIMEOUT
|
||||
|| run.outcome === ORCHESTRATION_OUTCOME.ERROR || run.outcome === ORCHESTRATION_OUTCOME.HANG) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.FAILED,
|
||||
label: "Failed",
|
||||
detail: run.error?.slice(0, 160) || "The run ended without a successful fix. Retry or Watch Terminal.",
|
||||
};
|
||||
}
|
||||
|
||||
if (run.state === ORCH_STATE.DONE || run.state === ORCH_STATE.CLOSED || run.state === ORCH_STATE.CLOSING) {
|
||||
const ok = run.outcome === ORCHESTRATION_OUTCOME.SUCCESS || run.outcome === ORCHESTRATION_OUTCOME.PARTIAL;
|
||||
if (ok) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.DONE,
|
||||
label: "Done",
|
||||
detail: "Run finished — click Resolve if the fix looks right.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.FAILED,
|
||||
label: "Failed",
|
||||
detail: run.error?.slice(0, 160) || "Run finished without success. Retry or Watch Terminal.",
|
||||
};
|
||||
}
|
||||
|
||||
// waiting / idle — the ambiguous zone that previously read as success
|
||||
const ageMs = Date.now() - run.startedAt.getTime();
|
||||
if (!run.deliveredAt && ageMs > STARTING_MS) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.STUCK,
|
||||
label: "Not running",
|
||||
detail: "Queued, but the agent never started generating. Open Control — Retry if it stays.",
|
||||
};
|
||||
}
|
||||
if (!run.deliveredAt) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.QUEUED,
|
||||
label: "Queued",
|
||||
detail: "Starting — waiting for the agent to pick it up. You get a notification when the run finishes.",
|
||||
};
|
||||
}
|
||||
if (ageMs > THINKING_MS) {
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.STUCK,
|
||||
label: "Not running",
|
||||
detail: "Prompt was delivered, but there is no live progress. Open Control.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
phase: FEEDBACK_WORK_PHASE.WORKING,
|
||||
label: "Working now",
|
||||
detail: "Prompt delivered — agent may still be thinking. Watch Terminal. You get a notification when the run finishes.",
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
export const FLEET_PROJECT_STORAGE_KEY = "fleetcrown:active-project";
|
||||
export const FLEET_PROJECT_EVENT = "fleetcrown:project-context";
|
||||
|
||||
export type FleetSurfaceId = "profile" | "chat" | "control" | "terminal";
|
||||
export type FleetWorkspaceSurfaceId = "profile" | "chat" | "control" | "terminal";
|
||||
export type FleetSurfaceId = FleetWorkspaceSurfaceId | "activity";
|
||||
|
||||
export function fleetSurfaceHref(surface: FleetSurfaceId, project: string | null): string {
|
||||
const value = project?.trim();
|
||||
@@ -9,6 +10,7 @@ export function fleetSurfaceHref(surface: FleetSurfaceId, project: string | null
|
||||
if (surface === "profile") return "/projects";
|
||||
if (surface === "chat") return "/loki";
|
||||
if (surface === "control") return "/control";
|
||||
if (surface === "activity") return "/activity";
|
||||
return "/terminal";
|
||||
}
|
||||
|
||||
@@ -16,9 +18,24 @@ export function fleetSurfaceHref(surface: FleetSurfaceId, project: string | null
|
||||
if (surface === "profile") return `/projects?project=${encoded}`;
|
||||
if (surface === "chat") return `/loki?project=${encoded}`;
|
||||
if (surface === "control") return `/control?focus=${encoded}`;
|
||||
if (surface === "activity") return `/activity?project=${encoded}`;
|
||||
return `/terminal?source=server&tab=${encoded}`;
|
||||
}
|
||||
|
||||
/** Where to watch a queued inject: Control for state, Activity for the ledger,
|
||||
* Terminal only once a session is actually running. */
|
||||
export function injectWatchUrls(projectKey: string): {
|
||||
watchUrl: string;
|
||||
activityUrl: string;
|
||||
terminalUrl: string;
|
||||
} {
|
||||
return {
|
||||
watchUrl: fleetSurfaceHref("control", projectKey),
|
||||
activityUrl: fleetSurfaceHref("activity", projectKey),
|
||||
terminalUrl: fleetSurfaceHref("terminal", projectKey),
|
||||
};
|
||||
}
|
||||
|
||||
export function projectFromFleetRoute(pathname: string, search: URLSearchParams): string | null {
|
||||
const value = pathname === "/projects"
|
||||
? search.get("project")
|
||||
@@ -28,7 +45,9 @@ export function projectFromFleetRoute(pathname: string, search: URLSearchParams)
|
||||
? search.get("focus")
|
||||
: pathname.startsWith("/terminal")
|
||||
? search.get("tab")
|
||||
: null;
|
||||
: pathname.startsWith("/activity")
|
||||
? search.get("project")
|
||||
: null;
|
||||
return value?.trim() || null;
|
||||
}
|
||||
|
||||
|
||||
+99
-22
@@ -162,15 +162,56 @@ function downscaleImage(file: Blob): Promise<string | null> {
|
||||
const PENCIL_SVG =
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg>';
|
||||
|
||||
/** id-first CSS selector for a clicked element (ported from revampit's
|
||||
* element-selector.ts; hardened for SVG where className isn't a string). */
|
||||
/**
|
||||
* Prefer the thing the visitor meant (link/button/card) over decorative
|
||||
* children (img/svg/path/rect). Empty elementText on bare <img> / <rect> made
|
||||
* OrangeCat "make this clickable" reports useless for Dispatch fix.
|
||||
*/
|
||||
function resolvePickTarget(el: Element): Element {
|
||||
const interactive = el.closest(
|
||||
'a, button, [role="button"], [role="link"], summary, label, [tabindex]:not([tabindex="-1"])',
|
||||
);
|
||||
if (interactive instanceof Element) return interactive;
|
||||
|
||||
let cur: Element | null = el;
|
||||
while (cur && /^(path|rect|circle|line|polyline|polygon|g)$/i.test(cur.tagName)) {
|
||||
cur = cur.parentElement;
|
||||
}
|
||||
if (cur && cur.tagName.toLowerCase() === "svg") {
|
||||
const wrap = cur.parentElement;
|
||||
if (wrap && wrap !== document.body) return wrap;
|
||||
return cur;
|
||||
}
|
||||
if (el.tagName.toLowerCase() === "img") {
|
||||
const wrap = el.closest("a, button, figure, [role='button'], article, li");
|
||||
if (wrap instanceof Element) return wrap;
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
function elementLabel(el: Element): string {
|
||||
const aria = el.getAttribute("aria-label")?.trim();
|
||||
if (aria) return aria.slice(0, 100);
|
||||
const alt = el.getAttribute("alt")?.trim();
|
||||
if (alt) return alt.slice(0, 100);
|
||||
const title = el.getAttribute("title")?.trim();
|
||||
if (title) return title.slice(0, 100);
|
||||
const text = (el.textContent ?? "").replace(/\s+/g, " ").trim();
|
||||
if (text) return text.slice(0, 100);
|
||||
return `<${el.tagName.toLowerCase()}>`;
|
||||
}
|
||||
|
||||
/** id / data-testid first; else tag + up to 2 classes (skip fcw-*). */
|
||||
function generateSelector(el: Element): string {
|
||||
if (el.id) return `#${el.id}`;
|
||||
if (el.id) return `#${CSS.escape(el.id)}`;
|
||||
const testId = el.getAttribute("data-testid");
|
||||
if (testId) return `[data-testid="${CSS.escape(testId)}"]`;
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const cls = (el.getAttribute("class") ?? "")
|
||||
.split(/\s+/)
|
||||
.filter((c) => c && !c.startsWith("fcw-"));
|
||||
if (cls.length > 0) return `${el.tagName.toLowerCase()}.${cls.slice(0, 2).join(".")}`;
|
||||
return el.tagName.toLowerCase();
|
||||
if (cls.length > 0) return `${tag}.${cls.slice(0, 2).map((c) => CSS.escape(c)).join(".")}`;
|
||||
return tag;
|
||||
}
|
||||
|
||||
function h<K extends keyof HTMLElementTagNameMap>(
|
||||
@@ -417,25 +458,44 @@ function h<K extends keyof HTMLElementTagNameMap>(
|
||||
}
|
||||
}
|
||||
|
||||
// -- element picking: listeners are document-level + capture so the host
|
||||
// page can't swallow them; our own UI is skipped via composedPath.
|
||||
function isOwnUi(e: Event): boolean {
|
||||
return e.composedPath().includes(host);
|
||||
// Full-viewport shield: blocks host navigation/handlers during pick.
|
||||
// Target resolution uses elementsFromPoint so we still hit the real DOM
|
||||
// under the shield (capture-only listeners on the host page were not
|
||||
// enough — some Next Link clicks still navigated mid-pick).
|
||||
const pickShield = h("div");
|
||||
pickShield.id = "fcw-pick-shield";
|
||||
pickShield.setAttribute("aria-hidden", "true");
|
||||
Object.assign(pickShield.style, {
|
||||
position: "fixed",
|
||||
inset: "0",
|
||||
zIndex: "2147482999",
|
||||
cursor: "crosshair",
|
||||
background: "transparent",
|
||||
} as CSSStyleDeclaration);
|
||||
|
||||
function targetUnderPoint(x: number, y: number): Element | null {
|
||||
const stack = document.elementsFromPoint(x, y);
|
||||
for (const node of stack) {
|
||||
if (node === pickShield || node === host || host.contains(node)) continue;
|
||||
if (node instanceof Element) return resolvePickTarget(node);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function onPickMove(e: MouseEvent) {
|
||||
if (isOwnUi(e)) return;
|
||||
const target = e.target as Element;
|
||||
const target = targetUnderPoint(e.clientX, e.clientY);
|
||||
if (!target) return;
|
||||
if (hoverNode && hoverNode !== target) hoverNode.classList.remove("fcw-hover");
|
||||
hoverNode = target;
|
||||
target.classList.add("fcw-hover");
|
||||
}
|
||||
|
||||
function onPickClick(e: MouseEvent) {
|
||||
if (isOwnUi(e)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const target = e.target as Element;
|
||||
e.stopImmediatePropagation();
|
||||
const target = targetUnderPoint(e.clientX, e.clientY);
|
||||
if (!target) return;
|
||||
const selector = generateSelector(target);
|
||||
const idx = selected.findIndex((s) => s.selector === selector);
|
||||
if (idx > -1) {
|
||||
@@ -445,7 +505,7 @@ function h<K extends keyof HTMLElementTagNameMap>(
|
||||
} else if (selected.length < MAX_ELEMENTS) {
|
||||
selected.push({
|
||||
elementType: target.tagName.toLowerCase(),
|
||||
elementText: (target.textContent ?? "").trim().slice(0, 100),
|
||||
elementText: elementLabel(target),
|
||||
selector,
|
||||
});
|
||||
selectedNodes.push(target);
|
||||
@@ -455,9 +515,18 @@ function h<K extends keyof HTMLElementTagNameMap>(
|
||||
}
|
||||
|
||||
function syncPickbar() {
|
||||
pickMsg.textContent = selected.length
|
||||
? `${selected.length} selected — click more or Done`
|
||||
: "Click the element your feedback is about";
|
||||
if (selected.length === 0) {
|
||||
pickMsg.textContent = "Click the element your feedback is about";
|
||||
pickDone.disabled = true;
|
||||
return;
|
||||
}
|
||||
const last = selected[selected.length - 1];
|
||||
const label = last.elementText || last.selector;
|
||||
pickMsg.textContent =
|
||||
selected.length === 1
|
||||
? `Selected: ${label} — click more or Done`
|
||||
: `${selected.length} selected (last: ${label}) — Done when ready`;
|
||||
pickDone.disabled = false;
|
||||
}
|
||||
|
||||
function startPicking() {
|
||||
@@ -466,17 +535,25 @@ function h<K extends keyof HTMLElementTagNameMap>(
|
||||
document.head.appendChild(docStyle);
|
||||
backdrop.remove();
|
||||
panel.remove();
|
||||
root.appendChild(pickbar);
|
||||
// Shield lives in the shadow root under the pickbar so Done/Cancel stay
|
||||
// clickable; fixed positioning still covers the host page viewport.
|
||||
root.append(pickShield, pickbar);
|
||||
syncPickbar();
|
||||
document.addEventListener("mousemove", onPickMove, true);
|
||||
document.addEventListener("click", onPickClick, true);
|
||||
pickShield.addEventListener("mousemove", onPickMove, true);
|
||||
pickShield.addEventListener("click", onPickClick, true);
|
||||
// Also swallow pointerdown so Next <Link> / button handlers never fire.
|
||||
pickShield.addEventListener("pointerdown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}, true);
|
||||
}
|
||||
|
||||
function stopPicking() {
|
||||
if (!picking) return;
|
||||
picking = false;
|
||||
document.removeEventListener("mousemove", onPickMove, true);
|
||||
document.removeEventListener("click", onPickClick, true);
|
||||
pickShield.removeEventListener("mousemove", onPickMove, true);
|
||||
pickShield.removeEventListener("click", onPickClick, true);
|
||||
pickShield.remove();
|
||||
hoverNode?.classList.remove("fcw-hover");
|
||||
hoverNode = null;
|
||||
pickbar.remove();
|
||||
|
||||
Reference in new issue
Block a user