0f1081d423
* feat(share): add public share links via GitHub Gists Adds a Share button to the chat panel header that publishes the current session as a secret GitHub Gist on the user's account. The share link routes through gistpreview.github.io to render share.html as a styled kandev-themed page; snapshot.json + README.md ride along for machine-readable + fallback views. Snapshots run a redaction pass (absolute paths, common credential shapes, .env contents, shell env vars) and strip <kandev-system> prompt blocks via the shared sysprompt helper. Message filtering whitelists user prose + tool_* types so internal noise never leaks into shares. Spec at docs/specs/public-share-links/spec.md. * fix(share): coerce pendingClarification to bool for ClarificationSection A late refactor extracted ClarificationSection with `pendingClarification: boolean` on its props, but the call site passes the actual Message|null value. CI's tsc build catches the mismatch; runtime was unaffected because the section only uses the value in a truthiness check. Coerce with Boolean() at the call site to keep the prop's intent narrow. * fix(share): address PR #995 review feedback Bugs (flagged by Greptile, Cubic, Claude): - abs-path redaction split on `root + "/"` so sibling dirs like /home/user/proj2 don't get corrupted when workspaceRoot is /home/user/proj; regression test added. - GHClient.DeleteGist now wraps "HTTP 404" stderr as *GitHubAPIError so share.IsAlreadyGone matches consistently with the PAT client; this restores the "gist already revoked upstream" soft-success path for CLI-authenticated users. - SnapshotSizeBytes is now measured from the same MarshalIndent payload the gist backend uploads, so the size shown in the UI matches the actual gist bytes (was ~20-40% underreported). Polish (flagged by CodeRabbit, Cubic): - Tool name + tool output now HTML-escaped; tool call args and output render via <pre><code> instead of triple-backtick fences so payloads containing ``` can't break out of the code block. - share-list.tsx: clear `busy` via finally and break error layout out of the justify-between row. - use-shares.ts: convert UseSharesResult to interface (repo TS rules); reset error+isLoading when ids are missing. - use-shares.test.tsx: wait on the actual async outcome (shares populated, listShares called) instead of isLoading flipping false. - provider.go: replace `repo.Close` cleanup with an explicit noop closure so the comment ("Cleanup is a no-op") and the impl match. - spec.md: aligned the shareability rule across What/Failure/Scenarios/ Out-of-scope — any non-prehistory state can be shared; added language tags to fenced code blocks for markdownlint. Skipped intentionally (reply on each thread): - HTML-escape every metadata badge: the values are controlled enum strings from kandev's own schema, not user input. Defense-in-depth noise. Tool name (which can come from agent runtime) IS escaped. - useShares request-token guard against stale responses: the dialog owns the hook lifecycle and opens against a single (taskId, sessionId) — the race the comment describes can't occur here. * fix(share): redact paths for every worktree, not just the first A single TaskSession can carry multiple worktrees when the task spans multiple repos. The redactor previously only saw the first worktree path, so absolute paths from secondary worktrees leaked into public shares instead of being rewritten to repo-relative form. NewRedactor is now variadic and applies the abs-path rule against every root it receives, sorted longest-first so a root that is a prefix of another (e.g. /workspace vs /workspace/repo1) gets matched by the more specific one first. workspaceRootFor in builder.go becomes workspaceRootsFor and emits every WorktreePath plus the WorkspacePath fallback. Flagged by Cubic on PR #995. * fix(share): address PR #995 review round 3 Bugs (flagged by Cubic + Claude on gh_client.go:714): - DeleteGist now calls the existing isNotFoundErr helper instead of an inline strings.Contains(err, "HTTP 404"). The helper also covers "404 Not Found" and "status: 404", which some gh versions emit, so the share service's "gist already revoked upstream" soft-success path now fires consistently across CLI auth users. Bugs (flagged by Claude on builder.go:220): - toolCallBlock used to read metadata["tool_name"] and metadata["args"] but production never writes those keys; the typed payload lives under metadata["normalized"] (a *streams.NormalizedPayload) and the tool kind is on Message.Type. Switched to deriving ToolName from strings.TrimPrefix(m.Type, "tool_") (gives "read", "execute", "edit", …) and reading args from metadata["normalized"], with backward-compat fallback to the older "tool_name"/"args" keys for the debug-fixture replay path. New TestBuildSnapshot_ToolCall_ProductionMetadataShape exercises the real session shape. Bugs (flagged by CodeRabbit on redaction.go:110): - Bare workspace-root occurrences (pwd output, end-of-sentence, quoted paths) used to leak because the matcher only handled root + "/". Switched to a precompiled regex per root — regexp.QuoteMeta(root) + `(?:/|\b)` — so both `root/...` and standalone `root` get stripped, while sibling dirs like /workspace2 still don't match. Test TestRedactor_AbsPath_StandaloneRootStripped covers the bare-root variants. Doc (flagged by Claude on spec.md): - Two malformed fence closers (`go and `text on closing fences) corrected to plain ``` so the file is markdownlint-clean. * fix(share): narrow abs-path boundary to avoid sibling-prefix corruption Round 4 review (Claude + CodeRabbit) caught a regression in the regex introduced by 436cb66: `(?:/|\b)` used `\b` (word boundary) to catch bare-root cases, but `\b` fires on any word↔non-word transition. So a sibling path like `/workspace.bak`, `/workspace-old`, or `/workspace-other` would false-match the `/workspace` root (since e→. and e→- are word boundaries), stripping it and leaving a corrupted `.bak` / `-old/file.ts` in the share. Replaced the matcher with `(/|\s|$)`: path separator, whitespace, or end-of-string only — never punctuation or quote chars. The boundary is captured and re-emitted via ReplaceAllStringFunc (or dropped, in the `/` case) so prose loses only the root, not the surrounding space. Added TestRedactor_AbsPath_SiblingsWithPunctuationNotCorrupted covering `.bak`, `-old`, `_alt` siblings; the digit-sibling test still passes. The quoted-bare-root case (`"/workspace"`) no longer matches and was dropped from the standalone-root test — contrived enough that a small leak there is preferable to corrupting realistic sibling paths. * refactor(share): move share button into chat status bar Replaces the dedicated PanelHeaderBarSplit above the message list with a slot in ChatStatusBar (the existing row holding TodoIndicator and PRStatusChip just above the chat input). The button anchors right via ml-auto; when the "proceed to next step" affordance is present it takes the right anchor instead and the share button stays inline. Also tightens the iconOnly variant in ShareButton to a ghost style that matches the muted-foreground chips in the status bar, and exports shareableSessionStateClient from share-button.tsx so the gating logic lives next to the entry point it controls. Net -23 lines in task-chat-panel.tsx: the extra header bar and the local gate helper are gone. * docs(share): broaden tooltip + add share/ to CLAUDE.md tree The share tooltip read "Share this completed task with a public link", but shareableSessionStateClient allows RUNNING / IDLE / WAITING_FOR_INPUT / FAILED / CANCELLED too. A user hovering mid-run saw misleading copy; reworded to "Share this task conversation as a public link" which matches the actual gate. Also added the missing internal/task/share/ entry to the task/ subtree in CLAUDE.md so the new package shows up in the repo map — flagged across multiple rounds. * docs: add internal/task/share/ to repo map Carryover from the share PR — AGENTS.md (which CLAUDE.md symlinks to) was missing the share/ subpackage under task/. Adding it now so the repo map matches what's checked in. --------- Co-authored-by: Kandev Agent <agent@kandev.dev>
138 lines
4.8 KiB
TypeScript
138 lines
4.8 KiB
TypeScript
"use client";
|
|
|
|
import { Badge } from "@kandev/ui/badge";
|
|
import { ScrollArea } from "@kandev/ui/scroll-area";
|
|
|
|
import type { SnapshotPreview, SnapshotPreviewMessage } from "@/lib/api/domains/share-api";
|
|
|
|
type Props = {
|
|
snapshot: SnapshotPreview;
|
|
};
|
|
|
|
// Long conversations would blow up the dialog. Cap what we render in the
|
|
// preview to the first + last few messages; the published gist still has
|
|
// the complete snapshot.
|
|
const PREVIEW_HEAD = 8;
|
|
const PREVIEW_TAIL = 8;
|
|
|
|
/**
|
|
* Renders the redacted snapshot as a read-only preview. Intentionally not
|
|
* reusing NativeMessageList: the snapshot does not have the live Zustand
|
|
* shape the rich renderer expects, and a stripped-down view makes "this is
|
|
* exactly what will be published" easy to verify at a glance.
|
|
*/
|
|
export function ShareSnapshotPreview({ snapshot }: Props) {
|
|
const slices = previewSlices(snapshot.messages);
|
|
return (
|
|
<div className="flex min-w-0 flex-col gap-2">
|
|
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
|
{snapshot.session.agent_type && (
|
|
<Badge variant="outline">{snapshot.session.agent_type}</Badge>
|
|
)}
|
|
{snapshot.session.model && <Badge variant="outline">{snapshot.session.model}</Badge>}
|
|
{snapshot.session.executor_type && (
|
|
<Badge variant="outline">{snapshot.session.executor_type}</Badge>
|
|
)}
|
|
<span>{snapshot.messages.length} messages</span>
|
|
{snapshot.redaction.applied_rules.length > 0 && (
|
|
<span>Redacted: {snapshot.redaction.applied_rules.join(", ")}</span>
|
|
)}
|
|
</div>
|
|
<ScrollArea className="h-72 rounded border bg-muted/30">
|
|
<div className="flex flex-col gap-3 p-3">
|
|
{snapshot.messages.length === 0 && (
|
|
<p className="text-sm text-muted-foreground italic">
|
|
This conversation has no shareable content.
|
|
</p>
|
|
)}
|
|
{slices.head.map((msg, idx) => (
|
|
<PreviewMessage key={`h-${idx}`} message={msg} />
|
|
))}
|
|
{slices.hiddenCount > 0 && (
|
|
<p className="text-center text-xs text-muted-foreground italic py-1">
|
|
… {slices.hiddenCount} more message{slices.hiddenCount === 1 ? "" : "s"} hidden in
|
|
this preview (still included in the share) …
|
|
</p>
|
|
)}
|
|
{slices.tail.map((msg, idx) => (
|
|
<PreviewMessage key={`t-${idx}`} message={msg} />
|
|
))}
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// previewSlices splits the messages into a head + tail with a hidden count
|
|
// in between when the conversation exceeds the per-section caps. Short
|
|
// conversations come back as the full head with empty tail / zero hidden.
|
|
function previewSlices(messages: SnapshotPreviewMessage[]): {
|
|
head: SnapshotPreviewMessage[];
|
|
tail: SnapshotPreviewMessage[];
|
|
hiddenCount: number;
|
|
} {
|
|
if (messages.length <= PREVIEW_HEAD + PREVIEW_TAIL) {
|
|
return { head: messages, tail: [], hiddenCount: 0 };
|
|
}
|
|
return {
|
|
head: messages.slice(0, PREVIEW_HEAD),
|
|
tail: messages.slice(messages.length - PREVIEW_TAIL),
|
|
hiddenCount: messages.length - PREVIEW_HEAD - PREVIEW_TAIL,
|
|
};
|
|
}
|
|
|
|
function PreviewMessage({ message }: { message: SnapshotPreviewMessage }) {
|
|
return (
|
|
<div className="flex min-w-0 flex-col gap-1 rounded border border-border/60 bg-background p-2">
|
|
<div className="text-[10px] uppercase tracking-wide text-muted-foreground">
|
|
{message.role}
|
|
</div>
|
|
<div className="flex min-w-0 flex-col gap-1">
|
|
{message.blocks.map((block, i) => (
|
|
<PreviewBlock key={i} block={block} />
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function PreviewBlock({ block }: { block: SnapshotPreviewMessage["blocks"][number] }) {
|
|
if (block.kind === "text") {
|
|
return <p className="whitespace-pre-wrap break-words text-sm">{block.text}</p>;
|
|
}
|
|
if (block.kind === "tool_call") {
|
|
return (
|
|
<div className="min-w-0 rounded bg-muted/60 p-1.5 text-xs">
|
|
<div className="truncate font-mono" title={block.tool_name || "tool"}>
|
|
{block.tool_name || "tool"}
|
|
</div>
|
|
{block.text && (
|
|
<p className="truncate text-muted-foreground" title={block.text}>
|
|
{block.text}
|
|
</p>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
if (block.kind === "tool_result") {
|
|
return (
|
|
<pre className="max-w-full overflow-x-auto rounded bg-muted/60 p-1.5 text-xs">
|
|
<code>{block.output}</code>
|
|
</pre>
|
|
);
|
|
}
|
|
if (block.kind === "diff") {
|
|
return (
|
|
<div className="min-w-0 rounded bg-muted/60 p-1.5 text-xs">
|
|
<div className="truncate font-mono" title={block.path}>
|
|
{block.path}
|
|
</div>
|
|
<pre className="max-w-full overflow-x-auto whitespace-pre">
|
|
<code>{block.unified_diff}</code>
|
|
</pre>
|
|
</div>
|
|
);
|
|
}
|
|
return null;
|
|
}
|