web: shared chat stars, pipeline mini graphs and agent questions

- Persist chat stars in the operator-session registry (chat_star) so every
  browser/device shows the same Starred group; migrate old local stars once.
- Add a compact pipeline graph shape to list responses and draw a lightweight
  list miniature; replace the cryptic id/version line with the stage count.
- Surface OpenCode form questions as a chat card (chat_answer), replay a
  pending form to late subscribers, and notify for background questions.
- Make the mobile dock's Search cell equal to every destination, keep the
  tab row visible with 100svh, and let Source use the full pane height.
- Let a fresh sign-in auto-connect to its own origin; use a Lax session cookie
  with Expires so Remember me survives app/link launches.
- Keep shipped starters and the skill agnostic: no repository paths, project
  areas or personal device commands; add Diagnose/Fix and Research starters.
- Refresh the installed skill and document the new browser conventions.
This commit is contained in:
2026-10-20 03:11:37 +01:00
parent caae8a8038
commit 526c19fc21
46 changed files with 1547 additions and 611 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"path/filepath"
)
var skillFiles = []string{"SKILL.md", "references/orchestration.md", "references/work.md", "references/queue.md", "references/debugging.md", "references/delivery.md", "references/format.md", "references/notifications.md", "references/operations.md", "references/transfer.md", "references/verification.md", "references/control.md", "references/harnesses.md"}
var skillFiles = []string{"SKILL.md", "references/orchestration.md", "references/work.md", "references/queue.md", "references/debugging.md", "references/delivery.md", "references/format.md", "references/notifications.md", "references/operations.md", "references/transfer.md", "references/verification.md", "references/control.md", "references/harnesses.md", "references/access.md"}
func SkillDirectory() (string, error) {
dir := os.Getenv("XDG_CONFIG_HOME")
+46 -33
View File
@@ -5,51 +5,64 @@ description: Use and author Pipelines workflows, inspect runs, and recover or de
# Pipelines
Pipelines are optional execution tools. The manager may also implement, test,
review, resolve conflicts, merge and deliver directly. Do not turn a failed
workflow into repeated whole-run retries or another pipeline's landing job.
Pipelines are reusable workflows for repositories. They are optional: direct
work, delegation and a pipeline are all valid routes. Use whichever finishes the
task with the least ceremony, and keep work small enough to verify.
## Work
## Using it
Read the task and relevant project map before asking questions. Split changes
into small verifiable items, each with one goal and short acceptance checks.
Run independent items concurrently; use separate worktrees and the agreed model.
Preserve partial work and inspect real diffs and command results. A failed item
does not freeze unrelated work. Continue at the necessary stage or recover directly.
`pipelines list` shows the registered workflows; `pipelines runs` shows history.
Start a run with `pipelines run <name> "<task>"`, and inspect it with
`pipelines inspect <id>`. `pipelines wait <id>` blocks until it finishes.
## Definitions
A failed run keeps its worktree and commits. Read `pipelines inspect <id> --json`
before deciding: resume the failed stage (`pipelines retry <id>`), fix directly,
or continue from the preserved branch.
Edit a retained draft, not immutable history. Give each stage one simple job and
only the input it needs. Preserve review gates, runtime limits, permissions and
the user's constraints unless asked to change them.
Use `pipelines validate DRAFT --json` before publication. Publish or execute when
the user requests it; do not ask again for routine steps already authorized.
Keep version guards. `--yes` is not a conflict policy; never silently force an
update over somebody else's version. A draft-only request does not authorize a run.
## Authoring
For delivery-enabled stages, the committer prepares a clean checked candidate and
returns success; the server lands afterward. Check ancestry after landing, not as
a precondition that prevents the gate running. Direct recovery may merge reviewed
work itself, while preserving unrelated changes and checking the result.
A definition is Markdown: `# stage <Name>` sections with `prompt`, `configs`,
`tools`, `edges`, and optional `limits`/`checks`/`settings`. Start from
`examples/`. Use stage names that describe the work:
`Plan` · `Code` · `Review` · `UIReview` · `Land` (`Prepare` and `Survey` are
useful variants).
Keep prompts short and objective: what the stage should produce and any real
constraints. The runner enforces turns, tools and limits; prompts do not need to
repeat them. Only `# outcome` is parsed from `output.md`; everything else is
free markdown. Use `links` and `memory` only when they clarify a handoff.
`pipelines validate DRAFT` checks a draft; `pipelines submit DRAFT` publishes a
new immutable version. `pipelines help <command>` has flags.
## Turns and artifacts
Each visit has `input.md` (the run prompt or previous body), `memory.md`
(completed turns), `output.md`, and `private/`. Every run also has one shared
`public/` directory, addressed by its absolute path; files there are visible to
later stages and are the stage's real artifacts. `input.md`, `memory.md`,
`output.md` and `session.html` are system evidence for auditing, not stage
output.
## References
Do not preload references. Read only the reference needed for the current task:
Read only what the task needs:
| Need | Reference |
| --- | --- |
| Small tasks and stage roles | `references/orchestration.md` |
| Queue and parallel work | `references/work.md`, `references/queue.md` |
| Failures and recovery | `references/debugging.md` |
| Definition syntax and turn files | `references/format.md` |
| Limits, tools and permissions | `references/control.md` |
| Stages, parallel work, recovery | `references/orchestration.md` |
| CLI, storage and evidence | `references/operations.md` |
| Verification and accounting | `references/verification.md` |
| Failures | `references/debugging.md` |
| Delivery and installation | `references/delivery.md` |
| Definition syntax and handoffs | `references/format.md`, `references/control.md` |
| Harnesses and models | `references/harnesses.md` |
| Notifications | `references/notifications.md` |
| CLI, storage and retained evidence | `references/operations.md` |
| Transfer and version conflicts | `references/transfer.md` |
| Verification and accounting | `references/verification.md` |
| Transfer and versions | `references/transfer.md` |
| Hosting, auth and deployment | `references/access.md` |
| Queue and work items | `references/work.md`, `references/queue.md` |
Use command-specific `pipelines help COMMAND` rather than guessing flags.
Distinguish validation, executed tests, landed source and deployed behavior.
Preserve history, branches and user data. Do not disrupt active services or device
users. Ask before destructive or out-of-scope actions, not ordinary implementation.
Ask about real ambiguity, destructive actions or changes outside the request;
routine steps of an authorized task do not need another confirmation.
@@ -0,0 +1,55 @@
# Hosting, access and deployment
The browser client is `web/serve.mjs`: static files plus a `/connect` WebSocket
proxy and `/artifacts/` proxy to the Pipelines server. Plain `node serve.mjs` is
enough for local work.
## Password gate
`serve.mjs` refuses pages, assets, artifacts and `/connect` without a signed
session cookie. The password and signing secret live outside the repository:
`~/.config/pipelines/web-auth.json` (mode `600`), e.g.
```json
{ "password": "…", "secret": "…" }
```
The sign-in page is `/login`; **Remember me** keeps a 30-day cookie, otherwise
the cookie lives until the browser closes. Wrong passwords are throttled. Tests
that start their own `serve.mjs` set `PIPELINES_WEB_AUTH=disabled`; never put that
in a service.
Changing the password: edit the file, then restart the web service.
## Bind and exposure
For an untrusted network, keep the raw ports local:
- Pipelines server: `-addr 127.0.0.1:8080`.
- Web proxy: `--host 127.0.0.1` (reachable through Tailscale, not the LAN).
- OpenCode: `server.hostname = "127.0.0.1"` in `~/.config/opencode/opencode.json`.
Tailscale can terminate HTTPS for a tailnet-only name:
```sh
tailscale serve --bg --https=8443 http://127.0.0.1:8095
# https://<machine>.<tailnet>.ts.net:8443/
```
That gives a valid certificate and a secure context (service worker, installable
web app). Only tailnet devices can resolve the name; the password still applies
to the app and its WebSocket.
Keep the server and web proxy supervised by the platform's service manager so
they restart after a reboot. Name the service files for your installation; their
labels are local choices, not part of the protocol. The HTTPS proxy rule must
also survive a reboot.
## Before exposing anything
Check what listens beyond loopback (`lsof -nP -iTCP -sTCP:LISTEN`). The Pipelines
server and the agent harness are control APIs without their own login; bind them
to localhost and expose only the authenticated web proxy. If an app-managed
server cannot bind loopback, a host firewall or tailnet ACLs are the remaining
options. Unrelated operating-system services are outside this deployment.
@@ -13,23 +13,27 @@ at integration. Serialize only actual dependency or resource conflicts.
## Stage jobs
- Planner: produce a short plan and acceptance checks only when needed.
- Implementer: make the focused change, add tests, run focused checks.
- Reviewer: inspect the whole task diff and independently verify relevant checks.
- UI reviewer: exercise rendered behavior using ready controlled data; retain captures.
- Committer: commit all reviewed task changes, integrate main and resolve conflicts.
- Plan: a short approach and acceptance checks when they help.
- Code: the focused change, tests and focused checks.
- Review: the whole task diff and independent verification.
- UIReview: rendered behavior with controlled data and captures.
- Land: commit the reviewed work, integrate main and resolve conflicts.
Handoff desired behavior and necessary evidence, not another role's restrictions.
An implementer's "no device use performed" is not a ban on the UI reviewer.
A fresh clean worktree is a successful no-op for preparation, not a failure.
Nonvisual changes need no device. A visual change needs actual visual evidence.
Names are a convention, not a requirement; a pipeline can use any clear stage
names. Keep each stage's job narrow enough to judge its output.
Hand off the desired behavior and the evidence that should exist at the end, not
another stage's restrictions. A clean worktree is a successful no-op for
preparation, not a failure. Nonvisual work needs no rendered evidence; a visual
change does.
## Pipeline choice
When using the project's area workflows: Android for android/, TUI for internal/tui/,
Server for backend/protocol work, Generic for genuinely cross-area work, Plan and
land when design is necessary, UI sweep for a visual survey, Probe for a smoke check.
Read area maps for project-specific commands. Keep models and costs as agreed.
Prefer the smallest workflow that makes the work verifiable: plan when the design
is genuinely uncertain, review when a change is risky or broad, and a visual survey
when appearance is the question. Stage names describe jobs, not fixed roles. Read
the project's own maps and commands instead of assuming an area layout. Keep models
and costs as agreed.
## Recovery and landing
+1 -1
View File
@@ -43,7 +43,7 @@ func TestEveryEmbeddedReferenceIsInstalledAndLinksResolve(t *testing.T) {
if len(main) > 8000 {
t.Fatal("keep detailed knowledge out of the main skill", len(main))
}
for _, required := range []string{"operations.md", "transfer.md", "verification.md", "Do not preload", "before asking", "--yes` is not a conflict policy"} {
for _, required := range []string{"operations.md", "transfer.md", "verification.md", "access.md", "Only `# outcome`", "Ask about real ambiguity"} {
if !strings.Contains(string(main), required) {
t.Fatal("missing routing or safety rule", required)
}
+139
View File
@@ -108,6 +108,26 @@ func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID stri
return nil
}
// Answer replies to one OpenCode form. The agent's question tool pauses inside a
// form.created event; replying lets the same turn continue. The answer object is
// keyed by the form field keys, exactly as the OpenCode CLI sends it.
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
if !sessionID.MatchString(request.SessionID) {
return fmt.Errorf("invalid OpenCode session id")
}
if strings.TrimSpace(request.FormID) == "" {
return fmt.Errorf("a form id is required")
}
body := map[string]any{"answer": request.Answers}
if request.Answers == nil {
body["answer"] = map[string]any{}
}
if _, err := c.call(ctx, "post", "/api/session/"+request.SessionID+"/form/"+request.FormID+"/reply", body); err != nil {
return err
}
return nil
}
// Interrupt aborts the session's active run, reusing the same translated surface.
func (c *Chat) Interrupt(ctx context.Context, id string) error {
if !sessionID.MatchString(id) {
@@ -635,12 +655,40 @@ func isChatEventType(t string) bool {
"session.tool.input.started", "session.tool.input.ended",
"session.tool.called", "session.tool.progress",
"session.tool.success", "session.tool.failed",
"form.created", "form.replied", "form.cancelled",
"shell.created", "shell.exited":
return true
}
return false
}
// chatFormPayload is the form object nested under form.created. The question
// tool uses metadata.kind == "question"; other forms are surfaced with their own
// kind so the client can decide whether to render them as a question.
type chatFormPayload struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Title string `json:"title"`
Metadata map[string]any `json:"metadata"`
Fields []chatFormField `json:"fields"`
}
type chatFormField struct {
Key string `json:"key"`
Title string `json:"title"`
Description string `json:"description"`
Type string `json:"type"`
Options []chatFormOption `json:"options"`
Custom bool `json:"custom"`
Required bool `json:"required"`
}
type chatFormOption struct {
Value string `json:"value"`
Label string `json:"label"`
Description string `json:"description"`
}
// chatEvent is the subset of the verified firehose envelope this adapter reads:
// {"type":"session.text.delta","data":{...}}. Fields absent from a given event
// stay zero so one struct covers every type.
@@ -672,6 +720,9 @@ type chatEvent struct {
Status string `json:"status"`
Exit *int `json:"exit"`
Info *chatShellInfo `json:"info"`
// Form is the nested form.created payload; FormID is the bare id on
// form.replied/form.cancelled.
Form *chatFormPayload `json:"form"`
}
// chatShellInfo is the Shell.Info envelope a shell.created event nests under
@@ -711,10 +762,13 @@ func (i *chatShellInfo) shellSessionID() string {
// seen exit. shell.exited carries no session id, so the id remembered here is
// what attributes the exit to its session: another session's shell is an
// unknown id and is ignored.
// - Forms maps a pending form id to its session, so form.replied/cancelled
// (which carry no session) can be attributed to the right chat.
type ChatStreamState struct {
mu sync.Mutex
LastMessageID string
Shells map[string]struct{}
Forms map[string]string
readGate chan struct{}
readback *ShellSnapshot
}
@@ -833,6 +887,9 @@ func NormalizeChatEvent(payload []byte, sessionID string, stream *ChatStreamStat
if outer.Type == "shell.created" || outer.Type == "shell.exited" {
return normalizeShellEvent(outer.Type, data, sessionID, stream)
}
if strings.HasPrefix(outer.Type, "form.") {
return normalizeFormEvent(outer.Type, data, sessionID, stream)
}
if data.SessionID != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
@@ -882,6 +939,88 @@ func NormalizeChatEvent(payload []byte, sessionID string, stream *ChatStreamStat
return frame, true, nil
}
// normalizeFormEvent maps one form.created / form.replied / form.cancelled
// payload onto a ChatEventForm frame. Form.created carries its own session; the
// terminal events carry only an id, so the stream remembers which session owns
// each pending form. A form from another session is ignored, and an unknown
// terminal id is another session's form rather than a malformed frame.
func normalizeFormEvent(eventType string, data chatEvent, sessionID string, stream *ChatStreamState) (protocol.ChatEventFrame, bool, error) {
if eventType == "form.created" {
form := data.Form
if form == nil || form.ID == "" {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode form.created event")
}
if form.SessionID != "" && form.SessionID != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
kind := ""
if form.Metadata != nil {
kind, _ = form.Metadata["kind"].(string)
}
frame := protocol.ChatForm{
ID: form.ID,
SessionID: sessionID,
Title: form.Title,
Kind: kind,
}
for _, field := range form.Fields {
out := protocol.ChatFormField{
Key: field.Key,
Title: field.Title,
Description: field.Description,
Type: field.Type,
Custom: field.Custom,
Required: field.Required,
}
for _, option := range field.Options {
value := option.Value
if value == "" {
value = option.Label
}
out.Options = append(out.Options, protocol.ChatFormOption{
Value: value, Label: option.Label, Description: option.Description,
})
}
frame.Fields = append(frame.Fields, out)
}
if stream != nil {
stream.mu.Lock()
if stream.Forms == nil {
stream.Forms = map[string]string{}
}
stream.Forms[form.ID] = sessionID
stream.mu.Unlock()
}
return protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: &frame}, true, nil
}
id := data.ID
if id == "" && data.Form != nil {
id = data.Form.ID
}
if id == "" {
return protocol.ChatEventFrame{}, false, fmt.Errorf("malformed OpenCode %s event", eventType)
}
if stream == nil {
return protocol.ChatEventFrame{}, false, nil
}
stream.mu.Lock()
owner, known := stream.Forms[id]
if known && owner == sessionID {
delete(stream.Forms, id)
}
stream.mu.Unlock()
if !known || owner != sessionID {
return protocol.ChatEventFrame{}, false, nil
}
form := &protocol.ChatForm{ID: id, SessionID: sessionID}
if eventType == "form.cancelled" {
form.Cancelled = true
} else {
form.Resolved = true
}
return protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: form}, true, nil
}
// normalizeShellEvent maps one shell.created/shell.exited payload onto a
// protocol.ChatEventShell frame. A shell belongs to the session whose id the
// created event carries in info.metadata.sessionID, so a shell started by any
+38
View File
@@ -822,3 +822,41 @@ func TestChatV1ConnectionDrivesThroughCall(t *testing.T) {
t.Fatalf("messages = %+v", page.Messages)
}
}
// TestNormalizeChatEventForm proves the question tool's form lifecycle is
// surfaced: form.created carries the field structure and is remembered for the
// session, while the terminal events (which carry only an id) resolve the same
// form for that session and are ignored for another.
func TestNormalizeChatEventForm(t *testing.T) {
state := &ChatStreamState{}
created := []byte(`{"type":"form.created","data":{"form":{"id":"form_1","sessionID":"ses_1","title":"Choose a colour","metadata":{"kind":"question"},"fields":[{"key":"colour","title":"Which colour?","description":"Pick one","type":"string","required":true,"options":[{"value":"red","label":"Red","description":"Warm"},{"value":"blue","label":"Blue"}]}]}}}`)
frame, ok, err := NormalizeChatEvent(created, "ses_1", state)
if err != nil || !ok {
t.Fatalf("form.created: ok=%v err=%v", ok, err)
}
if frame.Kind != protocol.ChatEventForm || frame.Form == nil {
t.Fatalf("form.created frame = %+v", frame)
}
if frame.Form.ID != "form_1" || frame.Form.Kind != "question" || len(frame.Form.Fields) != 1 {
t.Fatalf("form.created form = %+v", frame.Form)
}
field := frame.Form.Fields[0]
if field.Key != "colour" || field.Title != "Which colour?" || !field.Required || len(field.Options) != 2 {
t.Fatalf("form.created field = %+v", field)
}
if field.Options[0].Value != "red" || field.Options[0].Label != "Red" || field.Options[0].Description != "Warm" {
t.Fatalf("form option = %+v", field.Options[0])
}
// Another session's terminal event is not this session's form.
if _, ok, err := NormalizeChatEvent([]byte(`{"type":"form.replied","data":{"id":"form_1"}}`), "ses_2", state); err != nil || ok {
t.Fatalf("foreign form.replied: ok=%v err=%v", ok, err)
}
resolved, ok, err := NormalizeChatEvent([]byte(`{"type":"form.replied","data":{"id":"form_1"}}`), "ses_1", state)
if err != nil || !ok || resolved.Form == nil || !resolved.Form.Resolved || resolved.Form.ID != "form_1" {
t.Fatalf("form.replied frame = %+v ok=%v err=%v", resolved, ok, err)
}
if _, ok, err := NormalizeChatEvent([]byte(`{"type":"form.cancelled","data":{"id":"form_1"}}`), "ses_1", state); err != nil || ok {
t.Fatalf("duplicate/unknown form.cancelled: ok=%v err=%v", ok, err)
}
}
+27 -5
View File
@@ -30,6 +30,10 @@ type OperatorSession struct {
// so every client sees the same thing; the session and its history are never
// deleted, and reopening clears it back to 0.
ClosedAt int64
// StarredAt is the epoch-millisecond time the operator starred this session,
// or 0 while unstarred. It lives on the server so the starred group is shared
// by every browser and device.
StarredAt int64
}
// ChatCreateBootstrap is the durable progress record for one chat_create
@@ -58,7 +62,8 @@ func (s *Store) initOperatorSessions() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions (
session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL,
closed_at INTEGER NOT NULL DEFAULT 0, ephemeral INTEGER NOT NULL DEFAULT 0);
closed_at INTEGER NOT NULL DEFAULT 0, starred_at INTEGER NOT NULL DEFAULT 0,
ephemeral INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
if err != nil {
return err
@@ -134,6 +139,11 @@ func (s *Store) migrateOperatorSessions() error {
if err := s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// starred_at records the shared star. Existing sessions default to 0
// (unstarred); the column is independent of closed_at.
if err := s.addColumnIfMissing("operator_sessions", "starred_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// ephemeral marks a chat created for automated verification. It is hidden from
// OperatorSessions but still a real row, so the session stays usable and
// closable. Existing rows default to 0 (a normal, listed chat).
@@ -202,14 +212,26 @@ func (s *Store) ReopenOperatorSession(ctx context.Context, sessionID string) err
return err
}
// SetOperatorSessionStar records the shared star state in one UPDATE. A session
// id that is not an operator session updates no row and is not an error, so a
// pipeline-owned run session is never affected.
func (s *Store) SetOperatorSessionStar(ctx context.Context, sessionID string, starred bool) error {
at := int64(0)
if starred {
at = time.Now().UnixMilli()
}
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET starred_at=? WHERE session_id=?", at, sessionID)
return err
}
// OperatorSession returns one operator session by id. found is false when the id
// is not a recorded operator session (so a pipeline-owned run session is never
// returned). It is one indexed lookup and never mutates the row.
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
var session OperatorSession
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil {
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return OperatorSession{}, false, nil
}
@@ -228,7 +250,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at,starred_at
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
@@ -237,7 +259,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at D
sessions := []OperatorSession{}
for rows.Next() {
var session OperatorSession
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil {
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); err != nil {
return nil, err
}
sessions = append(sessions, session)
@@ -0,0 +1,53 @@
package pipeline
import (
"context"
"path/filepath"
"testing"
)
// TestOperatorSessionStarIsSharedAndReversible proves the server-side star
// contract: starring records starred_at on the registry row, listing returns it,
// unstarring clears it, and the OpenCode session id and other fields are never
// changed. This is what makes the Starred group visible from every browser.
func TestOperatorSessionStarIsSharedAndReversible(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "star.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionStar(ctx, "ses_a", true); err != nil {
t.Fatal(err)
}
starred, found, err := store.OperatorSession(ctx, "ses_a")
if err != nil || !found {
t.Fatalf("starred lookup: found=%v err=%v", found, err)
}
if starred.StarredAt <= 0 {
t.Fatalf("star did not record starred_at: %+v", starred)
}
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 1 || listed[0].StarredAt != starred.StarredAt {
t.Fatalf("list did not return the shared star: %+v", listed)
}
if err := store.SetOperatorSessionStar(ctx, "ses_a", false); err != nil {
t.Fatal(err)
}
plain, found, err := store.OperatorSession(ctx, "ses_a")
if err != nil || !found {
t.Fatalf("unstarred lookup: found=%v err=%v", found, err)
}
if plain.StarredAt != 0 {
t.Fatalf("unstar did not clear starred_at: %+v", plain)
}
if plain.ID != "ses_a" || plain.Directory != "/work/a" || plain.Title != "A" || plain.Tag != "operator" {
t.Fatalf("star toggling changed other session fields: %+v", plain)
}
}
+22 -2
View File
@@ -118,7 +118,8 @@ func (s *Store) Directory() string { return s.dir }
func (s *Store) List(ctx context.Context) ([]protocol.PipelineSummary, error) {
rows, err := s.db.QueryContext(ctx, `SELECT p.id, p.name, v.version,
json_array_length(v.graph_json, '$.stages'),
strftime('%Y-%m-%dT%H:%M:%SZ', p.created_at), strftime('%Y-%m-%dT%H:%M:%SZ', v.created_at)
strftime('%Y-%m-%dT%H:%M:%SZ', p.created_at), strftime('%Y-%m-%dT%H:%M:%SZ', v.created_at),
v.graph_json
FROM pipelines p JOIN pipeline_versions v ON v.pipeline_id=p.id
WHERE v.version=(SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=p.id)
ORDER BY p.name, p.id`)
@@ -129,9 +130,28 @@ ORDER BY p.name, p.id`)
result := []protocol.PipelineSummary{}
for rows.Next() {
var item protocol.PipelineSummary
if err := rows.Scan(&item.ID, &item.Name, &item.Version, &item.Stages, &item.CreatedAt, &item.UpdatedAt); err != nil {
var graphJSON string
if err := rows.Scan(&item.ID, &item.Name, &item.Version, &item.Stages, &item.CreatedAt, &item.UpdatedAt, &graphJSON); err != nil {
return nil, err
}
var shape protocol.Graph
if err := json.Unmarshal([]byte(graphJSON), &shape); err == nil && len(shape.Stages) > 0 {
// A list needs the drawing, not the definition: strip prompts,
// configs, tools, limits, notifications and checks so one list reply
// cannot leak a whole pipeline source or grow into a large payload.
shape.Settings = nil
for index := range shape.Stages {
stage := &shape.Stages[index]
stage.Prompt = ""
stage.Output = ""
stage.Configs = nil
stage.Blocks = nil
stage.Memory = nil
stage.Notify = nil
stage.Limits = nil
}
item.Shape = &shape
}
result = append(result, item)
}
return result, rows.Err()
+67 -1
View File
@@ -40,6 +40,10 @@ const (
// only records the finished state, it never detaches a client.
ChatClose = "chat_close"
ChatReopen = "chat_reopen"
// ChatStar records the operator's star on the server, so every browser and
// device shows the same starred group. It takes a ChatQuery with SessionID
// and Starred, and echoes the updated session like close/reopen.
ChatStar = "chat_star"
// ChatSubscribe attaches a connection to one session's shared live stream so
// it receives every frame any client's turn produces (its own and the other
// devices'), not only the frames of a turn it prompted itself. Any number of
@@ -61,6 +65,13 @@ const (
// ChatEvent and ChatPermission are the server-pushed frames; they are the
// only types the server sends without a matching request.
ChatEvent = "chat_event"
// ChatEventForm carries an OpenCode form (the agent's question tool uses a
// form with kind=question). It is a ChatEvent kind, not a separate request:
// the same frame stream that carries text and tools carries the question.
ChatEventForm = "form"
// ChatAnswer is the client's answer to a ChatEventForm. Answers is keyed by
// field key and mirrors OpenCode's form.reply answer object.
ChatAnswer = "chat_answer"
// ChatPermission carries one pending OpenCode approval request the phone
// answers with chat_reply.
ChatPermission = "chat_permission"
@@ -165,6 +176,11 @@ type ChatSession struct {
// Additive/omitempty so older peers ignore them.
Closed bool `json:"closed,omitempty"`
ClosedAt int64 `json:"closed_at,omitempty"`
// Starred is the operator's shared star, stored in the operator-session
// registry so every client sees the same Starred group. StarredAt is the
// epoch-millisecond time it was set, 0 while unstarred.
Starred bool `json:"starred,omitempty"`
StarredAt int64 `json:"starred_at,omitempty"`
}
// ChatCloseResult reports the outcome of a chat_close: the session id, the
@@ -210,7 +226,9 @@ type ChatAdoptRequest struct {
// returned history (server default when zero).
type ChatQuery struct {
SessionID string `json:"session_id"`
Limit int `json:"limit,omitempty"`
// Starred is set by chat_star; nil means the command did not name a state.
Starred *bool `json:"starred,omitempty"`
Limit int `json:"limit,omitempty"`
// Cursor is the opaque continuation returned by OpenCode's descending
// message listing. It is deliberately not interpreted by the broker.
Cursor string `json:"cursor,omitempty"`
@@ -346,6 +364,9 @@ type ChatEventFrame struct {
// status, the command it is running and (once it has exited) its exit code.
// It is nil on every other kind.
Shell *ChatShell `json:"shell,omitempty"`
// Form is the payload of a ChatEventForm frame: the agent's pending question
// (or another OpenCode form), and the resolved/cancelled terminal state.
Form *ChatForm `json:"form,omitempty"`
// Client is the sending device's label on a user frame (ChatEventUser), so a
// transcript can say who sent the message. It is empty on assistant frames.
Client string `json:"client,omitempty"`
@@ -374,6 +395,51 @@ type ChatUsage struct {
// distinguishable from "not exited yet". No credential, environment or output is
// carried: the command line is the only text, and only so the operator can name
// what is running.
// ChatForm is the agent's structured question/form. OpenCode emits these as
// form.created / form.replied / form.cancelled; the question tool uses
// Kind=="question". A client answers with ChatAnswerRequest. Answers is kept as
// JSON values because a field may be a string, a list (multiselect), a number or
// a boolean.
type ChatForm struct {
ID string `json:"id"`
SessionID string `json:"session_id,omitempty"`
Title string `json:"title,omitempty"`
Kind string `json:"kind,omitempty"`
Fields []ChatFormField `json:"fields,omitempty"`
Resolved bool `json:"resolved,omitempty"`
Cancelled bool `json:"cancelled,omitempty"`
Answers map[string]any `json:"answers,omitempty"`
}
// ChatFormField is one question/input in a form. Type is OpenCode's field type
// (string, multiselect, number, integer, boolean, external); Options is present
// when the question offers choices.
type ChatFormField struct {
Key string `json:"key"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Type string `json:"type,omitempty"`
Options []ChatFormOption `json:"options,omitempty"`
Custom bool `json:"custom,omitempty"`
Required bool `json:"required,omitempty"`
}
// ChatFormOption is one selectable choice in a ChatFormField.
type ChatFormOption struct {
Value string `json:"value"`
Label string `json:"label"`
Description string `json:"description,omitempty"`
}
// ChatAnswerRequest is the chat_answer body: the form id and a field-keyed
// answer object. It is deliberately separate from ChatQuery because its payload
// is structured answers, not a session-scoped read.
type ChatAnswerRequest struct {
SessionID string `json:"session_id"`
FormID string `json:"form_id"`
Answers map[string]any `json:"answers"`
}
type ChatShell struct {
ID string `json:"id"`
Status string `json:"status,omitempty"`
+7
View File
@@ -100,6 +100,10 @@ type PipelineSummary struct {
Stages int `json:"stages"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Shape is the current version's parsed graph, included so a list can draw
// a miniature without one detail request per row. Detail responses keep the
// full Graph field; this one is deliberately optional and additive.
Shape *Graph `json:"shape,omitempty"`
}
// Message is the JSON envelope shared by the server and client. It also brokers
@@ -179,6 +183,9 @@ type Message struct {
// requests themselves ride on ChatQuery (the session id), matching
// chat_messages/chat_interrupt.
ChatClose *ChatCloseResult `json:"chat_close,omitempty"`
// ChatAnswer is the chat_answer body; the form update arrives through the
// normal chat_event stream.
ChatAnswer *ChatAnswerRequest `json:"chat_answer,omitempty"`
// ChatSubscribe attaches this connection to one session's shared stream; the
// body names the session like ChatQuery. A chat_prompt response sets
// ChatQueued when the prompt had to wait for an in-flight turn and was
+14
View File
@@ -46,6 +46,13 @@ type chatPromptWithMessageID interface {
PromptWithMessageID(context.Context, string, string, string) error
}
// chatAnswerer is the optional form-answer surface. Test brokers and older
// backends need not implement it; a broker that does not answers chat_answer
// with a clear error rather than pretending the question was delivered.
type chatAnswerer interface {
Answer(context.Context, protocol.ChatAnswerRequest) error
}
type chatShellOutputReader interface {
ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error)
}
@@ -83,6 +90,7 @@ type operatorRegistry interface {
// session (which has no operator_sessions row).
CloseOperatorSession(ctx context.Context, sessionID string) error
ReopenOperatorSession(ctx context.Context, sessionID string) error
SetOperatorSessionStar(ctx context.Context, sessionID string, starred bool) error
}
var chatTokenSequence atomic.Uint64
@@ -121,6 +129,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatReply:
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatAnswer:
handleChatAnswer(ctx, request, broker, write)
return true
case protocol.ChatSessions:
handleChatSessions(ctx, request, broker, hub, registry, write)
return true
@@ -139,6 +150,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatReopen:
handleChatReopen(ctx, request, registry, write)
return true
case protocol.ChatStar:
handleChatStar(ctx, request, registry, write)
return true
case protocol.ChatShells:
handleChatShells(ctx, request, broker, registry, write)
return true
+48
View File
@@ -0,0 +1,48 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// handleChatAnswer replies to one OpenCode form, which is how the agent's
// question tool resumes: the tool call is paused inside form.created until a
// client answers. It validates the session/form ids before calling the broker,
// so a malformed answer cannot reach another session. The resulting
// form.replied/form.cancelled event arrives on the ordinary chat_event stream
// and clears the card on every watching client.
func handleChatAnswer(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
answer := request.ChatAnswer
if answer == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat_answer payload is required"})
return
}
if !opencode.ValidSessionID(answer.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
if answer.FormID == "" {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a form id is required"})
return
}
if len(answer.Answers) == 0 {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "at least one answer is required"})
return
}
answerer, ok := broker.(chatAnswerer)
if !ok {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "this chat backend cannot answer questions"})
return
}
if err := answerer.Answer(ctx, *answer); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
_ = write(protocol.Message{Type: protocol.ChatAnswer, ID: request.ID})
}
+4
View File
@@ -140,5 +140,9 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess
out.Closed = true
out.ClosedAt = session.ClosedAt
}
if session.StarredAt > 0 {
out.Starred = true
out.StarredAt = session.StarredAt
}
return out
}
+19
View File
@@ -157,6 +157,25 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) {
}
turn.applyShell(frame.Shell)
return
case protocol.ChatEventForm:
// A form/question likewise carries no message id. Keep the pending form
// for a late subscriber; a resolved or cancelled form removes it.
if frame.Form == nil || frame.Form.ID == "" {
return
}
if room := h.rooms[frame.SessionID]; room != nil {
next := room.forms[:0]
for _, form := range room.forms {
if form.ID != frame.Form.ID {
next = append(next, form)
}
}
room.forms = next
if !frame.Form.Resolved && !frame.Form.Cancelled && len(room.forms) < 8 {
room.forms = append(room.forms, *frame.Form)
}
}
return
}
if frame.MessageID == "" {
return
+16 -1
View File
@@ -137,7 +137,10 @@ type chatRoom struct {
// pending holds the room's unresolved approval requests, in the order they
// were raised, replayed to a client that attaches after they were raised. A
// request is removed once it is resolved.
pending []protocol.ChatPermissionFrame
pending []protocol.ChatPermissionFrame
// forms holds the room's unresolved question/form frames so a client that
// attaches after the agent asked still renders the question.
forms []protocol.ChatForm
pollerStarted bool
wake chan struct{}
turnDone chan struct{}
@@ -548,6 +551,18 @@ func (h *chatHub) submitPrompt(sessionID string, p *chatQueuedPrompt) (queued bo
// pendingFrames returns a copy of the room's unresolved approval requests so a
// client that attaches after they were raised can be shown every one of them. It
// returns nil when the room holds none.
func (h *chatHub) pendingForms(sessionID string) []protocol.ChatForm {
h.mu.Lock()
defer h.mu.Unlock()
room := h.rooms[sessionID]
if room == nil || len(room.forms) == 0 {
return nil
}
forms := make([]protocol.ChatForm, len(room.forms))
copy(forms, room.forms)
return forms
}
func (h *chatHub) pendingFrames(sessionID string) []protocol.ChatPermissionFrame {
h.mu.Lock()
defer h.mu.Unlock()
+2
View File
@@ -80,6 +80,8 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
// clients may watch and write one session.
session.Closed = operator.ClosedAt > 0
session.ClosedAt = operator.ClosedAt
session.Starred = operator.StarredAt > 0
session.StarredAt = operator.StarredAt
response.ChatSessions = append(response.ChatSessions, session)
}
_ = write(response)
+59
View File
@@ -0,0 +1,59 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// handleChatStar records the operator's shared star for one operator chat
// session. It is a registry write, not a local preference: every browser and
// device lists the same Starred group, and starring never mutates the OpenCode
// session or its transcript. A session id that is not a recorded operator
// session is refused before anything is written, so a pipeline-owned run session
// is never touched. The request body is a ChatQuery carrying SessionID and the
// desired Starred value; the reply echoes the updated session.
func handleChatStar(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) {
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
if query.Starred == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a starred state is required"})
return
}
sessionID := query.SessionID
if _, found, err := registry.OperatorSession(ctx, sessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
} else if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is not an operator chat session"})
return
}
if err := registry.SetOperatorSessionStar(ctx, sessionID, *query.Starred); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
session, found, err := registry.OperatorSession(ctx, sessionID)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is no longer an operator session"})
return
}
wire := chatSessionFromOperator(session)
write(protocol.Message{
Type: protocol.ChatStar,
ID: request.ID,
ChatSession: &wire,
ChatSessions: []protocol.ChatSession{wire},
})
}
+10
View File
@@ -132,6 +132,16 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
frame := pending
sub.send(protocol.Message{Type: protocol.ChatPermission, ChatPermission: &frame})
}
// Replay a question/form the agent raised before this client attached, so a
// reload or another device still sees the paused tool call.
for _, form := range hub.pendingForms(query.SessionID) {
pending := form
sub.send(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
SessionID: query.SessionID,
Kind: protocol.ChatEventForm,
Form: &pending,
}})
}
// Replay the background processes still running, so a device that attaches
// after they started (a reconnect, or a chat opened from another device)
// shows them rather than nothing until they exit. The message snapshot cannot