Documentation
¶
Overview ¶
Package timeline builds the unified task-detail timeline consumed by both the TUI and the Web UI. It imports orchestrator only — no api dependency — so web/templates can import it without creating an import cycle with internal/api (which pulls in web/templates for rendering).
The builder takes fully-resolved inputs: the task, its actions, and a list of JobInfo records. Each caller adapts from its own Job shape (api.Job / dispatcher job model) via ConvertAPIJob-style helpers.
Index ¶
- Constants
- func BuildActionLabel(a *orchestrator.Action) string
- func BuildJobLabel(j *JobInfo) string
- func ClampCardTimelineLimit(requested int) int
- func FormatElapsed(t time.Time) string
- func IsAPIGatewayRequestAction(a *orchestrator.Action) bool
- func IsAnsweredAction(a *orchestrator.Action) bool
- func IsProgressAction(a *orchestrator.Action) bool
- func IsStateTransition(a *orchestrator.Action) bool
- func JobDuration(j *JobInfo) string
- type CardChildDetail
- type CardCommandDetail
- type CardItem
- type CardItemKind
- type CardTimelinePage
- type Event
- type EventKind
- type JobInfo
- type StatusGroup
Constants ¶
const ( DefaultCardTimelineLimit = 10 MaxCardTimelineLimit = 200 )
DefaultCardTimelineLimit / MaxCardTimelineLimit bound one BuildCardTimeline call's ITEM count, mirroring orchestrator.ClampActionListLimit's role for the raw action list.
const ( JobStatusRunning = "running" JobStatusCompleted = "completed" JobStatusFailed = "failed" )
JobStatus mirrors the string values used by api.JobStatus so timeline renderers don't need to import api to discriminate running / completed / failed states. Callers pass these strings through.
const ActionTypeAPIGatewayRequest = "api_gateway_request"
ActionTypeAPIGatewayRequest is the orchestrator.Action.Type recorded for one API gateway request. Exported so internal/server's apigateway.RequestRecorder adapter can tag every Action it writes with this exact value — a single source of truth shared by the writer and the readers here, rather than two packages each hard-coding the same magic string.
These rows are intentionally audit-only: a multi-request gateway operation (a paginated search, a status-polling loop) would otherwise spam the task-detail timeline with one row per request, so Build excludes them from the rendered Event list. The row still lands in the actions table and remains queryable via TaskRepository.ListActionsByTask — only the timeline *display* drops it.
Variables ¶
This section is empty.
Functions ¶
func BuildActionLabel ¶
func BuildActionLabel(a *orchestrator.Action) string
BuildActionLabel returns the display label for a timeline action. State transitions: "<type> → <to_status>". Progress actions: "進捗: <message>" (extracted from JSON payload). Answered actions: "answered: <accept|reject>" (falls back to the bare "answered" type string if the payload is missing/malformed — Build itself never lets a malformed answered payload land here in practice, since parseAnsweredPayload validates it before CreateAction, but this stays defensive rather than assuming that invariant).
func BuildJobLabel ¶
BuildJobLabel returns the display label for a job.
- completed: "[role] <name> ✓ <duration>" (name omitted when empty)
- failed: "[role] <name> ✗ <duration>"
- running: "[role] <elapsed> ago"
- other: "[role] <name><status>"
DisplayName is used when set; otherwise HandlerID is used as fallback. When role is "hook", the "[hook]" prefix is omitted — the handler name alone identifies the hook sufficiently.
func ClampCardTimelineLimit ¶ added in v0.5.0
ClampCardTimelineLimit resolves a caller-requested limit (<=0 meaning "use the default") against the two constants above.
func FormatElapsed ¶
FormatElapsed returns a short MM:SS (or HH:MM:SS) elapsed string since t. Matches the TUI helper so that TUI display is unchanged after shared-timeline migration. Exported so the Web UI can compute the initial server-side value for a running job's live-ticking elapsed counter.
func IsAPIGatewayRequestAction ¶ added in v0.1.0
func IsAPIGatewayRequestAction(a *orchestrator.Action) bool
IsAPIGatewayRequestAction reports whether an action records one API gateway request. Consulted only by Build's unconditional exclusion check (see ActionTypeAPIGatewayRequest's own doc comment).
func IsAnsweredAction ¶ added in v0.4.0
func IsAnsweredAction(a *orchestrator.Action) bool
IsAnsweredAction reports whether an action records a human's accept/ reject answer to a Web UI suggestion. Consulted by Build to deliberately ALLOW this one non-transitioning action type through, unlike the general non-transitioning/non-progress exclusion just below (which still applies to attrs_set / child_added / child_specced / noted).
`answered` is the one non-transitioning action a human directly triggers by clicking a Web UI button (the task-detail page's Accept/Reject pair). Without this, clicking Reject makes the suggestion card disappear with no human-visible trace anywhere in the UI. The others are daemon-internal or script-originated, not something a human clicks, so they don't share this gap.
func IsProgressAction ¶
func IsProgressAction(a *orchestrator.Action) bool
IsProgressAction reports whether an action is a non-transitioning progress note.
func IsStateTransition ¶
func IsStateTransition(a *orchestrator.Action) bool
IsStateTransition reports whether an action carries a recorded status change, including a self-loop (FromStatus == ToStatus) for the types in selfLoopTransitionTypes. Build's grouping only opens a new StatusGroup when ToStatus differs from FromStatus, so a self-loop still renders as one Event in the current group rather than a spurious new visit.
func JobDuration ¶
JobDuration returns a human-readable duration for a completed/failed job. Returns "?" when the job has no UpdatedAt or UpdatedAt is not after CreatedAt.
Types ¶
type CardChildDetail ¶ added in v0.5.0
type CardChildDetail struct {
ChildID string
Title string
// Status is one of orchestrator.TaskTriageChildStatus*.
Status string
Spec *orchestrator.TaskTriageChildSpec
TaskRef string
// TaskExists reports whether TaskRef still resolves to a live task row —
// false once the child's own task has been GC'd (GCTasks, 30 days after
// terminal). A caller must not render a link when this is false.
TaskExists bool
// ClosingActionType is "child_closed" (the child's own task reached
// done/aborted) or "child_dropped" (withdrawn before ever being
// dispatched) once Status is closed; "" while still open/specced/
// dispatched.
ClosingActionType string
// HasResult, Result, ResultStatus are populated from the child_closed
// action's own payload (never from a live task lookup), so they survive
// the child task row's own GC. Only set when ClosingActionType is
// "child_closed" — a child_dropped closure carries no result.
HasResult bool
Result string
ResultStatus orchestrator.TaskStatus
// LiveStatus is the dispatched child's live orchestrator.TaskStatus
// (executing/awaiting/done/aborted). This package never sets it — it is
// a caller-side enrichment; "" means unresolved.
LiveStatus string
}
CardChildDetail is CardItem's payload for Kind == CardItemChild (both the rich creation-position item and its lightweight CardItemChildFinished pointer share the same *CardChildDetail — see loadCardTimelineState).
type CardCommandDetail ¶ added in v0.5.0
type CardCommandDetail struct {
RequestID string
CommandKey string
// Label is the launch-time snapshot (card_requests.launched_label) —
// empty for a still-queued (never-launched) pinned request.
Label string
// Instruction is best-effort: read from the LIVE card_requests row when
// it still exists. Once GCCardRequests has removed that row, this is
// simply "" — only Result/Error/Reason (sourced from the terminal
// action's own payload) are guaranteed to survive that GC.
Instruction string
// Origin is "human" or "event" (orchestrator.CardRequestOrigin).
Origin string
CauseID string
TargetKind string
TargetID string
// TargetExists is resolved only for TargetKind == "task" (checked via a
// live task lookup) — false once that task has been GC'd. Left false,
// not "unknown", for TargetKind == "session": a session's liveness is a
// job-table concern the existing job pages already own, out of scope
// here.
TargetExists bool
// Status is the live card_requests.status (queued/launching/attached),
// set only while Pinned — a renderer needs this to distinguish "not
// dispatched yet" from "running" (a queued request has no target, no
// Label, and would otherwise be indistinguishable from a launching
// one). Empty for a terminal history item, where Outcome is the
// authoritative status instead.
Status orchestrator.CardRequestStatus
// Outcome is "" while Pinned (still running), else one of "finished" /
// "failed" / "force_released".
Outcome string
Result string
Error string
Reason string
}
CardCommandDetail is CardItem's payload for Kind == CardItemCommand. The same struct shape covers both a still-running command (Pinned, Outcome == "") and a terminal history entry (Outcome one of finished/failed/ force_released).
type CardItem ¶ added in v0.5.0
type CardItem struct {
ID string
Kind CardItemKind
// Time is the item's position, straight from actions.created_at (UTC).
// This package does no timezone conversion — a renderer calls .Local()
// at format time, the same way web/templates/tasks.templ already does
// for the execution-detail timeline.
Time time.Time
HasTime bool
CorrelationID string
// Pinned marks an item BuildCardTimeline deliberately excludes
// (CardPinnedItems returns it instead) because it is still the current
// occupant of a fixed slot. Once resolved, the same ID reappears from
// BuildCardTimeline at its normal chronological position.
Pinned bool
// Action is the backing action for every kind except CardItemChild (and
// a still-pinned CardItemCommand, which has none yet).
Action *orchestrator.Action
// Child is populated only for Kind == CardItemChild.
Child *CardChildDetail
// Command is populated only for Kind == CardItemCommand.
Command *CardCommandDetail
// Operation is the associated human attempt, or a standalone receipt.
Operation *orchestrator.OperationResult
}
CardItem is one row of a card's timeline read model. Kind selects which of Action/Child/Command is populated. ID is a raw actions.id for every action-backed kind, or a deterministic derived string for the two cases that don't map 1:1 onto one action (a suggestion/summary sharing one attrs_set action gets "<action id>:suggestion" / "<action id>:summary"; a still-pinned, not-yet-launched command has no action yet and gets "pending-command:<request id>").
CorrelationID is a relationship key, never an identity: it lets a UI link a CardItemChildFinished back to its CardItemChild (both carry the child's stable TaskTriageChild.ID). A pinned CardItemCommand leaves it empty — its pinned and terminal forms are never displayed at once, so nothing needs linking.
func CardPinnedItems ¶ added in v0.5.0
CardPinnedItems returns cardID's currently-pinned items: the live suggestion, the next unresolved work spec/child, and the sole in-progress task/session (a dispatched child, or a running card command). Uses the SAME CardItem type/IDs BuildCardTimeline would eventually show once resolved.
func OperationCardItem ¶ added in v0.5.0
func OperationCardItem(receipt *orchestrator.OperationResult) CardItem
OperationCardItem retains rejected and unconfirmed attempts alongside work history.
type CardItemKind ¶ added in v0.5.0
type CardItemKind string
CardItemKind enumerates the kinds of item a card's timeline read model returns.
const ( // CardItemChild is one work child, tracked by its stable // TaskTriageChild.ID from spec through execution to closure, sitting at // its child_added (creation) position. CardItemChild CardItemKind = "child" // CardItemChildFinished is the lightweight pointer item a closed child // leaves at ITS OWN closing position, linking back to CardItemChild via // CorrelationID. CardItemChildFinished CardItemKind = "child_finished" // CardItemCommand is a card command's self-recorded terminal outcome, or // — when Pinned — the card command currently running. CardItemCommand CardItemKind = "command" // CardItemSuggestion is one attrs_set action whose payload carries a // "suggestion" key. CardItemSuggestion CardItemKind = "suggestion" // CardItemAnswered is one "answered" action. CardItemAnswered CardItemKind = "answered" // CardItemSummary is one attrs_set action whose payload carries a // "summary" key. CardItemSummary CardItemKind = "summary" // CardItemNote is one "noted" action. CardItemNote CardItemKind = "note" // CardItemWakeDue is one "wake_due" action. CardItemWakeDue CardItemKind = "wake_due" // CardItemOperation is an attempt without a corresponding command item. CardItemOperation CardItemKind = "operation" )
type CardTimelinePage ¶ added in v0.5.0
type CardTimelinePage struct {
Items []CardItem
// NextCursor: pass to the next BuildCardTimeline call's cursor argument
// to load older items ("Load older"). Unchanged from the input cursor
// when Items is empty (same "nothing new, keep resending" contract as
// orchestrator.ListActionsSince).
NextCursor string
// HasMore reports whether older items exist beyond this page.
HasMore bool
}
CardTimelinePage is one page of BuildCardTimeline's result.
func BuildCardTimeline ¶ added in v0.5.0
BuildCardTimeline returns cardID's history, newest-first, paginated by ITEM (not raw action) via a keyset cursor over (item time, item id) — EncodeActionCursor/DecodeActionCursor's own format, reused verbatim. Items currently pinned are excluded — see CardPinnedItems.
type Event ¶
type Event struct {
Time time.Time
HasTime bool
Kind EventKind
Label string
Action *orchestrator.Action
Job *JobInfo
Sticky bool
}
Event is a single row in the unified timeline. Exactly one of Action / Job is populated, matching Kind.
Sticky marks a synthesized reference row that surfaces a long-lived job under the task's CURRENT status group (in addition to the historic group where the job originally landed). Without this, a single hook job that outlives multiple ask/answer round trips (the canonical `boid task ask` blocking RPC pattern) would only render under its starting executing group while later status visits look empty even though the same agent process is still running there. Sticky events are non-authoritative — they share the underlying *JobInfo with the original row — so renderers must treat them as display-only (no separate progress fetch, no double-counted runtime, etc.).
type JobInfo ¶
type JobInfo struct {
ID string
Role string
HandlerID string
DisplayName string // optional; shown instead of HandlerID when non-empty
Status string // one of JobStatusRunning / Completed / Failed (or other)
ExitCode int
CreatedAt time.Time
UpdatedAt time.Time
}
JobInfo is the minimum job data needed to place a job on the timeline and render its label / status icon / link target. Callers convert from their native job type (api.Job for TUI / Web).
type StatusGroup ¶
StatusGroup groups events under a single task-status visit. Repeated visits to the same status produce distinct groups in order.
func Build ¶
func Build(task *orchestrator.Task, actions []*orchestrator.Action, jobs []*JobInfo) []StatusGroup
Build groups filtered events by the task-status visit in which they occurred. Only state-transition actions and jobs are included. hook_fired actions are intentionally dropped because the associated job carries the same information (success, handler id, duration) plus output.
Each visit to a status creates a new group so repeated visits (e.g. executing → aborted → pending → executing) produce distinct groups in chronological order instead of collapsing same-status events into one.
Each group's EnteredAt records when the task entered that visit:
- initial group: task.CreatedAt
- subsequent groups: the CreatedAt of the transition action that moved into it