feat(share): add public share links via GitHub Gists (#995)

* 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>
This commit is contained in:
João Salavisa
2026-05-21 23:35:41 +01:00
committed by GitHub
parent 722cd31489
commit 0f1081d423
47 changed files with 6060 additions and 53 deletions
+8
View File
@@ -90,4 +90,12 @@ type Client interface {
// GetIssueState returns the state of a single issue ("open" or "closed").
GetIssueState(ctx context.Context, owner, repo string, number int) (string, error)
// CreateGist creates a new gist on the authenticated user's account.
// Set Public=false to create a secret (unlisted) gist.
CreateGist(ctx context.Context, in CreateGistInput) (*GistResponse, error)
// DeleteGist deletes a gist by ID. A 404 is wrapped in *GitHubAPIError
// so callers can distinguish "already gone" from transport failures.
DeleteGist(ctx context.Context, gistID string) error
}
@@ -99,6 +99,10 @@ func (s *stubClient) GetIssueState(context.Context, string, string, int) (string
func (s *stubClient) GetPRStatus(context.Context, string, string, int) (*PRStatus, error) {
return nil, nil
}
func (s *stubClient) CreateGist(context.Context, CreateGistInput) (*GistResponse, error) {
return nil, nil
}
func (s *stubClient) DeleteGist(context.Context, string) error { return nil }
func newControllerTestLogger() *logger.Logger {
log, _ := logger.NewLogger(logger.LoggingConfig{
+76
View File
@@ -692,6 +692,65 @@ func (c *GHClient) ListRepoBranches(ctx context.Context, owner, repo string) ([]
return branches, nil
}
func (c *GHClient) CreateGist(ctx context.Context, in CreateGistInput) (*GistResponse, error) {
payload := struct {
Description string `json:"description,omitempty"`
Public bool `json:"public"`
Files map[string]gistFileDTO `json:"files"`
}{
Description: in.Description,
Public: in.Public,
Files: make(map[string]gistFileDTO, len(in.Files)),
}
for name, f := range in.Files {
payload.Files[name] = gistFileDTO(f)
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("marshal gist payload: %w", err)
}
args := []string{"api", "gists",
"-X", "POST",
"-H", "Accept: " + githubAccept,
"--input", "-",
}
out, err := c.runWithStdin(ctx, body, args...)
if err != nil {
return nil, fmt.Errorf("create gist: %w", err)
}
var resp GistResponse
if err := json.Unmarshal([]byte(out), &resp); err != nil {
return nil, fmt.Errorf("decode gist response: %w", err)
}
return &resp, nil
}
func (c *GHClient) DeleteGist(ctx context.Context, gistID string) error {
if gistID == "" {
return fmt.Errorf("delete gist: empty id")
}
_, err := c.run(ctx, "api", "gists/"+gistID, "-X", "DELETE")
if err != nil {
// gh exits non-zero for HTTP errors; stderr contains the status
// line (e.g. "HTTP 404: Not Found"). Promote 404 to *GitHubAPIError
// so share.IsAlreadyGone matches consistently — PATClient.delete()
// already returns a typed error for the same case, and the share
// service uses errors.As to detect "gist already revoked upstream"
// and treat it as a soft success rather than a 502. Use isNotFoundErr
// so every gh-CLI 404 format ("HTTP 404", "404 Not Found", "status: 404")
// is recognised, not just the most common one.
if isNotFoundErr(err) {
return &GitHubAPIError{
StatusCode: http.StatusNotFound,
Endpoint: "/gists/" + gistID,
Body: err.Error(),
}
}
return fmt.Errorf("delete gist %s: %w", gistID, err)
}
return nil
}
const ghCLITimeout = 30 * time.Second
// withDefaultGHTimeout applies a 30s timeout if the context has no deadline.
@@ -719,6 +778,23 @@ func (c *GHClient) run(ctx context.Context, args ...string) (string, error) {
return stdout.String(), nil
}
// runWithStdin is like run but pipes stdin into the gh CLI process.
// Useful for `gh api --input -` calls where the body comes from JSON.
func (c *GHClient) runWithStdin(ctx context.Context, stdin []byte, args ...string) (string, error) {
ctx, cancel := withDefaultGHTimeout(ctx)
defer cancel()
cmd := exec.CommandContext(ctx, "gh", args...)
cmd.Stdin = bytes.NewReader(stdin)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
c.inspectRateStderr(args, stderr.String())
return stdout.String(), fmt.Errorf("gh %s: %w: %s", args[0], err, stderr.String())
}
return stdout.String(), nil
}
// ghRateLimitResponse mirrors the GET /rate_limit JSON shape so we can seed
// the tracker on startup and after CLI failures without parsing prose.
type ghRateLimitResponse struct {
+22
View File
@@ -0,0 +1,22 @@
package github
import "time"
// CreateGistInput is the payload for CreateGist.
type CreateGistInput struct {
Description string
Public bool
Files map[string]GistFile
}
// GistFile is a single file entry inside a gist.
type GistFile struct {
Content string
}
// GistResponse is the subset of the GitHub gist API response we care about.
type GistResponse struct {
ID string `json:"id"`
HTMLURL string `json:"html_url"`
CreatedAt time.Time `json:"created_at"`
}
@@ -74,6 +74,19 @@ type MockClient struct {
submittedReviews []submittedReview
mergedPRs []mergedPR
mergeMethods map[repoKey]RepoMergeMethods
gists map[string]mockGist
deletedGists []string
nextGistID int
}
// mockGist captures a gist that was created via the mock client so tests
// can inspect what would have been uploaded.
type mockGist struct {
ID string
Description string
Public bool
Files map[string]GistFile
HTMLURL string
}
// NewMockClient creates a new MockClient with default values.
@@ -91,6 +104,7 @@ func NewMockClient() *MockClient {
files: make(map[prKey][]PRFile),
commits: make(map[prKey][]PRCommitInfo),
mergeMethods: make(map[repoKey]RepoMergeMethods),
gists: make(map[string]mockGist),
}
}
@@ -311,6 +325,65 @@ func (m *MockClient) MergePR(_ context.Context, owner, repo string, number int,
return nil
}
func (m *MockClient) CreateGist(_ context.Context, in CreateGistInput) (*GistResponse, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.nextGistID++
id := fmt.Sprintf("mock-gist-%d", m.nextGistID)
htmlURL := "https://gist.github.com/" + m.user + "/" + id
files := make(map[string]GistFile, len(in.Files))
for k, v := range in.Files {
files[k] = v
}
m.gists[id] = mockGist{
ID: id,
Description: in.Description,
Public: in.Public,
Files: files,
HTMLURL: htmlURL,
}
return &GistResponse{
ID: id,
HTMLURL: htmlURL,
CreatedAt: time.Now().UTC(),
}, nil
}
func (m *MockClient) DeleteGist(_ context.Context, gistID string) error {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.gists[gistID]; !ok {
return &GitHubAPIError{
StatusCode: 404,
Endpoint: "/gists/" + gistID,
Body: "gist not found",
}
}
delete(m.gists, gistID)
m.deletedGists = append(m.deletedGists, gistID)
return nil
}
// Gists returns all currently-stored gists for test inspection.
func (m *MockClient) Gists() map[string]mockGist {
m.mu.RLock()
defer m.mu.RUnlock()
out := make(map[string]mockGist, len(m.gists))
for k, v := range m.gists {
out[k] = v
}
return out
}
// DeletedGists returns the IDs of gists that were deleted, in call order.
func (m *MockClient) DeletedGists() []string {
m.mu.RLock()
defer m.mu.RUnlock()
out := make([]string, len(m.deletedGists))
copy(out, m.deletedGists)
return out
}
// --- Setter methods for HTTP control endpoints ---
// SetUser sets the authenticated username.
@@ -451,6 +524,9 @@ func (m *MockClient) Reset() {
m.submittedReviews = nil
m.mergedPRs = nil
m.mergeMethods = make(map[repoKey]RepoMergeMethods)
m.gists = make(map[string]mockGist)
m.deletedGists = nil
m.nextGistID = 0
}
// SubmittedReviews returns all recorded SubmitReview calls.
@@ -2,6 +2,7 @@ package github
import (
"context"
"errors"
"testing"
"time"
)
@@ -193,6 +194,54 @@ func TestMockClient_SubmitReview(t *testing.T) {
}
}
func TestMockClient_CreateAndDeleteGist(t *testing.T) {
m := NewMockClient()
ctx := context.Background()
resp, err := m.CreateGist(ctx, CreateGistInput{
Description: "snapshot",
Public: false,
Files: map[string]GistFile{
"snapshot.json": {Content: `{"x":1}`},
"README.md": {Content: "hi"},
},
})
if err != nil {
t.Fatalf("CreateGist error: %v", err)
}
if resp.ID == "" || resp.HTMLURL == "" {
t.Fatalf("expected non-empty id/url, got %+v", resp)
}
gists := m.Gists()
g, ok := gists[resp.ID]
if !ok {
t.Fatalf("gist %s not stored", resp.ID)
}
if g.Public {
t.Fatal("gist should default to secret (Public=false)")
}
if _, ok := g.Files["snapshot.json"]; !ok {
t.Fatal("snapshot.json missing from stored gist")
}
if err := m.DeleteGist(ctx, resp.ID); err != nil {
t.Fatalf("DeleteGist error: %v", err)
}
if _, ok := m.Gists()[resp.ID]; ok {
t.Fatal("gist still present after delete")
}
if got := m.DeletedGists(); len(got) != 1 || got[0] != resp.ID {
t.Fatalf("expected DeletedGists=[%q], got %v", resp.ID, got)
}
err = m.DeleteGist(ctx, resp.ID)
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != 404 {
t.Fatalf("expected 404 GitHubAPIError on second delete, got %v", err)
}
}
func TestMockClient_Reset(t *testing.T) {
m := NewMockClient()
ctx := context.Background()
@@ -108,3 +108,11 @@ func (c *NoopClient) SearchPRsPaged(context.Context, string, string, int, int) (
func (c *NoopClient) GetIssueState(context.Context, string, string, int) (string, error) {
return "", ErrNoClient
}
func (c *NoopClient) CreateGist(context.Context, CreateGistInput) (*GistResponse, error) {
return nil, ErrNoClient
}
func (c *NoopClient) DeleteGist(context.Context, string) error {
return ErrNoClient
}
@@ -487,6 +487,42 @@ func (c *PATClient) MergePR(ctx context.Context, owner, repo string, number int,
return c.put(ctx, endpoint, jsonBody)
}
func (c *PATClient) CreateGist(ctx context.Context, in CreateGistInput) (*GistResponse, error) {
payload := struct {
Description string `json:"description,omitempty"`
Public bool `json:"public"`
Files map[string]gistFileDTO `json:"files"`
}{
Description: in.Description,
Public: in.Public,
Files: make(map[string]gistFileDTO, len(in.Files)),
}
for name, f := range in.Files {
payload.Files[name] = gistFileDTO(f)
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("marshal gist payload: %w", err)
}
var resp GistResponse
if err := c.postJSON(ctx, "/gists", body, &resp); err != nil {
return nil, fmt.Errorf("create gist: %w", err)
}
return &resp, nil
}
func (c *PATClient) DeleteGist(ctx context.Context, gistID string) error {
if gistID == "" {
return fmt.Errorf("delete gist: empty id")
}
return c.delete(ctx, "/gists/"+gistID)
}
// gistFileDTO mirrors the GitHub API's per-file body shape.
type gistFileDTO struct {
Content string `json:"content"`
}
// post makes an authenticated HTTP POST to the GitHub API.
// Errors on non-2xx are returned as plain `fmt.Errorf` (not `*GitHubAPIError`),
// so callers cannot recover the HTTP status via `errors.As`. Use `put` (or
@@ -516,6 +552,60 @@ func (c *PATClient) post(ctx context.Context, endpoint string, body []byte) erro
return nil
}
// postJSON sends a POST and decodes the response body into result.
// 2xx with no body returns nil; 4xx/5xx returns a *GitHubAPIError.
func (c *PATClient) postJSON(ctx context.Context, endpoint string, body []byte, result interface{}) error {
u := githubAPIBase + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
if err != nil {
return err
}
c.setGitHubHeaders(req)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request POST %s: %w", endpoint, err)
}
defer func() { _ = resp.Body.Close() }()
c.recordRateHeaders(resp, endpoint)
if resp.StatusCode >= 400 {
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
c.maybeMarkRateExhaustedFromBody(endpoint, resp.StatusCode, respBody)
return &GitHubAPIError{StatusCode: resp.StatusCode, Endpoint: endpoint, Body: string(respBody)}
}
if result == nil {
return nil
}
return json.NewDecoder(resp.Body).Decode(result)
}
// delete sends a DELETE request. 2xx and 404 both return nil-or-typed-error per caller intent.
// Here we return a typed error on any non-2xx so callers can inspect for 404.
func (c *PATClient) delete(ctx context.Context, endpoint string) error {
u := githubAPIBase + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, u, nil)
if err != nil {
return err
}
c.setGitHubHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request DELETE %s: %w", endpoint, err)
}
defer func() { _ = resp.Body.Close() }()
c.recordRateHeaders(resp, endpoint)
if resp.StatusCode >= 400 {
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
c.maybeMarkRateExhaustedFromBody(endpoint, resp.StatusCode, respBody)
return &GitHubAPIError{StatusCode: resp.StatusCode, Endpoint: endpoint, Body: string(respBody)}
}
return nil
}
func (c *PATClient) put(ctx context.Context, endpoint string, body []byte) error {
u := githubAPIBase + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodPut, u, bytes.NewReader(body))