diff --git a/CHANGELOG.md b/CHANGELOG.md index f752865ae..e14c4bce1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **The Pulls screen is redrawn, and its list is sorted by what each pull request needs.** Open ones are grouped into Ready to merge, Needs work, In review and Drafts, in place of the All, Ready, Drafts and Failing filters and the Approved state. Inside a pull request, its facts stand beside the description, and Copy link and Copy Markdown are in the `⋯` menu. - **The Git panel shows one thing at a time.** Changes and History are now two tabs, and a commit opens beside the log when you click it. The branches open from the branch's name in the panel's header: click one to check it out, type a new name to create it, and find the rest in its `⋯`. - **A finished turn in the chat is your message, the answer and the files it changed.** The calls, thoughts and texts on the way fold under one line with the time they took, like Worked for 4m 6s; click it to read them in order. Each changed file is listed once under the answer, and a click opens all its edits. +- **A permission the agent asks for in the chat now waits over the message box.** It says what the agent wants to do and shows the whole command, or each file with its diff, with the answers always in view. Once you answer, only the call is left in the conversation, or a Denied line. - **Review threads in Pulls show who answers whom.** Each thread is a card with its file and code, and its replies hang from a line under the comment they answer, in Conversation and between the lines in Files. - **Long conversations no longer slow the window down.** Scrolling, typing and watching an answer come in cost about the same in a chat of thousands of messages as in a new one, and several agents working at once take about a third of the diff --git a/docs/ceilings.md b/docs/ceilings.md index 264d66e76..222ef47d2 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -417,6 +417,11 @@ work when nobody knows it and that the call site never shows. The mechanism and one-time allow and every digit answers. Crush has no chat. On every provider Enter answers nothing and an "always" option is never the suggestion; a digit typed on an empty composer the instant the box comes still answers, since nothing holds the keys for a moment after it shows. +- **A chat permission finds its call by name and target, not by id** (`native/cmd/lich-native/chat_rows.go`, + `asksAbout`). A permission item carries a copy of the call and no id of it, so the window hides the call while it + waits, and once denied, by the nearest one before it in the turn with the same name and title that did not go + well. A provider whose ask words the call otherwise than the call itself shows both: the call's line, and the box + or its Denied line. It never hides a call that went well. - **A chat turn's count of changes is a difference of two numstat readings, not a record of what the agent did** (`internal/chat/changes.go`, `internal/project/lines.go`): lich reads `git diff --numstat HEAD` and the untracked files before the message goes out and again when the turn ends, and counts the files whose numbers differ. It diff --git a/native/DESIGN.md b/native/DESIGN.md index 24baafa13..4d5346982 100644 --- a/native/DESIGN.md +++ b/native/DESIGN.md @@ -528,7 +528,7 @@ never makes the Latest pill show. message to the last thing the turn did, "Worked" where nobody reported times or under a second. In a long turn the texts on the way ("now the tests") weighed as much as the conclusion, which had to be hunted for. The answer is the last run of the agent's texts; what folds is every other text, thought, run of calls, failed - edit and answered permission. Never folded: a message or a steer, an answer to a question, a plan, a `!` + edit and denied permission. Never folded: a message or a steer, an answer to a question, a plan, a `!` command, a compaction and a notice; what stands between two of the first five is a stretch with its own line and answer. A turn with nothing to fold has no line, unless it was stopped, "Stopped after 41s", or failed, "Failed after 12s" in `Destructive`, which say so with nothing under them too. There is no closing line and no @@ -616,17 +616,25 @@ never makes the Latest pill show. from the background in 150ms ease-out, from the first frame that draws it; the one that leaves goes at once. The chevrons, the option highlight, the Send and Stop swap, the composer's height, a tool's state, the copy check and the footer's changes stay dry. -- **A permission** is a box on `Sidebar`, `RadiusMD`, `Space(3)` padding (see Boxes inside a screen): the tool, - its diff, and a `SizeSM` button per answer the provider offers, on one line at the right in the provider's - order (1, 2, 3), each with its digit's key cap leading it (`ButtonStyle.Keys`); the first one-time reject also - wears Esc's cap after its text (`ButtonStyle.AlsoKeys`, `chat_permit.go`). **Enter never answers it**, on the box or on an empty composer under it: an Enter meant +- **A permission** (`chat_permit.go`, `chat_permit_draw.go`) waits over the composer, where a question does and + for its reason: a box on `Sidebar`, `RadiusLG`, `Space(2)` over the composer, coming in as the question does, its + text starting where the conversation's and the composer's do (`chatComposerPadX`). Its head is a `ToneWait` dot + and who asks for what, "Claude Code asks to run a command", "to edit a file", "to use WebFetch", muted `TextXS`. + Under it is what is being approved, whole, never its first line: the command or target in mono `TextSM`, or an + edit's line over its diff per file (see An edit), with no chevron and no "Show more". Past `chatPermitShare` (0.4) + of the pane it scrolls, the bar in the box's padding, so the answers never leave the window. They are a `SizeSM` + button per answer the provider offers, on one line at the right in the provider's + order (1, 2, 3), each with its digit's key cap (`ButtonStyle.Keys`); the first one-time reject also + wears Esc's cap after its text (`ButtonStyle.AlsoKeys`). **Enter never answers it**, on the box or on an empty composer under it: an Enter meant for a message could land as the box comes. Digits 1..9 answer the nth option and Esc takes the first one-time reject (nothing when there is none). The filled button is the suggestion, wherever it falls in the provider's order: the first one-time allow, never an "always"; on an ask the provider marks default-no (Claude Code's `default_to_no`) it is the first one-time - reject, no digit answers and the buttons carry no key caps, as Claude Code's own prompt takes none + reject, no digit answers and the buttons carry no digit, as Claude Code's own prompt takes none (`docs/ceilings.md`). The keys go where the question card's do: to the box when it comes on an empty composer, to the composer while a message is being typed, and back to the composer on a click in it. - Answered, it shrinks to a muted line naming the answer. + Several waiting are answered in the order they came, so a new one never lands under the pointer; a question goes + before them. The call it is about stays out of the conversation while it waits. Allowed, the call's own line is + all that tells it; denied, a call's line with a muted `ban` glyph and "Denied" stands in the call's place. - **An edit** (`chat_edit.go`), a call that changed a file, is a line of its own out of the turn's fold, and so is each file a call with no diff of its own changed (a shell command's `sed`, a script), right after that call (`ChatToolCall.Files`, `fileRows`). Edit lines that follow one another with nothing between them are one diff --git a/native/cmd/lich-native/chat_items.go b/native/cmd/lich-native/chat_items.go index 762a38f4f..46caaa2f7 100644 --- a/native/cmd/lich-native/chat_items.go +++ b/native/cmd/lich-native/chat_items.go @@ -6,7 +6,6 @@ import ( "image" "image/color" "path" - "strconv" "strings" "time" @@ -102,7 +101,7 @@ func (u *window) chatRow(gtx C, th *ui.Theme, p *chatPane, sv sessionView, r cha if it.Permission == nil { return D{} } - return chatPermission(gtx, th, p, it) + return chatDenied(gtx, th, &it.Permission.Tool, sv.path) case api.ItemQuestion: if it.Question == nil { return D{} @@ -704,86 +703,6 @@ func splitDiff(diff string) (name string, added, deleted int, body []string) { return name, added, deleted, body } -// permitLabel is the provider's words for a permission's answer, or, for one -// it sends by kind alone (Claude Code, Codex), lich's. -func permitLabel(o api.ChatPermitOption) string { - if o.Label != "" { - return o.Label - } - switch o.Kind { - case api.PermitAllowOnce: - return i18n.T("chat.permit.allowOnce") - case api.PermitAllowAlways: - return i18n.T("chat.permit.allowAlways") - case api.PermitRejectOnce: - return i18n.T("chat.permit.rejectOnce") - } - return o.ID -} - -// chatPermission is the agent asking before a tool runs: a box with the -// tool, its diff and a button per answer the provider offers at the row's -// right, in the provider's order, each with the digit that takes it, the -// suggested one filled, and Esc in the one-time reject it takes. Answered, it -// is a muted line with the answer. -func chatPermission(gtx C, th *ui.Theme, p *chatPane, it backend.ChatItem) D { - perm := it.Permission - tool := strings.TrimSpace(perm.Tool.Name + " " + cleanLine(perm.Tool.Title)) - if perm.Chosen != "" { - choice := perm.Chosen - for _, o := range perm.Options { - if o.ID == perm.Chosen { - choice = permitLabel(o) - } - } - return th.Text(ui.TextXS, i18n.T("chat.view.answered", i18n.Args{"tool": tool, "choice": choice})).Muted().Layout(gtx) - } - box := th.On(th.Sidebar) - primary := permitSuggested(perm) - reject := permitOption(perm, api.PermitRejectOnce) - buttons := []layout.FlexChild{layout.Flexed(1, func(gtx C) D { return D{Size: gtx.Constraints.Min} })} - for i, o := range perm.Options { - if i > 0 { - buttons = append(buttons, ui.Gap(1.5)) - } - b := box.Button(p.answer(it.ID, o.ID), permitLabel(o)) - if o.ID == reject { - b.AlsoKeys = "Esc" - } - b.Size, b.Variant = ui.SizeSM, ui.VariantOutline - if i < permitDigits(perm) { - b.Keys = strconv.Itoa(i + 1) - } - if o.ID == primary { - b.Variant = ui.VariantDefault - } - buttons = append(buttons, layout.Rigid(b.Layout)) - } - return layout.Background{}.Layout(gtx, - func(gtx C) D { return ui.Fill(gtx, th.Sidebar, ui.RadiusMD) }, - func(gtx C) D { - return layout.UniformInset(ui.Space(3)).Layout(gtx, func(gtx C) D { - return layout.Flex{Axis: layout.Vertical}.Layout(gtx, - layout.Rigid(func(gtx C) D { - return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, - layout.Rigid(box.Text(ui.TextSM, perm.Tool.Name).Weight(font.Medium).Layout), - ui.Gap(2), - layout.Flexed(1, box.Text(ui.TextXS, cleanLine(perm.Tool.Title)).Mono().Muted().Layout), - ) - }), - layout.Rigid(func(gtx C) D { - if perm.Tool.Diff == "" { - return D{} - } - return layout.Inset{Top: ui.Space(2)}.Layout(gtx, func(gtx C) D { return chatDiff(gtx, box, perm.Tool.Diff) }) - }), - ui.VGap(2.5), - layout.Rigid(func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, buttons...) }), - ) - }) - }) -} - // chatVerbSep splits the catalog's list of verbs, which each language writes // at its own length. const chatVerbSep = "|" diff --git a/native/cmd/lich-native/chat_motion_test.go b/native/cmd/lich-native/chat_motion_test.go index 0f0f72ef0..cd47ec4e0 100644 --- a/native/cmd/lich-native/chat_motion_test.go +++ b/native/cmd/lich-native/chat_motion_test.go @@ -103,8 +103,8 @@ func TestAChatRowEntersByHeightAndOpacityWithoutScale(t *testing.T) { // The live line leaving for a permission plays the entry backwards: it keeps // its place and size, its row shrinking and its verb dimming. The live line -// keeps its slot over the permission while it goes, so the permission's -// distance from the message above is the live row's height. +// keeps its slot under the message while it goes, so the distance from the +// message to the permission's box, over the composer, is the live row's height. func TestAChatRowLeavesByHeightAndOpacityWithoutScale(t *testing.T) { items := []backend.ChatItem{{ID: "u1", Kind: api.ItemUser, Turn: 1, At: novDay(18, 17, 59), Text: "go"}} u, r := lifeFrames(t, items, true) @@ -122,7 +122,7 @@ func TestAChatRowLeavesByHeightAndOpacityWithoutScale(t *testing.T) { Options: []api.ChatPermitOption{{ID: "yes", Label: "Allow", Kind: api.PermitAllowOnce}}, }}}) r.frame() - gap := func() int { return labelTop(t, r, "Edit") - labelTop(t, r, "go") } + gap := func() int { return int(r.at(t, "claude asks to edit a file").Y - r.at(t, "go").Y) } r.play(1) start := gap() r.now = r.now.Add(into - frameStep) diff --git a/native/cmd/lich-native/chat_permit.go b/native/cmd/lich-native/chat_permit.go index 7be25bfc0..9dd718469 100644 --- a/native/cmd/lich-native/chat_permit.go +++ b/native/cmd/lich-native/chat_permit.go @@ -5,15 +5,19 @@ import ( "gioui.org/io/event" "gioui.org/io/key" + "gioui.org/widget" "github.com/lichdotdev/lich/api" "github.com/lichdotdev/lich/native/backend" ) // chatPermit is the keys' target while a permission waits; shown is the last -// one they were handed to. +// one they were handed to, scrolled the one list holds the scroll of. type chatPermit struct { - shown string + shown string + scrolled string + list widget.List + motion panelMotion } // focusPermit hands the keys to a waiting permission when it comes, unless a diff --git a/native/cmd/lich-native/chat_permit_draw.go b/native/cmd/lich-native/chat_permit_draw.go new file mode 100644 index 000000000..b3c7037c7 --- /dev/null +++ b/native/cmd/lich-native/chat_permit_draw.go @@ -0,0 +1,220 @@ +package main + +import ( + "image" + "strconv" + "strings" + + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + + "github.com/lichdotdev/lich/api" + "github.com/lichdotdev/lich/native/backend" + "github.com/lichdotdev/lich/native/i18n" + "github.com/lichdotdev/lich/native/ui" + "github.com/lichdotdev/lich/native/ui/icons" +) + +// chatPermitShare is how much of the pane's height what a permission asks +// about may take before it scrolls, so its answers stay in view. +const chatPermitShare = 0.4 + +// codexPermissionsTool names Codex's request to reach past its sandbox, which +// is no tool (internal/chat/codex_question.go). +const codexPermissionsTool = "request_permissions" + +// chatPermitPad is the box's inner room, the composer's, so its text starts +// where the conversation's and the composer's do. +var chatPermitPad = chatComposerPadX + +// chatPermitBar is how far into the box's padding its scrollbar stands. +var chatPermitBar = ui.Space(3) + +var icPermitDenied = icons.Lucide("ban") + +// chatPermitting is the waiting permission's box, over the composer, a gap +// under it; nothing while none waits or a question does. +func (u *window) chatPermitting(gtx C, th *ui.Theme, p *chatPane, sv sessionView) D { + items := u.model.chat.of(sv.ID) + it := permissionWaiting(items) + if it == nil || questionWaiting(items) != nil { + p.permit.motion.track(gtx.Now, false, "") + return D{} + } + p.permit.motion.track(gtx.Now, true, "") + m := op.Record(gtx.Ops) + d := layout.Inset{Bottom: ui.Space(2)}.Layout(gtx, func(gtx C) D { return u.chatPermission(gtx, th, p, sv, *it) }) + call := m.Stop() + defer p.permit.motion.push(gtx, d.Size, 0)() + call.Add(gtx.Ops) + return d +} + +// chatPermission is the box: who asks for what, what it would run or change, +// whole, and the answers under it. +func (u *window) chatPermission(gtx C, th *ui.Theme, p *chatPane, sv sessionView, it backend.ChatItem) D { + box := th.On(th.Sidebar) + files := permitFiles(&it.Permission.Tool) + return layout.Background{}.Layout(gtx, + func(gtx C) D { return ui.Fill(gtx, th.Sidebar, ui.RadiusLG) }, + func(gtx C) D { + gtx.Constraints.Min = image.Pt(gtx.Constraints.Max.X, 0) + return layout.Inset{Top: ui.Space(3), Bottom: ui.Space(3), Left: chatPermitPad, Right: chatPermitPad}.Layout(gtx, func(gtx C) D { + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(func(gtx C) D { return ui.StatusDot(gtx, box.ToneWait) }), + ui.Gap(1), + layout.Flexed(1, box.Text(ui.TextXS, permitAsks(u.providerName(sv), &it.Permission.Tool, len(files))).Muted().Layout), + ) + }), + ui.VGap(2), + layout.Rigid(func(gtx C) D { return u.chatPermitBody(gtx, box, p, sv, it, files) }), + ui.VGap(3), + layout.Rigid(func(gtx C) D { return chatPermitAnswers(gtx, box, p, it) }), + ) + }) + }) +} + +// chatPermitBody is the files' diffs, or the command or target as it came, +// every line of it, behind a scroll past chatPermitShare of the pane. +func (u *window) chatPermitBody(gtx C, th *ui.Theme, p *chatPane, sv sessionView, it backend.ChatItem, files []string) D { + if p.permit.scrolled != it.ID { + p.permit.scrolled = it.ID + p.permit.list.ScrollTo(0) + } + gtx.Constraints.Max.Y = min(gtx.Constraints.Max.Y, int(float32(p.slashRoom)*chatPermitShare)) + gtx.Constraints.Min.Y = 0 + // The bar stands in the box's padding, clear of the counts at the right. + gtx.Constraints.Max.X += gtx.Dp(chatPermitBar) + p.permit.list.Axis = layout.Vertical + return th.ThinScrollArea(&p.permit.list).Layout(gtx, max(len(files), 1), func(gtx C, i int) D { + return layout.Inset{Right: chatPermitBar}.Layout(gtx, func(gtx C) D { + if len(files) == 0 { + return th.Text(ui.TextSM, expandTabs(strings.TrimSpace(it.Permission.Tool.Title))).Mono().Wrapped().Layout(gtx) + } + return u.chatPermitFile(gtx, th, p, sv, p.fold("permit:"+it.ID+"#"+strconv.Itoa(i)), files[i]) + }) + }) +} + +// chatPermitFile is one file of the ask, an edit's line over its whole diff. +func (u *window) chatPermitFile(gtx C, th *ui.Theme, p *chatPane, sv sessionView, f *chatFold, diff string) D { + if f.diff == nil { + f.diff = &chatEditDiff{whole: true} + } + _, added, deleted, body := splitDiff(diff) + t := &backend.ChatToolCall{Diff: diff} + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, + layout.Rigid(func(gtx C) D { + return layout.Inset{Top: chatEditPadY, Bottom: chatEditPadY}.Layout(gtx, func(gtx C) D { + return chatEditLine(gtx, th, f, t, editPath(t, sv.path), false, added, deleted, false) + }) + }), + layout.Rigid(func(gtx C) D { + if len(body) == 0 { + return D{} + } + return u.chatEditDiff(gtx, th, p, f, diff, body) + }), + ) +} + +// chatPermitAnswers are a button per answer the provider offers at the row's +// right, in the provider's order, each with the digit that takes it, the +// suggested one filled, and Esc in the one-time reject it takes. +func chatPermitAnswers(gtx C, th *ui.Theme, p *chatPane, it backend.ChatItem) D { + perm := it.Permission + primary := permitSuggested(perm) + reject := permitOption(perm, api.PermitRejectOnce) + buttons := []layout.FlexChild{layout.Flexed(1, func(gtx C) D { return D{Size: gtx.Constraints.Min} })} + for i, o := range perm.Options { + if i > 0 { + buttons = append(buttons, ui.Gap(1.5)) + } + b := th.Button(p.answer(it.ID, o.ID), permitLabel(o)) + if o.ID == reject { + b.AlsoKeys = "Esc" + } + b.Size, b.Variant = ui.SizeSM, ui.VariantOutline + if i < permitDigits(perm) { + b.Keys = strconv.Itoa(i + 1) + } + if o.ID == primary { + b.Variant = ui.VariantDefault + } + buttons = append(buttons, layout.Rigid(b.Layout)) + } + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, buttons...) +} + +// permitLabel is the provider's words for a permission's answer, or, for one +// it sends by kind alone (Claude Code, Codex), lich's. +func permitLabel(o api.ChatPermitOption) string { + if o.Label != "" { + return o.Label + } + switch o.Kind { + case api.PermitAllowOnce: + return i18n.T("chat.permit.allowOnce") + case api.PermitAllowAlways: + return i18n.T("chat.permit.allowAlways") + case api.PermitRejectOnce: + return i18n.T("chat.permit.rejectOnce") + } + return o.ID +} + +// permitAsks is the box's head: provider and what it asks to do with t, which +// changes files files. +func permitAsks(provider string, t *backend.ChatToolCall, files int) string { + switch { + case files > 0 || kindOf(t.Name) == callEdited: + return i18n.T("chat.permit.edit", i18n.Args{"provider": provider, "count": max(files, 1)}) + case kindOf(t.Name) == callRan: + return i18n.T("chat.permit.run", i18n.Args{"provider": provider}) + case t.Name == codexPermissionsTool: + return i18n.T("chat.permit.more", i18n.Args{"provider": provider}) + } + return i18n.T("chat.permit.use", i18n.Args{"provider": provider, "tool": t.Name}) +} + +// permitFiles is t's diff cut where each file starts: Codex asks about all the +// files of a patch at once. +func permitFiles(t *backend.ChatToolCall) []string { + if t.Diff == "" { + return nil + } + const head = "diff --git " + parts := strings.Split("\n"+gitPatch(t.Diff), "\n"+head) + files := make([]string, 0, len(parts)) + for _, part := range parts[1:] { + files = append(files, head+strings.TrimSuffix(part, "\n")+"\n") + } + if len(files) == 0 { + return []string{t.Diff} + } + return files +} + +// chatDenied is a call the person did not allow, in a call's line. +func chatDenied(gtx C, th *ui.Theme, t *backend.ChatToolCall, checkout string) D { + target := cleanLine(t.Title) + if t.Diff != "" { + target = editPath(t, checkout) + } + if target == "" { + target = t.Name + } + h := gtx.Dp(chatToolRow) + gtx.Constraints.Min.Y, gtx.Constraints.Max.Y = h, h + return layout.Flex{Alignment: layout.Middle}.Layout(gtx, + layout.Rigid(func(gtx C) D { return icPermitDenied.Layout(gtx, unit.Dp(14), th.MutedForeground) }), + ui.Gap(2), + layout.Rigid(th.Text(ui.TextXS, i18n.T("chat.permit.denied")).Muted().Layout), + ui.Gap(2), + layout.Flexed(1, th.Text(ui.TextXS, target).Mono().Layout), + ) +} diff --git a/native/cmd/lich-native/chat_permit_draw_test.go b/native/cmd/lich-native/chat_permit_draw_test.go new file mode 100644 index 000000000..02c9b4e05 --- /dev/null +++ b/native/cmd/lich-native/chat_permit_draw_test.go @@ -0,0 +1,151 @@ +package main + +import ( + "strings" + "testing" + + "github.com/lichdotdev/godemirror" + "github.com/lichdotdev/lich/api" + "github.com/lichdotdev/lich/native/backend" +) + +const permitTwoFiles = "--- a/pkg/a.go\n+++ b/pkg/a.go\n@@ -1 +1 @@\n-a\n+b\n--- a/pkg/b.go\n+++ b/pkg/b.go\n@@ -1 +1,2 @@\n c\n+d\n" + +// askedCall is a turn whose call t waits on, or was answered by, chosen. +func askedCall(t backend.ChatToolCall, options []api.ChatPermitOption, chosen string) []backend.ChatItem { + asked := t + asked.State = api.ToolPending + return []backend.ChatItem{ + {ID: "u1", Kind: api.ItemUser, Turn: 1, Text: "go"}, + {ID: "t1", Kind: api.ItemTool, Turn: 1, Tool: &t}, + {ID: "p1", Kind: api.ItemPermission, Turn: 1, Permission: &backend.ChatPermission{Tool: asked, Options: options, Chosen: chosen}}, + } +} + +// The conversation says a call once: nothing while it waits, the call once +// allowed, and one Denied line in its place once rejected, on every chat path. +func TestAnAskedCallIsSaidOnce(t *testing.T) { + for name, s := range permitShapes { + for _, c := range []struct{ what, chosen, state, want string }{ + {"waiting", "", api.ToolPending, ""}, + {"allowed", s.allow, api.ToolDone, "t1"}, + {"denied", s.reject, api.ToolFailed, "p1"}, + } { + t.Run(name+"/"+c.what, func(t *testing.T) { + items := askedCall(backend.ChatToolCall{Name: "Bash", Title: "gopls version", State: c.state}, s.options, c.chosen) + var got []string + for _, it := range withoutAsks(items)[1:] { + got = append(got, it.ID) + } + if strings.Join(got, ",") != c.want { + t.Errorf("the conversation holds %v, want %q", got, c.want) + } + }) + } + } + always := askedCall(backend.ChatToolCall{Name: "Bash", Title: "x", State: api.ToolFailed}, permitShapes["acp"].options, "never") + if got := withoutAsks(always); len(got) != 2 || got[1].ID != "p1" { + t.Errorf("a reject_always is not drawn as denied: %v", got) + } +} + +// A permission the provider withdrew, or a stop dismissed, waits on nobody: its +// box leaves, and the call tells how it ended. +func TestADismissedPermissionLeaves(t *testing.T) { + items := askedCall(backend.ChatToolCall{Name: "Bash", Title: "gopls version", State: api.ToolFailed}, permitShapes["claude"].options, "") + items[2].Permission.Tool.State = api.ToolFailed + if permissionWaiting(items) != nil { + t.Error("a dismissed permission still waits") + } + if got := withoutAsks(items); len(got) != 2 || got[1].ID != "t1" { + t.Errorf("the conversation holds %v, want the message and the call", got) + } +} + +// Several waiting are answered in the order they came: a new one never takes +// the place of the one under the pointer. +func TestTheFirstPermissionStaysUntilAnswered(t *testing.T) { + u, r, _ := permitFrames(t, backend.ChatPermission{Options: permitShapes["claude"].options}) + second := backend.ChatPermission{Tool: backend.ChatToolCall{Name: "Bash", Title: "git push", State: api.ToolPending}, Options: permitShapes["claude"].options} + u.model.chat.apply(api.ChatItemUpdate{SessionID: "s1", Item: backend.ChatItem{ID: "p2", Kind: api.ItemPermission, Turn: 1, Permission: &second}}) + r.settle(t) + if r.shows("git push") || !r.shows("src/total.ts") { + t.Fatalf("the second permission took the first's place:\n%s", r.drawn()) + } + first := *permissionWaiting(u.model.chat.of("s1")) + answered := *first.Permission + answered.Chosen = api.PermitAllowOnce + first.Permission = &answered + u.model.chat.apply(api.ChatItemUpdate{SessionID: "s1", Item: first}) + r.settle(t) + if !r.shows("git push") { + t.Errorf("the second permission did not come:\n%s", r.drawn()) + } +} + +// The box says who asks for what, each provider's tool names alike. +func TestWhatAPermissionAsks(t *testing.T) { + for _, c := range []struct { + tool backend.ChatToolCall + want string + }{ + {backend.ChatToolCall{Name: "Bash"}, "Agent asks to run a command"}, + {backend.ChatToolCall{Name: "shell"}, "Agent asks to run a command"}, + {backend.ChatToolCall{Name: "execute"}, "Agent asks to run a command"}, + {backend.ChatToolCall{Name: "edit"}, "Agent asks to edit a file"}, + {backend.ChatToolCall{Name: "apply_patch", Diff: permitTwoFiles}, "Agent asks to edit 2 files"}, + {backend.ChatToolCall{Name: "WebFetch"}, "Agent asks to use WebFetch"}, + {backend.ChatToolCall{Name: codexPermissionsTool}, "Agent asks for more access"}, + } { + if got := permitAsks("Agent", &c.tool, len(permitFiles(&c.tool))); got != c.want { + t.Errorf("%s: %q, want %q", c.tool.Name, got, c.want) + } + } +} + +// What is approved is read whole: each line of a command, each file of a patch, +// and the answers stay in view under a long one. +func TestAPermissionShowsAllItAsksAbout(t *testing.T) { + long := "--- /dev/null\n+++ b/long.go\n@@ -0,0 +1,300 @@\n" + strings.Repeat("+line\n", 300) + for _, c := range []struct { + name string + tool backend.ChatToolCall + shows []string + }{ + {"command", backend.ChatToolCall{Name: "Bash", Title: "go vet ./... &&\ngit push"}, []string{"go vet ./... &&\ngit push"}}, + {"patch", backend.ChatToolCall{Name: "apply_patch", Title: "pkg/a.go, pkg/b.go", Diff: permitTwoFiles}, []string{"a.go", "b.go"}}, + {"long", backend.ChatToolCall{Name: "Write", Title: "long.go", Diff: long}, []string{"long.go"}}, + {"long-command", backend.ChatToolCall{Name: "Bash", Title: strings.Repeat("echo line\n", 200)}, nil}, + } { + t.Run(c.name, func(t *testing.T) { + u, r, _ := chatFrames(t, api.ViewChat) + r.theme.Code = godemirror.DarkTheme + c.tool.State = api.ToolPending + u.model.chat.history("s1", askedCall(c.tool, permitShapes["claude"].options, "")) + u.model.chat.turn(api.ChatTurn{SessionID: "s1", Running: true}) + r.settle(t) + writeShot(t, r, "chat-permit-"+c.name+".png") + if !r.showsAll(append(c.shows, "Allow", "Always allow", "Deny")...) { + t.Errorf("not all of it shows:\n%s", r.drawn()) + } + if top := r.at(t, "Deny").Y; top < 0 || int(top) > r.size.Y { + t.Errorf("Deny is out of the window, at %v", top) + } + }) + } +} + +// A denied call reads as a call's line, its file by its path in the checkout. +func TestADeniedCallSaysSo(t *testing.T) { + for _, tool := range []backend.ChatToolCall{{Name: "Bash", Title: "gopls version"}, {Name: "Edit", Title: "pkg/a.go", Diff: permitTwoFiles}} { + u, r, _ := chatFrames(t, api.ViewChat) + tool.State = api.ToolFailed + u.model.chat.history("s1", askedCall(tool, permitShapes["claude"].options, api.PermitRejectOnce)) + u.model.chat.turn(api.ChatTurn{SessionID: "s1", Running: true}) + r.frames(30) // the live line never settles + writeShot(t, r, "chat-permit-denied-"+tool.Name+".png") + if !r.showsAll("Denied", tool.Title) || r.shows("Allow") { + t.Errorf("no Denied line:\n%s", r.drawn()) + } + } +} diff --git a/native/cmd/lich-native/chat_rows.go b/native/cmd/lich-native/chat_rows.go index 8ee1d3780..6064a1bf3 100644 --- a/native/cmd/lich-native/chat_rows.go +++ b/native/cmd/lich-native/chat_rows.go @@ -108,6 +108,13 @@ func chatRowsAfter(turnDay time.Time, items []backend.ChatItem, kind string, run if slices.ContainsFunc(items, isPlan) { items = slices.DeleteFunc(slices.Clone(items), isPlan) } + // The item being produced is the conversation's last, while it runs. + liveID := "" + if running && len(items) > 0 { + liveID = items[len(items)-1].ID + } + waiting := permissionWaiting(items) != nil || questionWaiting(items) != nil + items = withoutAsks(items) spans := map[int]*chatTurnSpan{} shell := map[string]bool{} runsShell := slices.Contains(chatRunShellKinds, kind) @@ -148,11 +155,6 @@ func chatRowsAfter(turnDay time.Time, items []backend.ChatItem, kind string, run } rows := make([]chatRow, 0, len(items)+2) folded := map[string]bool{} - // The item being produced is the conversation's last, while it runs. - liveID := "" - if running && len(items) > 0 { - liveID = items[len(items)-1].ID - } for _, it := range items { if began := spans[it.Turn].began; it.Kind == api.ItemUser && began > 0 { day := time.UnixMilli(began).In(now.Location()) @@ -205,7 +207,7 @@ func chatRowsAfter(turnDay time.Time, items []backend.ChatItem, kind string, run rows = append(rows, work) rows = append(rows, fileRows(it)...) } - if running && permissionWaiting(items) == nil && questionWaiting(items) == nil { + if running && !waiting { live := chatRow{kind: chatRowLive, turn: last, movable: movable(items), compacting: compactRunning(items)} if sp := spans[last]; sp != nil && sp.start > 0 && !now.IsZero() { live.since = sp.start @@ -340,17 +342,72 @@ func sameDay(a, b time.Time) bool { return ay == by && am == bm && ad == bd } -// permissionWaiting is the permission item still unanswered, the last one, -// nil for none. +// permissionWaiting is the first permission item still unanswered, nil for +// none: one that comes while another waits never takes its place under the +// pointer. One the provider withdrew, or a stop dismissed, waits no more. func permissionWaiting(items []backend.ChatItem) *backend.ChatItem { - for i := len(items) - 1; i >= 0; i-- { - if it := &items[i]; it.Kind == api.ItemPermission && it.Permission != nil && it.Permission.Chosen == "" { + for i := range items { + if it := &items[i]; it.Kind == api.ItemPermission && permitWaits(it.Permission) { return it } } return nil } +func permitWaits(p *backend.ChatPermission) bool { + return p != nil && p.Chosen == "" && p.Tool.State != api.ToolFailed +} + +// permitDenied is whether the person answered p with a reject, once or always. +func permitDenied(p *backend.ChatPermission) bool { + return p != nil && p.Chosen != "" && slices.ContainsFunc(p.Options, func(o api.ChatPermitOption) bool { + return o.ID == p.Chosen && strings.HasPrefix(o.Kind, permitRejects) + }) +} + +// permitRejects starts the kinds of option that reject: ACP has reject_once +// and reject_always. +const permitRejects = "reject_" + +// withoutAsks is items as the conversation draws its permissions: only a denied +// one, in place of the call it was about, which never ran. A waiting one and +// its call are in the box over the composer, and an allowed one's call says it. +func withoutAsks(items []backend.ChatItem) []backend.ChatItem { + hidden := map[int]bool{} + for i, it := range items { + if it.Kind != api.ItemPermission { + continue + } + denied := permitDenied(it.Permission) + hidden[i] = !denied + if !denied && !permitWaits(it.Permission) { + continue + } + for j := i - 1; j >= 0 && items[j].Turn == it.Turn; j-- { + if !hidden[j] && asksAbout(it.Permission, items[j]) { + hidden[j] = true + break + } + } + } + if len(hidden) == 0 { + return items + } + out := make([]backend.ChatItem, 0, len(items)) + for i, it := range items { + if !hidden[i] { + out = append(out, it) + } + } + return out +} + +// asksAbout is whether p asks about the call it: the ask carries the call's +// name and target, not its id, and a call that went well was another one. +func asksAbout(p *backend.ChatPermission, it backend.ChatItem) bool { + return it.Tool != nil && it.Tool.State != api.ToolDone && it.Tool.Name == p.Tool.Name && it.Tool.Title == p.Tool.Title +} + // permitOption is p's option of the first of kinds it offers, "" for none. func permitOption(p *backend.ChatPermission, kinds ...string) string { for _, k := range kinds { diff --git a/native/cmd/lich-native/chat_store_test.go b/native/cmd/lich-native/chat_store_test.go index 35162d631..3d47f8986 100644 --- a/native/cmd/lich-native/chat_store_test.go +++ b/native/cmd/lich-native/chat_store_test.go @@ -183,7 +183,10 @@ func TestChatRowsLiveRowGivesWayToAWaitingPermission(t *testing.T) { perm := func(chosen string) backend.ChatItem { return backend.ChatItem{ID: "p", Kind: api.ItemPermission, Permission: &backend.ChatPermission{Chosen: chosen}} } + // The message opens the turn: a permission waiting or allowed draws no row + // of its own (contract changed: its box stands over the composer). last := func(items []backend.ChatItem, running bool) chatRowKind { + items = append([]backend.ChatItem{{ID: "u", Kind: api.ItemUser}}, items...) rows := chatRows(items, claudeKind, running, time.Time{}) return rows[len(rows)-1].kind } diff --git a/native/cmd/lich-native/chat_turn_fold_test.go b/native/cmd/lich-native/chat_turn_fold_test.go index 2c13d2ef0..b5168c944 100644 --- a/native/cmd/lich-native/chat_turn_fold_test.go +++ b/native/cmd/lich-native/chat_turn_fold_test.go @@ -116,12 +116,13 @@ func TestAFinishedTurnFoldsToItsAnswerAndItsFiles(t *testing.T) { } } -// A waiting permission or question holds its turn open. +// A waiting permission or question holds its turn open (contract changed: the +// permission's box stands over the composer, not in a row). func TestATurnThatWaitsOnThePersonDoesNotFold(t *testing.T) { ask := turnItem(1, "p", api.ItemPermission, 12) ask.Permission = &backend.ChatPermission{} items := []backend.ChatItem{turnItem(1, "u", api.ItemUser, 10), turnCall(1, "k", api.ToolDone, 11), ask} - if got, want := drawRows(endedRows(items, false, "")), []string{"u", "work:k", "p"}; !slices.Equal(got, want) { + if got, want := drawRows(endedRows(items, false, "")), []string{"u", "work:k"}; !slices.Equal(got, want) { t.Errorf("got %q, want %q", got, want) } } diff --git a/native/cmd/lich-native/chat_view.go b/native/cmd/lich-native/chat_view.go index 0198d6da9..0885096c2 100644 --- a/native/cmd/lich-native/chat_view.go +++ b/native/cmd/lich-native/chat_view.go @@ -756,6 +756,7 @@ func (u *window) chatComposer(gtx C, th *ui.Theme, p *chatPane, sv sessionView, } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { return u.chatAsking(gtx, th, p, sv) }), + layout.Rigid(func(gtx C) D { return u.chatPermitting(gtx, th, p, sv) }), layout.Rigid(func(gtx C) D { return u.chatWorkflow(gtx, th, p, sv.ID) }), layout.Rigid(func(gtx C) D { return u.chatQueue(gtx, th, p, sv.ID) }), layout.Rigid(func(gtx C) D { diff --git a/native/i18n/locales/en/chat.json b/native/i18n/locales/en/chat.json index 520bde6f5..7ba59cb40 100644 --- a/native/i18n/locales/en/chat.json +++ b/native/i18n/locales/en/chat.json @@ -48,7 +48,6 @@ "other": "Show {count} more lines" }, "shellLess": "Show less", - "answered": "{tool} · {choice}", "verbs": "Conjuring|Summoning|Channeling|Brewing|Scrying|Inscribing|Weaving|Raising", "thinking": "Thinking", "toolCalls": { @@ -168,7 +167,15 @@ "permit": { "allowOnce": "Allow", "allowAlways": "Always allow", - "rejectOnce": "Deny" + "rejectOnce": "Deny", + "run": "{provider} asks to run a command", + "edit": { + "one": "{provider} asks to edit a file", + "other": "{provider} asks to edit {count} files" + }, + "use": "{provider} asks to use {tool}", + "more": "{provider} asks for more access", + "denied": "Denied" }, "choice": { "manual": "Manual", diff --git a/native/i18n/locales/es/chat.json b/native/i18n/locales/es/chat.json index 05d66d77d..14af53356 100644 --- a/native/i18n/locales/es/chat.json +++ b/native/i18n/locales/es/chat.json @@ -48,7 +48,6 @@ "other": "Mostrar {count} líneas más" }, "shellLess": "Mostrar menos", - "answered": "{tool} · {choice}", "verbs": "Conjurando|Invocando|Canalizando|Destilando|Vislumbrando|Inscribiendo|Tejiendo|Alzando", "thinking": "Pensando", "toolCalls": { @@ -168,7 +167,15 @@ "permit": { "allowOnce": "Permitir", "allowAlways": "Permitir siempre", - "rejectOnce": "Denegar" + "rejectOnce": "Denegar", + "run": "{provider} pide ejecutar un comando", + "edit": { + "one": "{provider} pide editar un archivo", + "other": "{provider} pide editar {count} archivos" + }, + "use": "{provider} pide usar {tool}", + "more": "{provider} pide más acceso", + "denied": "Denegado" }, "choice": { "manual": "Manual", diff --git a/native/i18n/locales/ja/chat.json b/native/i18n/locales/ja/chat.json index 67691d3af..066716491 100644 --- a/native/i18n/locales/ja/chat.json +++ b/native/i18n/locales/ja/chat.json @@ -41,7 +41,6 @@ "other": "さらに {count} 行を表示" }, "shellLess": "折りたたむ", - "answered": "{tool} · {choice}", "verbs": "詠唱中|召喚中|魔力を注ぎ中|調合中|占い中|刻印中|紡ぎ中|蘇らせ中", "thinking": "思考中", "toolCalls": { @@ -150,7 +149,14 @@ "permit": { "allowOnce": "許可", "allowAlways": "常に許可", - "rejectOnce": "拒否" + "rejectOnce": "拒否", + "run": "{provider} がコマンドの実行許可を求めています", + "edit": { + "other": "{provider} が {count} 個のファイルの編集許可を求めています" + }, + "use": "{provider} が {tool} の使用許可を求めています", + "more": "{provider} が追加のアクセス権を求めています", + "denied": "拒否" }, "choice": { "manual": "手動", diff --git a/native/i18n/locales/ko/chat.json b/native/i18n/locales/ko/chat.json index f350c5150..f757f0be9 100644 --- a/native/i18n/locales/ko/chat.json +++ b/native/i18n/locales/ko/chat.json @@ -41,7 +41,6 @@ "other": "{count}줄 더 보기" }, "shellLess": "접기", - "answered": "{tool} · {choice}", "verbs": "주문 외우는 중|소환하는 중|마력을 모으는 중|달이는 중|들여다보는 중|새기는 중|엮는 중|일으키는 중", "thinking": "생각 중", "toolCalls": { @@ -150,7 +149,14 @@ "permit": { "allowOnce": "허용", "allowAlways": "항상 허용", - "rejectOnce": "거부" + "rejectOnce": "거부", + "run": "{provider}에서 명령 실행 권한을 요청합니다", + "edit": { + "other": "{provider}에서 파일 {count}개의 편집 권한을 요청합니다" + }, + "use": "{provider}에서 {tool} 사용 권한을 요청합니다", + "more": "{provider}에서 추가 접근 권한을 요청합니다", + "denied": "거부됨" }, "choice": { "manual": "수동", diff --git a/native/i18n/locales/pt-br/chat.json b/native/i18n/locales/pt-br/chat.json index d07c072b5..b32ce3dc8 100644 --- a/native/i18n/locales/pt-br/chat.json +++ b/native/i18n/locales/pt-br/chat.json @@ -48,7 +48,6 @@ "other": "Mostrar mais {count} linhas" }, "shellLess": "Mostrar menos", - "answered": "{tool} · {choice}", "verbs": "Conjurando|Invocando|Canalizando|Destilando|Vislumbrando|Inscrevendo|Tecendo|Erguendo", "thinking": "Pensando", "toolCalls": { @@ -168,7 +167,15 @@ "permit": { "allowOnce": "Permitir", "allowAlways": "Sempre permitir", - "rejectOnce": "Negar" + "rejectOnce": "Negar", + "run": "{provider} pede para executar um comando", + "edit": { + "one": "{provider} pede para editar um arquivo", + "other": "{provider} pede para editar {count} arquivos" + }, + "use": "{provider} pede para usar {tool}", + "more": "{provider} pede mais acesso", + "denied": "Negado" }, "choice": { "manual": "Manual", diff --git a/native/i18n/locales/ru/chat.json b/native/i18n/locales/ru/chat.json index 3e789984e..c4354cc8e 100644 --- a/native/i18n/locales/ru/chat.json +++ b/native/i18n/locales/ru/chat.json @@ -62,7 +62,6 @@ "other": "Показать ещё {count} строки" }, "shellLess": "Свернуть", - "answered": "{tool} · {choice}", "verbs": "Колдует|Призывает|Направляет силу|Варит зелье|Гадает|Чертит руны|Плетёт чары|Воскрешает", "thinking": "Думает", "toolCalls": { @@ -204,7 +203,17 @@ "permit": { "allowOnce": "Разрешить", "allowAlways": "Всегда разрешать", - "rejectOnce": "Запретить" + "rejectOnce": "Запретить", + "run": "{provider} просит выполнить команду", + "edit": { + "one": "{provider} просит изменить {count} файл", + "few": "{provider} просит изменить {count} файла", + "many": "{provider} просит изменить {count} файлов", + "other": "{provider} просит изменить {count} файла" + }, + "use": "{provider} просит использовать {tool}", + "more": "{provider} просит расширить доступ", + "denied": "Запрещено" }, "choice": { "manual": "Ручной", diff --git a/native/i18n/locales/zh-cn/chat.json b/native/i18n/locales/zh-cn/chat.json index 6dd1ec520..07d56faee 100644 --- a/native/i18n/locales/zh-cn/chat.json +++ b/native/i18n/locales/zh-cn/chat.json @@ -41,7 +41,6 @@ "other": "再显示 {count} 行" }, "shellLess": "收起", - "answered": "{tool} · {choice}", "verbs": "施法中|召唤中|引导魔力中|熬制中|占卜中|铭刻中|编织中|唤醒中", "thinking": "思考中", "toolCalls": { @@ -150,7 +149,14 @@ "permit": { "allowOnce": "允许", "allowAlways": "始终允许", - "rejectOnce": "拒绝" + "rejectOnce": "拒绝", + "run": "{provider} 请求运行命令", + "edit": { + "other": "{provider} 请求编辑 {count} 个文件" + }, + "use": "{provider} 请求使用 {tool}", + "more": "{provider} 请求更多访问权限", + "denied": "已拒绝" }, "choice": { "manual": "手动",