From b69832250548eb495a52d4b73717c3c449ed27fc Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Thu, 3 Sep 2026 07:15:59 +1000 Subject: [PATCH] fix(gateway): split /status (health) and /tasks (work) apart /status conflated two unrelated concerns: a thin per-status task count that duplicated information belonging to a task view, and runtime config already visible via /model. Worse, a bare status count actively misled -- "Running: 1" read the same whether that task was making progress or stuck in a failure loop, because a count carries no age or identity. /status now reports one aggregate queue-depth line (in-flight work: running/waiting/parked, health signal only) instead of an itemized breakdown -- queued and terminal states are excluded as neither actionable nor a health concern. /tasks is new: the live, per-task view with enough identity and state to act on it (id, title, status, workflow/stage, age since last transition, attempt once a retry has happened, and a parked task's reason). Age comes from Task.UpdatedAt, already persisted and now threaded through ChatTaskSummary and chatTaskListerAdapter -- no new instrumentation needed. Tasks sort actionable-first (running, waiting, parked, ...) ahead of terminal states, stable within a status group so the lister's own recency order survives. Wired via the existing configureTaskCommands call sites (web, telegram, email, webhook) using the same chatTaskListerAdapter already built for the task_list LLM tool -- no parallel data path. Note: internal/gateway's separate /agents command (AgentReader) is NOT touched here and remains dead in production (Router.Agents is never wired by any composition-root call site) -- tracked as its own finding, not folded into this fix. --- internal/app/archied/bootstrap.go | 6 +- internal/app/archied/main.go | 18 ++- internal/app/archied/main_test.go | 10 +- internal/app/archied/telegram_setup.go | 2 +- internal/channels/telegram/commands.go | 3 +- internal/gateway/gateway.go | 152 +++++++++++++++++++------ internal/gateway/gateway_test.go | 143 +++++++++++++++++++---- internal/gateway/task_tools.go | 12 ++ 8 files changed, 281 insertions(+), 65 deletions(-) diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 7416300a2..2ef98ef9b 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -526,7 +526,7 @@ func (b *boot) setupLLMAndChat(ctx context.Context) { } b.webRouter.Personas = b.personas b.webRouter.InitSessions(b.chatSessionStore) - configureTaskCommands(b.webRouter, b.chatTasks, b.chatController, b.defaultChatIdentity) + configureTaskCommands(b.webRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity) webSetup := telegramSetup{ Cfg: config.NewHolder(cfg), St: b.st, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg, Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController, @@ -593,7 +593,7 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b if cfg.Chat.Email.ListenAddr != "" { em := email.New(cfg.Chat.Email.ListenAddr, cfg.Chat.Email.RelayAddr, log) emRouter := gateway.NewRouter(b.st, nil, "email") - configureTaskCommands(emRouter, b.chatTasks, b.chatController, b.defaultChatIdentity) + configureTaskCommands(emRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity) b.startGateways = append(b.startGateways, func() { go func() { lifecycle := gateway.Lifecycle{ @@ -621,7 +621,7 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b log, ) whRouter := gateway.NewRouter(b.st, nil, "webhook") - configureTaskCommands(whRouter, b.chatTasks, b.chatController, b.defaultChatIdentity) + configureTaskCommands(whRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity) b.startGateways = append(b.startGateways, func() { go func() { lifecycle := gateway.Lifecycle{ diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 4bd50f7ec..1b411901b 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -159,12 +159,16 @@ func (a chatTaskListerAdapter) ListChatTasks(ctx context.Context, identity strin break } out = append(out, gateway.ChatTaskSummary{ - ID: task.ID, - Repo: task.Owner + "/" + task.Repo, - Title: task.Title, - Status: task.Status, - Workflow: task.Workflow, - PRNumber: task.PRNumber, + ID: task.ID, + Repo: task.Owner + "/" + task.Repo, + Title: task.Title, + Status: task.Status, + Workflow: task.Workflow, + Stage: task.Stage, + PRNumber: task.PRNumber, + Attempt: task.Attempt, + ParkReason: task.ParkReason, + UpdatedAt: task.UpdatedAt, }) } return out, nil @@ -743,10 +747,12 @@ func configureTaskCommands( router *gateway.Router, tasks gateway.TaskCreator, controller gateway.TaskController, + lister gateway.ChatTaskLister, identity string, ) { router.Tasks = tasks router.Controller = controller + router.TaskLister = lister router.Identity = identity } diff --git a/internal/app/archied/main_test.go b/internal/app/archied/main_test.go index f7747a2cf..fa83edbc7 100644 --- a/internal/app/archied/main_test.go +++ b/internal/app/archied/main_test.go @@ -522,6 +522,14 @@ func TestChatTaskListerAdapterReadsSQLiteIdentity(t *testing.T) { if len(got) != 1 || got[0].ID != want.ID || got[0].Title != want.Title { t.Fatalf("ListChatTasks = %+v, want task %d", got, want.ID) } + // /tasks (gateway.formatTasks) needs these to show "what needs the + // operator": workflow/stage, age, and (for a parked task) why. + if got[0].Workflow != want.Workflow { + t.Errorf("ListChatTasks()[0].Workflow = %q, want %q", got[0].Workflow, want.Workflow) + } + if got[0].UpdatedAt.IsZero() { + t.Error("ListChatTasks()[0].UpdatedAt is zero, want the task's row timestamp") + } } func TestChatTaskWriterAdapter(t *testing.T) { @@ -777,7 +785,7 @@ func TestChatTaskCommandsEndToEnd(t *testing.T) { transition: st.Transition, }) router := gateway.NewRouter(st, nil, "test") - configureTaskCommands(router, creator, controller, defaultIdentity) + configureTaskCommands(router, creator, controller, chatTaskListerAdapter{tasks: st.Tasks}, defaultIdentity) reply, err := router.Route(ctx, gateway.Message{ Text: "/spawn identity=reviewer workflow=feasibility Design native tasks", diff --git a/internal/app/archied/telegram_setup.go b/internal/app/archied/telegram_setup.go index 6cffc359e..90017b2b3 100644 --- a/internal/app/archied/telegram_setup.go +++ b/internal/app/archied/telegram_setup.go @@ -270,7 +270,7 @@ func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSe router.InitSessions(sessionStore) router.Titles = newChatTitleGenerator(s) router.Log = s.Log - configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity) + configureTaskCommands(router, s.ChatTasks, s.ChatController, s.ChatTaskLister, s.DefaultChatIdentity) if s.LLM != nil { turnRunner := newChatTurnRunner(ctx, tg.Name(), s, sessionStore, router) diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go index 6edb2788d..e3f754414 100644 --- a/internal/channels/telegram/commands.go +++ b/internal/channels/telegram/commands.go @@ -19,7 +19,8 @@ type commandSpec struct { // published command menu and /help. Keeping the discoverability surfaces // together prevents a newly registered command from being omitted from help. var gatewayCommandSpecs = []commandSpec{ - {Command: "status", Description: "Show task counts by state", Usage: "/status"}, + {Command: "status", Description: "Show daemon health", Usage: "/status"}, + {Command: "tasks", Description: "Show running and parked work", Usage: "/tasks"}, {Command: "version", Description: "Show installed Archie versions", Usage: "/version"}, {Command: "update", Description: "Check for Archie updates", Usage: "/update"}, {Command: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"}, diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2ed5bbe14..86b6e8d6a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -257,7 +257,10 @@ type Router struct { Personas *PersonaRegistry Tasks TaskCreator // nil = /spawn not configured Controller TaskController // nil = /approve and /cancel not configured - LLM LLMResponder // nil = LLM not wired yet + // TaskLister backs /tasks: the live work view (id, title, status, + // workflow/stage, age). nil = /tasks not configured. + TaskLister ChatTaskLister + LLM LLMResponder // nil = LLM not wired yet // LLMStream is the optional streaming responder. When set, adapters // that can render partial output (see RouteStream) show the reply as // it generates; when nil, everything falls back to LLM. @@ -353,6 +356,9 @@ func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd strin case "/status": reply, err := r.handleStatus(ctx) return reply, true, err + case "/tasks": + reply, err := r.handleTasks(ctx) + return reply, true, err case "/model": _, arg := parseCmd(text, "") reply, err := r.handleModel(ctx, arg) @@ -519,7 +525,7 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, stream TurnStream } var localCommands = []string{ - "/status", "/model", "/spawn", "/approve", "/cancel", + "/status", "/tasks", "/model", "/spawn", "/approve", "/cancel", "/start", "/new", "/reset", "/topic", "/retry", "/undo", "/title", "/branch", "/fork", "/compress", "/compact", @@ -537,7 +543,8 @@ type CommandSpec struct { } var localCommandSpecs = []CommandSpec{ - {Command: "/status", Description: "Show task counts by state", Usage: "/status"}, + {Command: "/status", Description: "Show daemon health", Usage: "/status"}, + {Command: "/tasks", Description: "Show running and parked work", Usage: "/tasks"}, {Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"}, {Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn "}, {Command: "/approve", Description: "Approve a waiting task", Usage: "/approve <task-id>"}, @@ -774,6 +781,73 @@ func (r *Router) handleStatus(ctx context.Context) (string, error) { return formatStatus(counts, r.Models), nil } +// handleTasks answers /tasks: the live view of this identity's work, with +// enough identity and state to act on it. This is the division of labour +// /status used to blur -- /status now reports health, /tasks reports work. +func (r *Router) handleTasks(ctx context.Context) (string, error) { + if r.TaskLister == nil { + return "task list not configured", nil + } + tasks, err := r.TaskLister.ListChatTasks(ctx, r.Identity, defaultTaskListLimit) + if err != nil { + return "", fmt.Errorf("tasks: %w", err) + } + return formatTasks(tasks, time.Now()), nil +} + +// formatTasks renders each task with enough identity and state to act on +// it: id, title, status, workflow/stage, and age since its last +// transition -- so a task that is running but stuck (old UpdatedAt) reads +// differently from one making progress (recent UpdatedAt), which a bare +// status count could never distinguish. +func formatTasks(tasks []ChatTaskSummary, now time.Time) string { + var b strings.Builder + b.WriteString("๐Ÿ—‚ Archie tasks\n\n") + if len(tasks) == 0 { + b.WriteString("No tasks yet\n") + return strings.TrimSpace(b.String()) + } + sortTasksByPriority(tasks) + for _, t := range tasks { + icon, label := "โ€ข", formatCustomStatus(t.Status) + if d, ok := taskStateDisplays[t.Status]; ok { + icon, label = d.icon, d.label + } + fmt.Fprintf(&b, "%s #%d %s\n", icon, t.ID, t.Title) + fmt.Fprintf(&b, " %s", label) + if stage := workflowStage(t.Workflow, t.Stage); stage != "" { + fmt.Fprintf(&b, " ยท %s", stage) + } + if t.Attempt > 1 { + fmt.Fprintf(&b, " ยท attempt %d", t.Attempt) + } + if age := relativeAge(t.UpdatedAt, now); age != "" { + fmt.Fprintf(&b, " ยท updated %s", age) + } + b.WriteString("\n") + if t.Status == taskstate.Parked && t.ParkReason != "" { + fmt.Fprintf(&b, " โ†ณ %s\n", t.ParkReason) + } + } + return strings.TrimSpace(b.String()) +} + +// workflowStage joins a task's workflow and stage for display, degrading +// gracefully when either is unknown (e.g. a task that hasn't started its +// first stage yet). +func workflowStage(workflow, stage string) string { + switch { + case workflow == "" && stage == "": + return "" + case stage == "": + return workflow + case workflow == "": + return stage + default: + return workflow + "/" + stage + } +} + type taskStateDisplay struct { icon string label string @@ -805,20 +879,19 @@ var statusOrder = []string{ taskstate.Dead, } -func sortStatuses(counts map[string]int) []string { - statuses := make([]string, 0, len(counts)) - for s := range counts { - statuses = append(statuses, s) - } - +// sortTasksByPriority orders tasks so the ones an operator would look for +// first -- running, then waiting on them, then parked -- lead the list, +// with terminal states (merged, rejected, dead, ...) trailing. It is +// stable, so within one status group the lister's own recency order +// survives. +func sortTasksByPriority(tasks []ChatTaskSummary) { orderMap := make(map[string]int, len(statusOrder)) for i, s := range statusOrder { orderMap[s] = i } - - slices.SortFunc(statuses, func(a, b string) int { - idxA, okA := orderMap[a] - idxB, okB := orderMap[b] + slices.SortStableFunc(tasks, func(a, b ChatTaskSummary) int { + idxA, okA := orderMap[a.Status] + idxB, okB := orderMap[b.Status] if okA && okB { return cmp.Compare(idxA, idxB) } @@ -828,10 +901,8 @@ func sortStatuses(counts map[string]int) []string { if okB { return 1 } - return strings.Compare(a, b) + return strings.Compare(a.Status, b.Status) }) - - return statuses } func formatCustomStatus(s string) string { @@ -911,26 +982,14 @@ func formatRuntimeSection(b *strings.Builder, provider, model string) { fmt.Fprintf(b, "Provider: %s\nModel: %s\n", provider, model) } -// formatStatus formats the task counts and active runtime details into -// a clean, mobile-friendly summary. +// formatStatus formats daemon health into a clean, mobile-friendly summary. +// It deliberately does not itemize tasks -- that is /tasks' job -- so it +// reduces the task counts to one aggregate health signal (is work backing +// up) rather than duplicating /tasks' per-task list. func formatStatus(counts map[string]int, models ModelManager) string { var b strings.Builder - b.WriteString("๐Ÿ“Š Archie status\n\nTasks\n") - - statuses := sortStatuses(counts) - if len(statuses) == 0 { - b.WriteString("No tasks yet\n") - } else { - for _, s := range statuses { - count := counts[s] - d, ok := taskStateDisplays[s] - if ok { - fmt.Fprintf(&b, "%s %s: %d\n", d.icon, d.label, count) - } else { - fmt.Fprintf(&b, "โ€ข %s: %d\n", formatCustomStatus(s), count) - } - } - } + b.WriteString("๐Ÿ“Š Archie status\n\n") + b.WriteString(formatQueueDepth(counts)) provider, model := extractRuntimeInfo(models) formatRuntimeSection(&b, provider, model) @@ -938,6 +997,31 @@ func formatStatus(counts map[string]int, models ModelManager) string { return strings.TrimSpace(b.String()) } +// formatQueueDepth summarizes in-flight work as one line: how many tasks +// are running, waiting on a human reply, or parked. Queued and terminal +// states are excluded -- neither is a health concern an operator needs +// /status to surface. +func formatQueueDepth(counts map[string]int) string { + running := counts[taskstate.Running] + waiting := counts[taskstate.WaitingHuman] + parked := counts[taskstate.Parked] + inFlight := running + waiting + parked + if inFlight == 0 { + return "Queue: idle\n" + } + var parts []string + if running > 0 { + parts = append(parts, fmt.Sprintf("%d running", running)) + } + if waiting > 0 { + parts = append(parts, fmt.Sprintf("%d waiting on you", waiting)) + } + if parked > 0 { + parts = append(parts, fmt.Sprintf("%d parked", parked)) + } + return fmt.Sprintf("Queue: %d in flight (%s)\n", inFlight, strings.Join(parts, ", ")) +} + func (r *Router) handleWhoami() (string, error) { if r.Identity == "" { return "I'm Archie, running without a configured identity.", nil diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 9da3c759a..680c3f3a0 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -7,6 +7,9 @@ import ( "slices" "strings" "testing" + "time" + + "github.com/samcharles93/archie-core/internal/taskstate" ) type fakeStore struct { @@ -22,13 +25,15 @@ func fakeLLM(ctx context.Context, msg Message) (string, error) { return "llm: " + msg.Text, nil } -func TestRouteStatusWithTasks(t *testing.T) { +func TestRouteStatusShowsQueueDepthNotPerTaskCounts(t *testing.T) { r := NewRouter(&fakeStore{counts: map[string]int{"queued": 2, "pr_open": 1}}, nil, "test") reply, err := r.Route(context.Background(), Message{Text: "/status"}) if err != nil { t.Fatalf("Route: %v", err) } - want := "๐Ÿ“Š Archie status\n\nTasks\nโณ Queued: 2\n๐Ÿ”€ PR open: 1\n\nRuntime\nNot configured" + // queued and pr_open are not "in flight" (running/waiting/parked), so + // /status reports the daemon idle -- that per-task detail is /tasks' job. + want := "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured" if reply != want { t.Errorf("reply =\n%q\nwant:\n%q", reply, want) } @@ -46,7 +51,7 @@ func TestRouteStatusIncludesActiveProviderAndModel(t *testing.T) { if err != nil { t.Fatal(err) } - want := "๐Ÿ“Š Archie status\n\nTasks\nโ–ถ Running: 1\n\nRuntime\nProvider: OpenAI\nModel: openai/gpt-5.6" + want := "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running)\n\nRuntime\nProvider: OpenAI\nModel: openai/gpt-5.6" if reply != want { t.Fatalf("reply =\n%q\nwant:\n%q", reply, want) } @@ -58,8 +63,8 @@ func TestRouteStatusAtMention(t *testing.T) { if err != nil { t.Fatalf("Route: %v", err) } - if !strings.Contains(reply, "โ–ถ Running: 3") { - t.Errorf("reply missing counts: %q", reply) + if !strings.Contains(reply, "3 running") { + t.Errorf("reply missing queue depth: %q", reply) } } @@ -69,7 +74,7 @@ func TestRouteStatusEmpty(t *testing.T) { if err != nil { t.Fatalf("Route: %v", err) } - want := "๐Ÿ“Š Archie status\n\nTasks\nNo tasks yet\n\nRuntime\nNot configured" + want := "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured" if reply != want { t.Errorf("reply = %q, want %q", reply, want) } @@ -94,15 +99,15 @@ func TestFormatStatus(t *testing.T) { want string }{ { - name: "example from specification - single parked task with provider and model", + name: "single parked task with provider and model", counts: map[string]int{"parked": 2}, models: &fakeProviderModelManager{ activeModel: "openai/gpt-5.6-luna", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nโธ Parked: 2\n\nRuntime\nProvider: OpenAI\nModel: openai/gpt-5.6-luna", + want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 parked)\n\nRuntime\nProvider: OpenAI\nModel: openai/gpt-5.6-luna", }, { - name: "multiple task states in canonical order", + name: "in-flight states reduce to one aggregate line; queued and terminal states are excluded", counts: map[string]int{ "queued": 4, "running": 1, @@ -118,7 +123,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeProviderModelManager{ activeModel: "deepseek/deepseek-v4-pro", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nโ–ถ Running: 1\n๐Ÿ‘ค Waiting: 2\nโธ Parked: 3\nโณ Queued: 4\n๐Ÿ”€ PR open: 5\nโœ… Merged: 6\nโŒ Rejected: 7\n๐Ÿšซ Declined: 8\n๐Ÿ›‘ Dead: 9\nโ€ข Custom state: 10\n\nRuntime\nProvider: DeepSeek\nModel: deepseek/deepseek-v4-pro", + want: "๐Ÿ“Š Archie status\n\nQueue: 6 in flight (1 running, 2 waiting on you, 3 parked)\n\nRuntime\nProvider: DeepSeek\nModel: deepseek/deepseek-v4-pro", }, { name: "empty task counts with active model", @@ -126,7 +131,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeModelManager{ activeModel: "anthropic/claude-3-5-sonnet", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nNo tasks yet\n\nRuntime\nProvider: Anthropic\nModel: anthropic/claude-3-5-sonnet", + want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nProvider: Anthropic\nModel: anthropic/claude-3-5-sonnet", }, { name: "nil counts with active model", @@ -134,19 +139,19 @@ func TestFormatStatus(t *testing.T) { models: &fakeModelManager{ activeModel: "google/gemini-2.5-flash", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nNo tasks yet\n\nRuntime\nProvider: Google\nModel: google/gemini-2.5-flash", + want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nProvider: Google\nModel: google/gemini-2.5-flash", }, { name: "nil model manager", counts: map[string]int{"running": 2}, models: nil, - want: "๐Ÿ“Š Archie status\n\nTasks\nโ–ถ Running: 2\n\nRuntime\nNot configured", + want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 running)\n\nRuntime\nNot configured", }, { name: "empty counts and nil model manager", counts: map[string]int{}, models: nil, - want: "๐Ÿ“Š Archie status\n\nTasks\nNo tasks yet\n\nRuntime\nNot configured", + want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured", }, { name: "custom display namer interface", @@ -154,15 +159,15 @@ func TestFormatStatus(t *testing.T) { models: &fakeCustomDisplayNamerManager{ activeModel: "openai/gpt-5.6", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nโ–ถ Running: 1\n\nRuntime\nProvider: OpenAI Custom Enterprise\nModel: openai/gpt-5.6", + want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running)\n\nRuntime\nProvider: OpenAI Custom Enterprise\nModel: openai/gpt-5.6", }, { - name: "provider set but model empty", + name: "queued-only counts as idle -- queued is not in flight", counts: map[string]int{"queued": 1}, models: &fakeProviderModelManager{ activeModel: "", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nโณ Queued: 1\n\nRuntime\nNot configured", + want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured", }, { name: "model without slash and no provider manager", @@ -170,7 +175,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeModelManager{ activeModel: "custom-local-model", }, - want: "๐Ÿ“Š Archie status\n\nTasks\nโ–ถ Running: 1\n\nRuntime\nProvider: Not configured\nModel: custom-local-model", + want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running)\n\nRuntime\nProvider: Not configured\nModel: custom-local-model", }, } @@ -191,6 +196,106 @@ func TestRouteStatusError(t *testing.T) { } } +// -- /tasks tests -- + +type fakeChatTaskLister struct { + tasks []ChatTaskSummary + err error +} + +func (f *fakeChatTaskLister) ListChatTasks(ctx context.Context, identity string, limit int) ([]ChatTaskSummary, error) { + return f.tasks, f.err +} + +func TestRouteTasksNotConfigured(t *testing.T) { + r := NewRouter(nil, nil, "test") + reply, err := r.Route(context.Background(), Message{Text: "/tasks"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if reply != "task list not configured" { + t.Errorf("reply = %q, want the not-configured message", reply) + } +} + +func TestRouteTasksEmpty(t *testing.T) { + r := NewRouter(nil, nil, "test") + r.TaskLister = &fakeChatTaskLister{} + reply, err := r.Route(context.Background(), Message{Text: "/tasks"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + want := "๐Ÿ—‚ Archie tasks\n\nNo tasks yet" + if reply != want { + t.Errorf("reply = %q, want %q", reply, want) + } +} + +func TestRouteTasksError(t *testing.T) { + r := NewRouter(nil, nil, "test") + r.TaskLister = &fakeChatTaskLister{err: errors.New("store unavailable")} + if _, err := r.Route(context.Background(), Message{Text: "/tasks"}); err == nil { + t.Error("expected error from Route when ListChatTasks fails") + } +} + +func TestFormatTasks(t *testing.T) { + now := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC) + + tests := []struct { + name string + tasks []ChatTaskSummary + want string + }{ + { + name: "running task shows workflow/stage and age", + tasks: []ChatTaskSummary{ + {ID: 42, Title: "Fix login bug", Status: taskstate.Running, Workflow: "tdd", Stage: "implement", UpdatedAt: now.Add(-3 * time.Minute)}, + }, + want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #42 Fix login bug\n Running ยท tdd/implement ยท updated 3m ago", + }, + { + name: "parked task shows its reason", + tasks: []ChatTaskSummary{ + {ID: 17, Title: "Add dark mode", Status: taskstate.Parked, Workflow: "feasibility", ParkReason: "gate failed 3x", UpdatedAt: now.Add(-2 * time.Hour)}, + }, + want: "๐Ÿ—‚ Archie tasks\n\nโธ #17 Add dark mode\n Parked ยท feasibility ยท updated 2h ago\n โ†ณ gate failed 3x", + }, + { + name: "attempt is shown only once a retry has happened", + tasks: []ChatTaskSummary{ + {ID: 1, Title: "First try", Status: taskstate.Running, Attempt: 1, UpdatedAt: now}, + {ID: 2, Title: "Retried", Status: taskstate.Running, Attempt: 2, UpdatedAt: now}, + }, + want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #1 First try\n Running ยท updated just now\nโ–ถ #2 Retried\n Running ยท attempt 2 ยท updated just now", + }, + { + name: "an unrecognized status still renders, generically", + tasks: []ChatTaskSummary{ + {ID: 9, Title: "Mystery", Status: "custom_state", UpdatedAt: now}, + }, + want: "๐Ÿ—‚ Archie tasks\n\nโ€ข #9 Mystery\n Custom state ยท updated just now", + }, + { + name: "actionable work leads terminal work regardless of recency", + tasks: []ChatTaskSummary{ + {ID: 3, Title: "Just merged", Status: taskstate.Merged, UpdatedAt: now}, + {ID: 4, Title: "Still running", Status: taskstate.Running, UpdatedAt: now.Add(-time.Hour)}, + }, + want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #4 Still running\n Running ยท updated 1h ago\nโœ… #3 Just merged\n Merged ยท updated just now", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := formatTasks(tc.tasks, now) + if got != tc.want { + t.Errorf("formatTasks() =\n%q\nwant:\n%q", got, tc.want) + } + }) + } +} + func TestRouteNonCommandWithLLM(t *testing.T) { r := NewRouter(nil, fakeLLM, "test") reply, err := r.Route(context.Background(), Message{Text: "hello"}) @@ -996,7 +1101,7 @@ func TestRouteAgentsError(t *testing.T) { func TestLocalCommandsIncludesNewCommands(t *testing.T) { cmds := LocalCommands() - for _, want := range []string{"/whoami", "/profile", "/sessions", "/resume", "/agents"} { + for _, want := range []string{"/whoami", "/profile", "/sessions", "/resume", "/agents", "/tasks"} { if !slices.Contains(cmds, want) { t.Errorf("LocalCommands() missing %s", want) } diff --git a/internal/gateway/task_tools.go b/internal/gateway/task_tools.go index 7a6ef83a5..4d1bd1052 100644 --- a/internal/gateway/task_tools.go +++ b/internal/gateway/task_tools.go @@ -34,7 +34,19 @@ type ChatTaskSummary struct { Title string `json:"title"` Status string `json:"status"` Workflow string `json:"workflow,omitempty"` + Stage string `json:"stage,omitempty"` PRNumber int `json:"pr_number,omitempty"` + // Attempt is the task's current retry attempt. 0 or 1 means it has never + // been retried; the /tasks command only surfaces this once it is + // actionable information (attempt > 1). + Attempt int `json:"attempt,omitempty"` + // ParkReason explains why a parked task is parked. Empty for any other + // status. + ParkReason string `json:"park_reason,omitempty"` + // UpdatedAt is the task's last transition time, so a caller can tell a + // task that is running but stuck (old UpdatedAt) from one making + // progress (recent UpdatedAt). + UpdatedAt time.Time `json:"updated_at,omitzero"` } // ChatTaskLister is the read surface the task tools need. It mirrors the