mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 16:27:18 +02:00
## Thinking Path > - Paperclip is the open source control plane people use to organize, govern, and understand AI-agent work > - Operators need concise, current status views across projects and execution workspaces without manually reading every issue and run > - Paperclip already has auditable issues, documents, built-in agents, routines, and live run events, but no first-class summary-slot workflow connecting those systems > - A built-in Summarizer can generate status prose through ordinary governed tasks while summary slots provide stable, revisioned destinations for that output > - The UI needs to show current summaries, generation progress, failures, revisions, and streaming draft status in the places operators already work > - This pull request adds the end-to-end summary-slot data, API, agent, orchestration, and UI surfaces behind an experimental setting > - The benefit is decision-oriented status context that remains company-scoped, auditable, retryable, and inexpensive by default ## Linked Issues or Issue Description No public GitHub issue exists for this feature. **Problem** Operators currently have to reconstruct project and workspace status by reading many issues, runs, and comments. This makes it hard to identify decisions, review queues, recent work, and the next event worth watching. **Proposed capability** Add an experimental summary system with revisioned summary slots for projects and workspaces, a paused-by-default built-in Summarizer agent, governed generation tasks, live draft status, and reusable UI cards. **Expected behavior** - Summary data remains company-scoped and revisions remain auditable. - Generation runs through normal issue/agent orchestration and deduplicates active requests. - Only the linked built-in Summarizer generation task can author a slot revision. - Operators can generate, retry, inspect revisions, and follow draft progress from project and workspace views. - The feature remains opt-in and background generation remains paused by default. ## What Changed - Added summary-slot schema, idempotent migrations, shared contracts, validators, API paths, and service tests. - Added company-scoped summary-slot routes for reading revisions, requesting generation, and guarded Summarizer writes with activity logging. - Added terminal generation finalization, failure reasons, assignment wakeups, and orchestration integration. - Added the paused-by-default built-in Summarizer bundle, low-cost runtime defaults, status-summarization skill, and stale-summary routine. - Added summary cards, revision selection, retry/configuration states, live draft streaming, transcript chunk handling, and project/workspace integrations. - Updated Claude local parsing for streamed status output and expanded server, adapter, shared, database, catalog, and UI coverage. ## Verification - `pnpm -r typecheck` - `pnpm exec vitest run packages/db/src/summary-slots-schema.test.ts packages/shared/src/summary-slot.test.ts server/src/__tests__/summary-slot-routes.test.ts server/src/__tests__/summary-slots.test.ts server/src/__tests__/built-in-agents.test.ts ui/src/components/SummarySlotCard.test.tsx ui/src/components/SummarySlotCard.status.test.tsx ui/src/components/useSummaryDraftStream.test.tsx ui/src/lib/summary-draft-stream.test.ts ui/src/lib/run-log-chunks.test.ts ui/src/context/LiveUpdatesProvider.hook.test.tsx` — 113 tests passed - `pnpm test:run` — server and UI suites passed; one CLI AWS doctor test was affected by inherited `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, and passed when those host credentials were removed - `pnpm exec vitest run cli/src/__tests__/secrets.test.ts` with inherited AWS credential variables removed — 8 tests passed - `pnpm build` - `pnpm check:token-gates` currently reports nine `#9627` comment references introduced by current `master`; none are in this PR diff ## Risks - Database risk is limited by incrementally ordered, idempotent migrations and migration safety checks. - Summary generation creates normal issues/runs, so misconfiguration can produce failed slots; the UI exposes retryable failure reasons and agent configuration entry points. - Streaming draft parsing depends on the documented `STATUS:` protocol; final persisted revisions remain the source of truth. - The feature is experimental, opt-in, and its built-in routine is paused with no background token spend by default. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - OpenAI GPT-5.3 Codex with reasoning, repository tool use, code execution, GitHub CLI, and Paperclip control-plane integration. Earlier branch commits also record Claude model co-authorship where applicable. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
181 lines
6.6 KiB
TypeScript
181 lines
6.6 KiB
TypeScript
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { useQuery } from "@tanstack/react-query";
|
|
import type { LiveEvent, SummarySlotIssueRef } from "@paperclipai/shared";
|
|
|
|
import type { RunLogChunk } from "@/adapters";
|
|
import { heartbeatsApi } from "@/api/heartbeats";
|
|
import { useCompanyLiveEvent } from "@/context/LiveUpdatesProvider";
|
|
import { queryKeys } from "@/lib/queryKeys";
|
|
import {
|
|
mergeRunLogChunks,
|
|
parsePersistedLogContent,
|
|
readChunkSeq,
|
|
type ChunkMergeRefs,
|
|
type IncomingRunLogChunk,
|
|
} from "@/lib/run-log-chunks";
|
|
import {
|
|
closeDanglingCodeFence,
|
|
extractAssistantOutputText,
|
|
parseSummaryDraftStream,
|
|
} from "@/lib/summary-draft-stream";
|
|
|
|
const LOG_POLL_INTERVAL_MS = 1500;
|
|
const LOG_READ_LIMIT_BYTES = 256_000;
|
|
const MAX_CHUNKS = 400;
|
|
|
|
export interface SummaryDraftStream {
|
|
/** The generation run id, once learned from a live event or the fallback. */
|
|
runId: string | null;
|
|
/** Latest `STATUS:` line streamed by the Summarizer (prefix stripped). */
|
|
statusLine: string | null;
|
|
/** Accumulating draft Markdown (fence-guarded while still streaming). */
|
|
draft: string | null;
|
|
/** True once the closing draft sentinel has arrived. */
|
|
draftClosed: boolean;
|
|
/** Whether any protocol output (status line or draft) has streamed yet. */
|
|
hasStream: boolean;
|
|
}
|
|
|
|
function freshMergeRefs(): ChunkMergeRefs {
|
|
return { seenChunkKeys: new Set<string>(), trimmedSeqFloorByRun: new Map<string, number>() };
|
|
}
|
|
|
|
function readPayloadString(value: unknown): string | null {
|
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
}
|
|
|
|
/**
|
|
* Token-streamed draft for a generating summary slot.
|
|
*
|
|
* Learns the generation run's id from `heartbeat.run.progress` /
|
|
* `heartbeat.run.queued` events (matched by `issueId`), falling back to the
|
|
* issue's active-run endpoint after a page refresh. It then merges the run's
|
|
* assistant `acpx.text_delta` output from both the persisted run-log poller and
|
|
* the live company-events socket (reusing the shared chunk-merge/seq-dedupe
|
|
* util) and parses the STATUS lines + sentinel-wrapped draft out of that stream.
|
|
*
|
|
* Degrades gracefully: no run id / no deltas (WS down, non-ACP adapter, model
|
|
* skipped the protocol) simply yields an empty stream and the card keeps its
|
|
* spinner. State resets whenever the tracked generation changes.
|
|
*/
|
|
export function useSummaryDraftStream(
|
|
companyId: string | null | undefined,
|
|
generatingIssue: SummarySlotIssueRef | null,
|
|
): SummaryDraftStream {
|
|
const issueId = generatingIssue?.id ?? null;
|
|
const [runId, setRunId] = useState<string | null>(null);
|
|
const [chunks, setChunks] = useState<RunLogChunk[]>([]);
|
|
|
|
const mergeRefs = useRef<ChunkMergeRefs>(freshMergeRefs());
|
|
const pendingLogRowsRef = useRef(new Map<string, string>());
|
|
const logOffsetRef = useRef(0);
|
|
|
|
// Reset all stream state whenever the tracked generation changes — including
|
|
// a superseded generation (new issue id) or generation ending (null).
|
|
useEffect(() => {
|
|
setRunId(null);
|
|
setChunks([]);
|
|
mergeRefs.current = freshMergeRefs();
|
|
pendingLogRowsRef.current = new Map();
|
|
logOffsetRef.current = 0;
|
|
}, [issueId]);
|
|
|
|
const appendChunks = useCallback((incoming: IncomingRunLogChunk[]) => {
|
|
if (incoming.length === 0) return;
|
|
setChunks((prev) => {
|
|
const { chunks: merged, changed } = mergeRunLogChunks(
|
|
"summary-draft",
|
|
prev,
|
|
incoming,
|
|
mergeRefs.current,
|
|
MAX_CHUNKS,
|
|
);
|
|
return changed ? merged : prev;
|
|
});
|
|
}, []);
|
|
|
|
// Learn the generation run id from live progress/queued events for the issue.
|
|
useCompanyLiveEvent((event: LiveEvent) => {
|
|
if (!issueId) return;
|
|
if (event.type !== "heartbeat.run.progress" && event.type !== "heartbeat.run.queued") return;
|
|
const payload = event.payload ?? {};
|
|
if (payload.issueId !== issueId) return;
|
|
const nextRunId = readPayloadString(payload.runId);
|
|
if (nextRunId) setRunId((current) => (current === nextRunId ? current : nextRunId));
|
|
});
|
|
|
|
// Fallback: resolve the active run for the generation issue when no live event
|
|
// has surfaced the run id yet (e.g. a page refresh mid-generation).
|
|
const activeRunQuery = useQuery({
|
|
queryKey: queryKeys.issues.activeRun(issueId ?? "__none__"),
|
|
queryFn: () => heartbeatsApi.activeRunForIssue(issueId!),
|
|
enabled: Boolean(companyId) && Boolean(issueId) && !runId,
|
|
retry: false,
|
|
refetchInterval: runId ? false : 4000,
|
|
});
|
|
const fallbackRunId = activeRunQuery.data?.id ?? null;
|
|
useEffect(() => {
|
|
if (fallbackRunId) setRunId((current) => current ?? fallbackRunId);
|
|
}, [fallbackRunId]);
|
|
|
|
// Live token deltas over the shared company-events socket.
|
|
useCompanyLiveEvent((event: LiveEvent) => {
|
|
if (!runId) return;
|
|
if (event.type !== "heartbeat.run.log") return;
|
|
const payload = event.payload ?? {};
|
|
if (payload.runId !== runId) return;
|
|
const chunk = readPayloadString(payload.chunk);
|
|
if (!chunk) return;
|
|
const ts = readPayloadString(payload.ts) ?? event.createdAt;
|
|
const stream =
|
|
payload.stream === "stderr" ? "stderr" : payload.stream === "system" ? "system" : "stdout";
|
|
appendChunks([
|
|
{ ts, stream, chunk, seq: readChunkSeq(payload.seq), dedupeKey: `log:${runId}:${ts}:${stream}:${chunk}` },
|
|
]);
|
|
});
|
|
|
|
// Hydrate already-emitted output and fill any gaps from the persisted run log.
|
|
useEffect(() => {
|
|
if (!runId) return;
|
|
logOffsetRef.current = 0;
|
|
pendingLogRowsRef.current = new Map();
|
|
|
|
let cancelled = false;
|
|
const read = async () => {
|
|
try {
|
|
const result = await heartbeatsApi.log(runId, logOffsetRef.current, LOG_READ_LIMIT_BYTES);
|
|
if (cancelled) return;
|
|
appendChunks(parsePersistedLogContent(runId, result.content, pendingLogRowsRef.current));
|
|
if (result.nextOffset !== undefined) {
|
|
logOffsetRef.current = result.nextOffset;
|
|
} else if (result.content.length > 0) {
|
|
logOffsetRef.current += result.content.length;
|
|
}
|
|
} catch {
|
|
// Ignore transient/404 reads (log not yet flushed, run just started).
|
|
}
|
|
};
|
|
|
|
void read();
|
|
const interval = window.setInterval(() => void read(), LOG_POLL_INTERVAL_MS);
|
|
return () => {
|
|
cancelled = true;
|
|
window.clearInterval(interval);
|
|
};
|
|
}, [runId, appendChunks]);
|
|
|
|
const parse = useMemo(() => parseSummaryDraftStream(extractAssistantOutputText(chunks)), [chunks]);
|
|
|
|
const draft = parse.draft !== null && !parse.draftClosed
|
|
? closeDanglingCodeFence(parse.draft)
|
|
: parse.draft;
|
|
|
|
return {
|
|
runId,
|
|
statusLine: parse.statusLine,
|
|
draft,
|
|
draftClosed: parse.draftClosed,
|
|
hasStream: parse.draft !== null || parse.statusLine !== null,
|
|
};
|
|
}
|