Skip to content

Commit fe5e545

Browse files
authored
Improve plan cards, xAI reauth, and TUI activity command display (#509)
* Improve plan cards, xAI reauth, and activity command display Render plan context as a design-doc overview without a CONTEXT label, preserve fenced headings, and surface xAI OAuth re-authentication in the TUI when tokens expire. Wrap full shell commands in the activity fold instead of truncating, and add understand-before-changing work policy to code and graph-plan prompts. * Collapse long TUI activity commands to one preview line Show the full command in the collapsed activity fold when it fits on one line. If it would wrap, keep a single truncated preview and reveal the full wrapped command on expand. * Put TUI activity commands on the same row as the label Collapsed Run command rows now match Find files: status, label, and command on one line. Short commands show in full; longer ones clip to terminal width. Expand still shows the full wrapped command body.
1 parent 8fe11d7 commit fe5e545

24 files changed

Lines changed: 899 additions & 57 deletions

‎docs/architecture/terminal-app.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ Phase → additive allow-list (`GraphPlanPhaseTools`, single source of truth; th
387387

388388
When the agent finalizes via `announce_plan`, `pkg/launcher/tui_code.go` emits one atomic `plan` payload containing the rendered `# Execution Plan` document, approval options, and lifecycle (`pending`, `approved`, `changes_requested`, or `declined`), followed by `done`. The matching mapper in `tui_chat.go` produces one `KindPlan` event, and `events/transcript.go` creates one `ItemPlan` that owns both the document and approval state. A pending plan points `ApprovalIdx` at that same item; no detached `ItemApproval` or footer is created.
389389

390-
The card (`pkg/tui/plan.go`) is a structured parse of PLAN.md via `agent.ParsePlanDocument`, not a generic markdown bubble. Layout: amber-bordered frame (code mode `PlanBorder`/`PlanHeader` = 172, matching the Plan-mode composer; platform stays steel-blue 75) with numbered phases, status glyphs (`[○]`/`[●]`/`[✓]`/`[✗]`), `+`/`~`/`−` file kinds, CONTEXT / WHAT NOT TO CHANGE / VERIFY bands, and a `k/n ready|running|done` footer. While pending, the selectable approval controls are rendered inside this same frame. After a decision, the document remains and the controls are replaced in place by `Approved`, `Changes requested`, or `Declined`. Unparseable documents use the same lifecycle section in the markdown fallback, so the plan never goes blank.
390+
The card (`pkg/tui/plan.go`) is a structured parse of PLAN.md via `agent.ParsePlanDocument`, not a generic markdown bubble. Layout: amber-bordered frame (code mode `PlanBorder`/`PlanHeader` = 172, matching the Plan-mode composer; platform stays steel-blue 75) with numbered phases, status glyphs (`[○]`/`[●]`/`[✓]`/`[✗]`), `+`/`~`/`−` file kinds, a label-free overview whose `##` headings render as full-width bars (title, rule, blank, body), WHAT NOT TO CHANGE / VERIFY bands, and a `k/n ready|running|done` footer. Chat markdown leaves heading bars off (`HeadingBar` is plan-card only). While pending, the selectable approval controls are rendered inside this same frame. After a decision, the document remains and the controls are replaced in place by `Approved`, `Changes requested`, or `Declined`. Unparseable documents use the same lifecycle section in the markdown fallback, so the plan never goes blank.
391391

392392
Approval actions live in `handlePlanApprovalKey` (called from `handleApprovalKey` before generic y/n/esc, the same way network denials are). Mapping: Enter submits the highlighted option (cursor defaults to implement); `y`/`1` implement; `r`/`2` request changes (stay in Plan mode, composer placeholder becomes "Describe the changes to the plan…"); `n`/`esc`/`3` decline (back to Normal). Do not route plan keys through `pickYes`/`pickNo`. Code mode persists the decision as a session state-delta event; history reconstructs each `announce_plan` as a plan entry defaulting to pending and applies later decision deltas. Therefore a session closed while waiting resumes with the same in-card controls, while a settled session resumes with its permanent status and no prompt.
393393

‎pkg/agent/code_system_prompt_builder.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ func (b *CodeSystemPromptBuilder) build(base *SystemPromptBuilder) string {
129129
sb.WriteString("- **Codegraph-first rule:** Before reading files or grepping to understand an unfamiliar area, call `codegraph_explore` first. It answers symbol definitions, call graphs, and cross-file dependencies in 1–4 calls and costs far fewer tokens than file reads. Once codegraph has named the relevant files, read only those — do not read files codegraph did not point you to. Fall back to grep/find only for what codegraph cannot answer (runtime strings, config keys, non-indexed paths).\n")
130130
sb.WriteString("- Do NOT re-read a file already read this session unless it changed. If you need multiple regions of a file, batch them in a single `read_file` call with a wide enough range, or read the whole file once. Do not read the same file in many small sequential chunks.\n")
131131
// Stop-exploring discipline — always present in code mode
132-
sb.WriteString("- **Stop exploring when the scope is clear.** Once you can name every file you will change and why, stop reading and start acting. Do not read additional files \"for context\" beyond what the change directly touches. The goal is a correct, complete change — not a codebase survey. Exception: if the bug is a running surface (sandbox, daemon, browser, live session), inspect the live process/overlay before more production edits — naming files is not enough.\n")
132+
sb.WriteString("- **Stop exploring when the scope is clear.** You are done exploring once you can name every file you will change and why AND you understand what the current code does, what calls it, and what your change will impact — not merely which files to edit. Then stop reading and start acting. Do not read additional files \"for context\" beyond what the change and its blast radius touch. The goal is a correct, complete change — not a codebase survey. Exception: if the bug is a running surface (sandbox, daemon, browser, live session), inspect the live process/overlay before more production edits — naming files is not enough.\n")
133133
sb.WriteString("- http_request CANNOT reach private/RFC1918 IPs (192.168.x.x, 10.x.x.x, 172.16-31.x.x) or localhost. Use curl via shell_command for private network endpoints.\n")
134134
sb.WriteString("- For multi-step tasks, execute sequentially, report progress.\n")
135135
sb.WriteString("- When the user asks you to do something, briefly acknowledge before starting work.\n")
@@ -229,6 +229,7 @@ func (b *CodeSystemPromptBuilder) build(base *SystemPromptBuilder) string {
229229
sb.WriteString("- Keep every explicit user requirement in view until it is completed, superseded, or blocked out loud. Do not drop a constraint to finish a phase.\n")
230230
sb.WriteString("- Match your response to the user's intent. Implement clear action requests; answer questions, reviews, explanations, and planning requests without making unsolicited project edits.\n")
231231
sb.WriteString("- Match effort to the request. A one-line fix does not need a plan; a cross-cutting refactor does.\n")
232+
sb.WriteString("- **Understand before changing (proportional to blast radius).** For a change request, first understand what the target functionality currently does and what depends on it, then identify ambiguities and the impact of your change, and only then propose or edit. Scale this to the blast radius: a typo or one-line local fix needs almost none; changing existing behavior, or touching a shared/exported symbol, means tracing callers with code_references and stating the impact before editing. A pure question just gets answered — this discipline is for changes. If the target is genuinely ambiguous (could be code area A or B), surface the options to the user and let them choose before editing.\n")
232233
sb.WriteString("- For clear, reversible local work, do it in the current turn instead of asking permission conversationally or ending with an offer to do it later.\n")
233234
sb.WriteString("- Claim that something is done, fixed, tested, or addressed only when this turn's tool output supports the claim. Library/code: a test that encodes the user-visible sequence failed before the change and passes after. Running surfaces (sandbox, daemon, browser, CLI, UI): observe the live process or run a drill. Package tests of unrelated code are not proof. In Plan execution, the runtime runs each phase's `verify` command — prose does not count. Otherwise state what you did not verify and why.\n")
234235
sb.WriteString("- Keep changes scoped to what was asked. Match the surrounding code's comment and tooling conventions.\n")

‎pkg/agent/plan_document.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,15 @@ func RenderPlanMarkdown(goal string, steps []planStep) string {
154154
func downgradeHeadings(s string) string {
155155
lines := strings.Split(s, "\n")
156156
changed := false
157+
inFence := false
157158
for i, line := range lines {
159+
if strings.HasPrefix(strings.TrimSpace(line), "```") {
160+
inFence = !inFence
161+
continue
162+
}
163+
if inFence {
164+
continue
165+
}
158166
if strings.HasPrefix(line, "## ") {
159167
lines[i] = "#" + line // "## X" → "### X"
160168
changed = true

‎pkg/agent/plan_document_test.go‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,3 +819,52 @@ func TestDowngradeHeadings(t *testing.T) {
819819
}
820820
}
821821
}
822+
823+
func TestPlanDocument_RoundTrip_StructuredContext(t *testing.T) {
824+
orig := planClock
825+
planClock = func() time.Time { return time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC) }
826+
defer func() { planClock = orig }()
827+
828+
context := "## Problem\n" +
829+
"We need to preserve fenced content verbatim.\n\n" +
830+
"```text\n" +
831+
"## inside-fence comment\n" +
832+
"A --> B --> C\n" +
833+
"```\n\n" +
834+
"| A | B |\n" +
835+
"| - | - |\n" +
836+
"| 1 | 2 |\n"
837+
838+
doc := PlanDocumentInfo{
839+
Context: context,
840+
Verification: "run go test ./pkg/agent/...",
841+
}
842+
steps := []PlanStepInfo{
843+
{Name: "explore", Description: "look around", Summary: "understand the code", Outcome: "map exists", Verify: "go test ./pkg/agent/...", VerifyKind: "unit"},
844+
{Name: "implement", Description: "make changes", Summary: "apply the fix", Outcome: "tests pass", Verify: "go test ./pkg/agent/...", VerifyKind: "unit"},
845+
}
846+
847+
rendered := RenderPlanFromInfoWithDoc("Some goal", doc, steps)
848+
849+
parsedDoc, parsedGoal, parsedSteps, err := ParsePlanDocument(rendered)
850+
if err != nil {
851+
t.Fatalf("ParsePlanDocument returned error: %v\n---\n%s", err, rendered)
852+
}
853+
854+
if !strings.Contains(parsedDoc.Context, "## inside-fence comment") {
855+
t.Errorf("parsed Context missing verbatim in-fence line\n---\n%s", parsedDoc.Context)
856+
}
857+
if !strings.Contains(parsedDoc.Context, "| 1 | 2 |") {
858+
t.Errorf("parsed Context missing table row\n---\n%s", parsedDoc.Context)
859+
}
860+
861+
// Idempotency: render again from parsed doc/steps, parse, compare context.
862+
rendered2 := RenderPlanFromInfoWithDoc(parsedGoal, parsedDoc, parsedSteps)
863+
parsedDoc2, _, _, err := ParsePlanDocument(rendered2)
864+
if err != nil {
865+
t.Fatalf("ParsePlanDocument (2nd) returned error: %v\n---\n%s", err, rendered2)
866+
}
867+
if parsedDoc2.Context != parsedDoc.Context {
868+
t.Errorf("round-trip not stable:\nfirst:\n%s\nsecond:\n%s", parsedDoc.Context, parsedDoc2.Context)
869+
}
870+
}

‎pkg/agent/plan_mode_gate_test.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,16 @@ func TestPlanModeSystemContext_StrategySummary(t *testing.T) {
260260
t.Error("PlanModeSystemContext should NOT contain 'WITHOUT any preceding prose' (replaced by strategy summary)")
261261
}
262262
}
263+
264+
func TestGraphPlanModeSystemContext_UnderstandFirst(t *testing.T) {
265+
ctx := GraphPlanModeSystemContext
266+
for _, want := range []string{
267+
"UNDERSTAND BEFORE YOU SHAPE THE CHANGE",
268+
"not merely to locate the files you will edit",
269+
"surface A-vs-B options to the user",
270+
} {
271+
if !strings.Contains(ctx, want) {
272+
t.Errorf("GraphPlanModeSystemContext should mention %q (understand-first discipline)", want)
273+
}
274+
}
275+
}

‎pkg/agent/system_prompt_contracts_code_test.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,13 +170,26 @@ func TestCodeSystemPromptContracts_InvestigationWorkPolicy(t *testing.T) {
170170
"CloakBrowser",
171171
"this turn's tool output",
172172
"inspect-live-surface",
173+
"Understand before changing",
174+
"proportional to blast radius",
175+
"what your change will impact",
173176
} {
174177
if !strings.Contains(prompt, want) {
175178
t.Errorf("code-mode Work Policy missing %q", want)
176179
}
177180
}
178181
}
179182

183+
func TestCodeSystemPromptContracts_UnderstandBeforeChanging(t *testing.T) {
184+
prompt := maximalCodeBuilder().Build()
185+
// The understand-before-changing discipline must be present, phrased as a
186+
// proportional (non-ceremonious) posture that gates edits on understanding
187+
// and surfaces A-vs-B ambiguity to the user before editing.
188+
assertContains(t, prompt, "only then propose or edit", "understand-before-changing gates editing on understanding")
189+
assertContains(t, prompt, "surface the options to the user", "understand-before-changing surfaces ambiguity to the user")
190+
assertContains(t, prompt, "proportional", "understand-before-changing is proportional, not a hard mandate")
191+
}
192+
180193
func TestCodeSystemPromptContracts_PlanFilePersistence(t *testing.T) {
181194
cb := maximalCodeBuilder()
182195
prompt := cb.Build()

‎pkg/agent/testdata/code_system_prompt_golden.txt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Use tabs.
3636
- **Code navigation rule (MUST):** In supported languages (Go, TS/TSX, JS/JSX, Python), to find where a symbol (function, type, method, constant, variable) is DEFINED or USED, you MUST use `code_definition` / `code_references` — do NOT use `grep_search` for this. They return exact declarations/call sites in one call, without the comment/string/unrelated-match noise that forces grep follow-up reads. Call `repo_map` once to orient in an unfamiliar repo. Fall back to `grep_search` for a symbol only when the structural tool returns nothing. Keep using `grep_search` for non-symbol text (log strings, config keys, comments, error messages, cross-language literals).
3737
- **Codegraph-first rule:** Before reading files or grepping to understand an unfamiliar area, call `codegraph_explore` first. It answers symbol definitions, call graphs, and cross-file dependencies in 1–4 calls and costs far fewer tokens than file reads. Once codegraph has named the relevant files, read only those — do not read files codegraph did not point you to. Fall back to grep/find only for what codegraph cannot answer (runtime strings, config keys, non-indexed paths).
3838
- Do NOT re-read a file already read this session unless it changed. If you need multiple regions of a file, batch them in a single `read_file` call with a wide enough range, or read the whole file once. Do not read the same file in many small sequential chunks.
39-
- **Stop exploring when the scope is clear.** Once you can name every file you will change and why, stop reading and start acting. Do not read additional files "for context" beyond what the change directly touches. The goal is a correct, complete change — not a codebase survey. Exception: if the bug is a running surface (sandbox, daemon, browser, live session), inspect the live process/overlay before more production edits — naming files is not enough.
39+
- **Stop exploring when the scope is clear.** You are done exploring once you can name every file you will change and why AND you understand what the current code does, what calls it, and what your change will impact — not merely which files to edit. Then stop reading and start acting. Do not read additional files "for context" beyond what the change and its blast radius touch. The goal is a correct, complete change — not a codebase survey. Exception: if the bug is a running surface (sandbox, daemon, browser, live session), inspect the live process/overlay before more production edits — naming files is not enough.
4040
- http_request CANNOT reach private/RFC1918 IPs (192.168.x.x, 10.x.x.x, 172.16-31.x.x) or localhost. Use curl via shell_command for private network endpoints.
4141
- For multi-step tasks, execute sequentially, report progress.
4242
- When the user asks you to do something, briefly acknowledge before starting work.
@@ -102,6 +102,7 @@ You have a configured identity for web portal registrations and interactions. Us
102102
- Keep every explicit user requirement in view until it is completed, superseded, or blocked out loud. Do not drop a constraint to finish a phase.
103103
- Match your response to the user's intent. Implement clear action requests; answer questions, reviews, explanations, and planning requests without making unsolicited project edits.
104104
- Match effort to the request. A one-line fix does not need a plan; a cross-cutting refactor does.
105+
- **Understand before changing (proportional to blast radius).** For a change request, first understand what the target functionality currently does and what depends on it, then identify ambiguities and the impact of your change, and only then propose or edit. Scale this to the blast radius: a typo or one-line local fix needs almost none; changing existing behavior, or touching a shared/exported symbol, means tracing callers with code_references and stating the impact before editing. A pure question just gets answered — this discipline is for changes. If the target is genuinely ambiguous (could be code area A or B), surface the options to the user and let them choose before editing.
105106
- For clear, reversible local work, do it in the current turn instead of asking permission conversationally or ending with an offer to do it later.
106107
- Claim that something is done, fixed, tested, or addressed only when this turn's tool output supports the claim. Library/code: a test that encodes the user-visible sequence failed before the change and passes after. Running surfaces (sandbox, daemon, browser, CLI, UI): observe the live process or run a drill. Package tests of unrelated code are not proof. In Plan execution, the runtime runs each phase's `verify` command — prose does not count. Otherwise state what you did not verify and why.
107108
- Keep changes scoped to what was asked. Match the surrounding code's comment and tooling conventions.

‎pkg/agent/tool_categories.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,9 @@ func PlanModeBlockedMessage(toolName string) string {
102102
// GraphPlanModeSystemContext is the per-turn instruction injected when
103103
// Graph-Optimized Plan mode is active (code mode only). The runtime enforces
104104
// the phase gate; this prompt teaches the model the "plan-for-the-plan"
105-
// discipline so it works WITH the gate instead of fighting it. It must stay in
106-
// sync with the TUI mirror (pkg/tui/app.go: graphPlanModeSystemContext).
105+
// discipline so it works WITH the gate instead of fighting it. It is injected
106+
// per-turn as PromptOverrides.SessionContext (there is no separate copy in
107+
// pkg/tui); this constant is the single source of truth.
107108
const GraphPlanModeSystemContext = `You are in Astonish GRAPH-OPTIMIZED PLAN MODE. This is a hard constraint enforced by the runtime through a staged tool gate, not a suggestion. Like Plan mode, this is a NO-CHANGES mode: write_file, edit_file, shell_command and every other mutating tool are DISABLED in every phase and will be refused.
108109
109110
BEFORE INVESTIGATING — MATCH YOUR RESPONSE TO THE USER'S INTENT:
@@ -117,6 +118,8 @@ Plan mode does not mean every message must produce a plan. Assess the user's mes
117118
118119
Remember: you are in Code mode — a local terminal IDE on the user's filesystem, not the Studio web UI.
119120
121+
UNDERSTAND BEFORE YOU SHAPE THE CHANGE: The GRAPH and READ phases exist so you understand what the current functionality does and its blast radius (callers, dependents, impact) — not merely to locate the files you will edit. Establish behavior and impact first, identify any ambiguity about WHICH code the request targets, and surface A-vs-B options to the user rather than guessing. Only after that should the PLAN phase shape the change.
122+
120123
When the user's intent IS an action request, the runtime advances through four phases. Each phase unlocks a specific set of tools; you move between phases by calling small transition tools. Do NOT try to call a tool before its phase — the gate will refuse it and tell you which phase it belongs to.
121124
122125
PHASE 1 — GRAPH (current at turn start). Only ` + "`codegraph_explore`" + ` and ` + "`find_files`" + ` are available. codegraph is a pre-computed knowledge graph of this repo: symbols, call edges, dependencies, cross-file references, and change blast-radius. Query it FIRST to understand the code you will touch — it answers most structural questions in 1-4 calls with far fewer tokens than grep. Compound your findings as you go: never re-query the graph for something already in your context. When you have identified the exact regions you need to read, call ` + "`gplan_reads`" + ` with the synthesized read list (each entry: path + why you need it). Only include paths that ` + "`codegraph_explore`" + ` explicitly returned — do NOT guess or infer filenames; if you need a file but do not have its confirmed path, use ` + "`find_files`" + ` to locate it first. This advances you to the READ phase. If codegraph returns no coverage (language unsupported / not indexed), call ` + "`gplan_gaps`" + ` immediately to skip straight to the GAP phase.

0 commit comments

Comments
 (0)