diff --git a/Docs/DESIGN.md b/Docs/DESIGN.md index 7d6a9c72..8265bd28 100644 --- a/Docs/DESIGN.md +++ b/Docs/DESIGN.md @@ -23,6 +23,7 @@ folder where a subject needs several. A file here is binding, not background. | [design/services/create-and-merge.md](design/services/create-and-merge.md) | Create Pull Request and its push, merging from the page, the merge form, Merge When Ready, Cancel Auto-Merge. | | [design/services/marks-and-pages.md](design/services/marks-and-pages.md) | Row marks and colours, the panel's pull request and CI pages, checks, merge verdicts, failed run reports. | | [design/services/merge-path.md](design/services/merge-path.md) | The pull request page's steps toward a merge, their order, the checks under one step, hints, the merge at the end, settled pull requests, its text colour. | +| [design/services/send-feedback.md](design/services/send-feedback.md) | Sending failing checks, review threads and failed CI jobs from the PR and CI pages: the shared Send foot and its `Handoff*` names, checkboxes and the step's mixed one, the sent bubble, item keys, what Send writes, log reads at Send, the thread read, Run output. | | [design/services/debug-stand-in.md](design/services/debug-stand-in.md) | Debug services stand-in, its JSON, how it waits on reads. | | [design/files/panel.md](design/files/panel.md) | The Files panel's place, what it lists, ignored files and their pace, the index read, caps, the pages and their saved choice, the filter, its switch and width, fitting columns, the badge's click, Copy Path, background reads, listing rebuilds, submodules, PR and CI pages. | | [design/files/file-tabs.md](design/files/file-tabs.md) | The open rule, file tabs as their own type in one order, saved tabs and their scroll, deleted and renamed files, the diff against HEAD and staged marks, re-reads and their pace, hidden tabs, the 1 MiB cap, encodings, TextKit 2 rows, fonts, tints and word diffs, the gutter, copy, find, the Changes rotor, Split, the bar, change arrows and the boxed change. | diff --git a/Docs/design/agents/command-line.md b/Docs/design/agents/command-line.md index f5de2b59..e1782dc2 100644 --- a/Docs/design/agents/command-line.md +++ b/Docs/design/agents/command-line.md @@ -75,8 +75,9 @@ The command line's requests on the reports' socket. Newest at the bottom. stops the pre-create hook or git as the sheet's Cancel does. The helper shuts its writing half after the request, so EOF says nothing; the reply polls for POLLHUP, which macOS sets only once both halves are shut, every 250 ms until - it is sent. A cancelled task stops nothing else: nothing else a request awaits - checks for it. + it is sent. `pr send` checks once its reads end, so a Ctrl-C while its logs + read pastes nothing into the agent. A cancelled task stops nothing else: the + reads themselves run on, and nothing else a request awaits checks for it. - **The app answers in data and the helper words it** (translation.md): ids and JSON on success, a typed refusal otherwise. - **Whatever a command prints is JSON**, indented and sorted as the app's @@ -232,6 +233,13 @@ The command line's requests on the reports' socket. Newest at the bottom. - **`tabs open-all-changes` opens or turns to a worktree's All changes tab**, and `tabs list` reports it as kind `all-changes`; `tabs step` and `tabs find` reach it as a file tab (files/all-changes-tab.md). +- **`pr send` and `ci send` take `--worktree` as `review` does** and send the + page's checked items without taking the keyboard, as `review send` does. + `--checks` or `--threads` sends that kind alone. With nothing checked and + unsent they are refused; `ci send` is told to show the page, which reads its + run's jobs only while shown, where `pr send` reads checks and threads itself + off the PR page (services/send-feedback.md). `pr send` waits with no timeout, + its answer coming once every checked check's log is read. ## Reviewed and left as is diff --git a/Docs/design/files/review-comments.md b/Docs/design/files/review-comments.md index 57a076fd..15afdfe5 100644 --- a/Docs/design/files/review-comments.md +++ b/Docs/design/files/review-comments.md @@ -128,6 +128,9 @@ panel's Review page (issue #6). Newest at the bottom. per file against that file's rows. The composer carries its file's path, the All changes tab holding several, and the tables a composer and its draft live in are keyed by the tab hosting cards, a file or All changes tab. +- **Review's foot and picker are shared with the PR and CI pages**, renamed + `Handoff*` in `Files/Panel/Handoff/` with one pick per worktree; see + [services/send-feedback.md](../services/send-feedback.md). ## Reviewed and left as is diff --git a/Docs/design/services/debug-stand-in.md b/Docs/design/services/debug-stand-in.md index 9234488c..7ba8d452 100644 --- a/Docs/design/services/debug-stand-in.md +++ b/Docs/design/services/debug-stand-in.md @@ -24,11 +24,15 @@ service's own command-line tool, for a scripted run. `title`, `state`, `headBranch`, `headCommit` and `headRepository` (a remote URL or `owner/name`), and optionally `url` (its GitHub page by default), `review`, `blocker`, `isReadyToMerge`, `autoMergesWhenReady`, `baseBranch`, - `updatedAt` and `checks` (`name`, `status`, `workflow`, `isRequired`, `link`); - and `ciRuns`, each with `id`, `branch`, `commit` and `status`, and optionally - `subject`, `isFinished`, `createdAt`, `repository` (where it ran; none matches - every project), `workflows` (`name`, `status`, `jobs` of `id`, `name`, - `status`) and `failures` (`workflow`, `job`, `text`). Dates are ISO 8601. + `updatedAt`, `checks` (`name`, `status`, `workflow`, `isRequired`, `link`, + `log`, the text a failed log read answers) and `threads` (`id`, `path`, + `line`, `originalLine`, `isOutdated`, `diffHunk`, `comments` of `id`, + `author`, `body`, `url`), a thread with no comments refused as the host never + answers one; and `ciRuns`, each with `id`, `branch`, `commit` and `status`, + and optionally `subject`, `isFinished`, `createdAt`, `repository` (where it + ran; none matches every project), `workflows` (`name`, `status`, `jobs` of + `id`, `name`, `status`) and `failures` (`workflow`, `job`, `text`). Dates are + ISO 8601. - **A value the stand-in cannot read refuses all of it**, a key no record takes or one missing included, naming the key path, rather than dropping one run unseen. The helper reads the file and sends its text, so the app opens no path diff --git a/Docs/design/services/marks-and-pages.md b/Docs/design/services/marks-and-pages.md index 0f36654b..f4d6c9dc 100644 --- a/Docs/design/services/marks-and-pages.md +++ b/Docs/design/services/marks-and-pages.md @@ -92,6 +92,9 @@ panel's pages. hold at most once a minute however often its list appears, one read at a time per run, and once more as it ends, a run reading failed while jobs still went; an earlier run's when its row opens. +- **The PR page also reads its open pull request's unresolved review threads**, + beside the checks and at their pace, kept for the panel's worktree alone. Both + pages send what failed to an agent; see [send-feedback.md](send-feedback.md). ## Reviewed and left as is diff --git a/Docs/design/services/merge-path.md b/Docs/design/services/merge-path.md index e324b61d..67e54e5a 100644 --- a/Docs/design/services/merge-path.md +++ b/Docs/design/services/merge-path.md @@ -46,6 +46,9 @@ or more checks the failing one sat among the passing ones. - **The words are the theme's text colour, not its secondary grey**: at 11 pt the grey measured 4.0:1 on the panel in Multishell Light. The chevron and the card keep their greys. +- **Unresolved review threads list under the review step**, or a Comments step + of their own where there is none, which is not counted among the steps left: a + thread holds no merge back. See [send-feedback.md](send-feedback.md). ## Reviewed and left as is diff --git a/Docs/design/services/send-feedback.md b/Docs/design/services/send-feedback.md new file mode 100644 index 00000000..87c7000a --- /dev/null +++ b/Docs/design/services/send-feedback.md @@ -0,0 +1,172 @@ +# Sending feedback to an agent + +The PR and CI pages send a pull request's failing checks, its unresolved review +threads and a CI run's failed jobs to an agent pane (issue #34). Mockups on the +issue. Newest at the bottom. + +- **The pages send, not Review.** An "Add to Review" on each item, so one Send + carried everything, was offered and not taken (owner's choice, 2026-11-19). + Each page has Review's foot, the same picker, no count and no hint. +- **The foot and picker are shared, as `Handoff*`.** Review's `ReviewRecipient`, + `ReviewFooter`, `ReviewRecipientMenu` and `ReviewSendFooter` became + `HandoffRecipient`, `HandoffFooter`, `HandoffRecipientMenu` and + `HandoffSendFooter` in `Files/Panel/Handoff/`, and their strings `handoff.*` + (owner's choice, 2026-11-19; NEW, not a reversal). "Handoff" is the word + `AgentHandoff` already used. One pick per worktree serves all three pages. + Each page wraps the foot in a view of its own, `ReviewSendFooter`, + `PullRequestSendFooter` and `CISendFooter`, so an agent's state change redraws + the foot and not the page. +- **Every item has a checkbox at the row's trailing edge.** Failing checks stay + under the Checks step in the host's order; a passing row keeps the empty slot, + so the Required tags stay in one column. A failing required check and every + thread start checked, an optional failing check unchecked. +- **A step's own checkbox is AppKit's, with its mixed state.** "Check all" and + "Uncheck all" were mocked and replaced (owner's choice, 2026-11-19). SwiftUI's + toggle draws no mixed state from one value, so `HandoffCheckbox` wraps + `NSButton` and undoes AppKit's own cycling on a click: the model decides. A + click on a mixed box checks all, as AppKit's does. It answers bot reviewers + that leave thirty threads. +- **A collapsed step says "1 to send"** after its hint, and a collapsed Latest + run after its title, since Send carries their checked items unseen. +- **Threads list under the review step**, or, where the path has none, a + Comments step of their own with Review's speech bubble, since an unresolved + thread neither passes nor fails. That step is not counted among the steps left + to clear: a thread holds no merge back. A merged or closed pull request lists + none, on the page, in the foot or in a Send, though a read before it settled + is kept until the next. +- **A sent item's checkbox becomes a green bubble**, a paper plane on + `ui.ci.passed`, its tooltip naming the agent. Review's "Sent to Claude Code" + chip was mocked and dropped: it took a line per item. A click on the bubble + turns it back into a checked box, to send the item again. +- **Item keys change where the thing does**: a check by its name, link and head, + since two checks can share a link and some keep theirs across a push; a thread + by its id and newest comment, so a new comment comes back checked; a CI job by + run, its place and job id, two workflows able to share a name; Run output by + run and its text's hash, a CircleCI rerun keeping the run's id. A rerun or + push needs no code to clear a bubble. +- **Choices and sent marks are runtime state** on `AppModel`, not saved as + Review's comments are: a relaunch shows everything unsent, which costs a + second send at most. Each page read lets go of the keys that page no longer + lists, each kind once its read answered, a failed run's report included, so a + failing thread read still lets the checks' old keys go: an item whose details + another worktree's read dropped keeps its mark. +- **The CI page finds a job's item by its place**, workflow index then job + index: two workflows can share a name. +- **What Send writes is `AgentHandoff`'s file**, a section per item, and the + mention is pasted as Review's is, with no Return. A check: its name, the head + it ran on where the worktree is elsewhere, its log's last 80 lines, its page. + A thread: its place, the end of its hunk, every comment. A CI job: its + workflow and name, its part of the report, its job id. Files are + `pr--.md` and `ci-.md`. +- **A worktree on another commit than the failure ran on is told so** in the + item's caveat, without saying which is ahead: Update branch on GitHub puts the + head past the worktree, unpushed commits the other way. Both pages match + commits by `namesSameCommit(as:)`, a seven-character prefix at least. +- **Logs and reports keep their last 80 lines**, a count of those cut said + first. Where a build fails is at the end, and a whole log is not for an + agent's context. The number is a choice, not a measurement. +- **An Actions check's log is read at Send** from the job's REST endpoint, + `gh api --hostname --allow-escape-sequences repos///actions/jobs//logs`, + the job id from the check's link (`/actions/runs//job/`, seen on + #43). `gh run view --job` refuses every job until its whole run ends, so a + lint job failing early sent no log (seen on #46). The endpoint gives the whole + job, the runner's cleanup after the failure, so the log ends at its last + `##[error]` line. Each line's timestamp, a step's byte-order mark, its + terminal codes and Actions' group markers are stripped, a fold's end dropped + so it takes no line, and a CRLF line split as any other. Four read at once, as + other service reads, and only the last 160 lines are cleaned, the lines before + them counted in bytes so the cut is said in the whole log's terms, a line + ending at `\n` alone so a progress bar's `\r` stays in its line, the tail + trimming blank and marker lines to 80. "Reading N logs" counts the checks the + host can read. A check from any other CI sends its name and link. +- **While logs read, the foot says "Reading 1 log" and Send is off**, so a + second click sends nothing twice: a Send with checks is claimed before any + read, a thread read included, and the foot says "Reading what to send" until + its logs are counted. A Send of threads alone reads no log, so goes meanwhile. + A Send for a worktree whose PR page is not on the panel, or with the app in + the background, from `pr send`, reads its checks, their head and its threads + first, together, the page reading them only while shown and frontmost, so none + sent are stale, and checks a push moved are captioned with the head they ran + on; one on the page before its first thread read answers sends none, a box + nobody has seen not going checked; their text dropped with the row; a page + whose thread read failed sends the threads it still shows from the last read + that answered, under its note, else its checks without them; checks that fail + to read off the page are left out the same way; failing that it sends nothing + and says why, checks first. Threads alone from a page whose thread read failed + say why too. Send then goes to the pane the picker showed, or nowhere: one + closed meanwhile gets nothing, the foot says so, and the items stay checked. A + paste the pane refuses says so over the foot, on either page, as does a pane + picked and closed before the click, though not a `--to` naming a pane with no + agent; a file that cannot be written is said by its alert alone. A box + unchecked meanwhile is left out. A log that fails to read is sent anyway, + `gh`'s words as its caveat, and an empty one says it printed nothing: the + agent can open the link, and one log should not hold back the rest. +- **The CI page reads nothing new.** It sends the report its page already read. + Only the newest run's jobs can be sent; earlier runs are history. A job that + failed while its run still goes has no report until the run ends, and says so + under its row; sent then, it goes without one. A job an ended run's report + leaves out is said to be left out. +- **Report text naming no listed job is "Run output"** with a checkbox of its + own: it can be the only failure, a config error before any job ran. A job the + report speaks of can be sent whatever unclear status the provider gave it, its + text being shown under its row; one that passed cannot, a rerun's passing job + sharing a failed one's names. A run that passed has nothing to send; a + cancelled one's failed jobs can be. +- **Unresolved threads are read while the PR page shows**, beside its checks and + at their pace, through `gh api graphql` (`reviewThreads`, a hundred a page, + ten pages at most): `gh pr view` does not say whether a thread is resolved. + `gh api` is still the tool, with `gh`'s login and `--hostname` for Enterprise. + A failed read is a note under the card. Thread text is kept for the panel's + worktree alone, as run details are: a change of row drops the rest, and a late + read for a row left is not kept. A return to a row whose threads were dropped + reads them at once rather than at the next poll. The two reads run together. + Only the first comment's hunk is asked for: it places the thread. +- **An outdated thread is labelled by the line it was written on**, its `line` + being gone, and tagged Outdated; one on a whole file by its path. + +## Reviewed and left as is + +- **A CircleCI job and its pull request check are two items.** Counting them as + one needs the check's link matched to the job's id, which nothing here has + shown can be done. +- **A thread's comments are its first hundred.** No review thread seen comes + near; paging them would be a query per thread. +- **The PR page's Send keeps the pull request it began with.** A push during the + log reads leaves the checked checks in, the checks list being the one it drew. + Only a checks read at the new head between them would drop them, and those + would be the old head's. +- **Send's focus after the log reads does not move the selection.** Taking the + agent's tab focuses it within its worktree; selecting another worktree during + the reads keeps it selected (tried on 2026-11-19). +- **Review keeps its own receipt.** It clears when a comment is added, a rule + about comments; the PR and CI pages' clears when none of their items is marked + sent. One store would hold two rules. +- **A worktree removed during the log reads leaves no note behind.** Tried on + 2026-11-19: the Send finds its pane gone and stores nothing for it. +- **A Send whose file cannot be written answers `pr send` with the error's + alert**, not with a refusal of its own: a request's alert is its answer + (agents/command-line.md), and the app presents the write's error. +- **`review send` with a file it cannot write answers with the write's alert**, + not "pane has no shell yet": a request's alert replaces its refusal (tested on + 2026-11-19). `sendReview` keeps its Bool. +- **A Send clicked as the picked agent exits, its pane still open, says + nothing.** The foot redraws on the board's next change with the next agent or + "No agent"; the window is one redraw, and a note would need the UI's Send told + apart from a script's `--to` naming a shell. +- **A script's `--to` naming a closed pane notes "The pane picked has closed" + over the page's foot**, as a script's other misses are noted there. Telling it + from the page's Send needs the flag the entry above declines. +- **A thread's comment text goes to the agent as written**, a bot's own headings + included: escaping it would change the code it quotes, as + files/review-comments.md settles for Review's comments. +- **The PR page reads its threads twice a draw**, once for the merge path's + count and once for its rows and foot. Both run in one synchronous draw on the + main actor, so no read lands between them; one is a dictionary lookup. +- **Unproven: a failed log taking past the 30 s read timeout.** It would be sent + with "did not answer in time" as its caveat. No log here has come close. +- **Unproven: a thread on removed lines, or on several, is labelled by one line + number.** GitHub's `line` may be the base file's for a removed line, and a + range shows its last line; the quoted hunk still places it. Asking for + `diffSide` and `startLine` would say more. +- **Unproven: OSC escapes, such as terminal hyperlinks, are not stripped** from + a log, only CSI codes. No log here has carried one. diff --git a/Docs/develop/dependencies.md b/Docs/develop/dependencies.md index a7ad5bd7..782483e8 100644 --- a/Docs/develop/dependencies.md +++ b/Docs/develop/dependencies.md @@ -117,8 +117,11 @@ - **`gh` and `circleci` are optional**, found on the login shell's PATH and never shipped: without one its integration shows nothing, and the Integrations page says how to install it. `circleci` 1.0 is the floor, the first with the - run commands. Their output is read as JSON, any field optional, so a release - that drops one costs that record (design/services/reads.md). + run commands; `gh` 2.97.0 is, the first whose `gh api` takes + `--allow-escape-sequences`, which a job's log needs; an older one still reads + the rest, the Integrations page saying it is too old. Their output is read as + JSON, any field optional, so a release that drops one costs that record + (design/services/reads.md). - **prettier formats the Markdown** for `make format` and the Claude Code hook. From Homebrew rather than a `package.json`: there is no Node toolchain here, and a `node_modules` for one formatter is more than the docs are worth. diff --git a/Sources/MultishellAppCore/Control/HandoffReceipt.swift b/Sources/MultishellAppCore/Control/HandoffReceipt.swift new file mode 100644 index 00000000..e936358a --- /dev/null +++ b/Sources/MultishellAppCore/Control/HandoffReceipt.swift @@ -0,0 +1,11 @@ +import Foundation + +/// What `multishell pr send` and `ci send` print: how many items went to which +/// agent pane. +struct HandoffReceipt: Encodable, Equatable { + /// Its worktree's `ControlID`. + let worktree: String + let pane: UUID + let agent: String + let itemCount: Int +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffCandidate.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffCandidate.swift new file mode 100644 index 00000000..ba60de1b --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffCandidate.swift @@ -0,0 +1,11 @@ +/// An item a page lists as sendable, and whether its checkbox starts checked: +/// a failing optional check starts unchecked, everything else checked. +public struct HandoffCandidate: Hashable, Sendable { + public let id: HandoffItemID + let startsChecked: Bool + + init(_ id: HandoffItemID, startsChecked: Bool = true) { + self.id = id + self.startsChecked = startsChecked + } +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffChoices.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffChoices.swift new file mode 100644 index 00000000..acafe754 --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffChoices.swift @@ -0,0 +1,58 @@ +/// One worktree's checkboxes on the PR and CI pages and what each Send carried. +/// Runtime state; see Docs/design/services/send-feedback.md. +struct HandoffChoices: Equatable, Sendable { + /// Where the user set a box, back to how it starts included. + private var picks: [HandoffItemID: Bool] = [:] + private var sentTo: [HandoffItemID: String] = [:] + + func state(of candidate: HandoffCandidate) -> HandoffItemState { + if let agentName = sentTo[candidate.id] { return .sent(agentName: agentName) } + return (picks[candidate.id] ?? candidate.startsChecked) ? .checked : .unchecked + } + + /// `nil` where nothing is left to send, so the step draws no box. + func groupState(of candidates: [HandoffCandidate]) -> HandoffGroupState? { + let unsent = candidates.filter { sentTo[$0.id] == nil } + guard !unsent.isEmpty else { return nil } + let checked = unsent.count { state(of: $0).isChecked } + if checked == unsent.count { return .checked } + return checked == 0 ? .unchecked : .mixed + } + + func checked(among candidates: [HandoffCandidate]) -> [HandoffCandidate] { + candidates.filter { state(of: $0).isChecked } + } + + mutating func set(_ id: HandoffItemID, checked: Bool) { + picks[id] = checked + } + + /// Every unsent item unchecked where all were checked, else every one checked, + /// as a click on AppKit's mixed checkbox turns it on. + mutating func toggleGroup(_ candidates: [HandoffCandidate]) { + let checksAll = groupState(of: candidates) != .checked + for candidate in candidates where sentTo[candidate.id] == nil { + picks[candidate.id] = checksAll + } + } + + mutating func markSent(_ ids: [HandoffItemID], to agentName: String) { + for id in ids { + sentTo[id] = agentName + picks[id] = nil + } + } + + /// Keeps only what `source` lists now, other reads' keys untouched: each push, + /// rerun or reply makes new keys. + mutating func keepOnly(_ listed: Set, from source: HandoffItemSource) { + picks = picks.filter { $0.key.source != source || listed.contains($0.key) } + sentTo = sentTo.filter { $0.key.source != source || listed.contains($0.key) } + } + + /// A click on the sent bubble: back to a checked box, to send it again. + mutating func unmarkSent(_ id: HandoffItemID) { + sentTo[id] = nil + picks[id] = true + } +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffDelivery.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffDelivery.swift new file mode 100644 index 00000000..a1e300b4 --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffDelivery.swift @@ -0,0 +1,8 @@ +/// How writing a Send's file and pasting its mention went. +enum HandoffDelivery: Equatable, Sendable { + case delivered + /// The pane took no paste: it closed, or its shell has not started. + case notPasted + /// The file could not be written; its error was presented. + case notWritten +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffFooter.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffFooter.swift new file mode 100644 index 00000000..561c38e2 --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffFooter.swift @@ -0,0 +1,10 @@ +/// A Send foot on Review, the PR or the CI page: what the last Send did until +/// there is more to send, else the picker and Send, else why nobody can be sent to. +public enum HandoffFooter: Equatable, Sendable { + case noRecipient(String) + /// "Reading 2 logs": Send is off until they are read and sent. + case reading(String) + case ready(picked: HandoffRecipient, recipients: [HandoffRecipient], canSend: Bool) + /// "3 comments sent to Claude Code". + case sent(summary: String) +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffGroupState.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffGroupState.swift new file mode 100644 index 00000000..53856c2b --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffGroupState.swift @@ -0,0 +1,6 @@ +/// A step's own checkbox over its unsent items: AppKit's on, mixed and off. +public enum HandoffGroupState: Equatable, Sendable { + case checked + case mixed + case unchecked +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemID.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemID.swift new file mode 100644 index 00000000..268f43fd --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemID.swift @@ -0,0 +1,25 @@ +import Foundation + +/// One thing the PR or CI page can send. A rerun, a push or a new comment +/// changes its key, so it comes back unsent and as it starts. +public enum HandoffItemID: Hashable, Sendable { + /// Two checks can share a link, and some keep theirs across a push. + case check(name: String, link: URL?, headCommit: String) + /// A failed job of a CI run by its place, two workflows able to share a name, + /// and the provider's id for it, which a rerun replaces. + case ciJob(runID: String, position: CIJobPosition, jobID: String?) + /// What a failed run's report says that names no listed job, by its text's hash, + /// which a rerun under the same id changes; hashed once, not at every lookup. + case ciRunOutput(runID: String, textHash: Int) + /// An unresolved thread and its newest comment. + case thread(id: String, newestCommentID: String) + + /// Which read lists it: only that read, once answered, can say it is gone. + var source: HandoffItemSource { + switch self { + case .check: .checks + case .thread: .threads + case .ciJob, .ciRunOutput: .ciRun + } + } +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemSource.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemSource.swift new file mode 100644 index 00000000..a697e6bc --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemSource.swift @@ -0,0 +1,7 @@ +/// The read that lists a sendable item, which prunes its kind alone: a failed +/// thread read must not keep the checks' old keys, nor drop the threads'. +enum HandoffItemSource: Equatable, Sendable { + case checks + case ciRun + case threads +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemState.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemState.swift new file mode 100644 index 00000000..dcfddc52 --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffItemState.swift @@ -0,0 +1,13 @@ +/// What a sendable row draws at its trailing edge: a checkbox, or the sent bubble. +public enum HandoffItemState: Equatable, Sendable { + case checked + /// Sent to the agent named, its tooltip and spoken label. + case sent(agentName: String) + case unchecked + + var isChecked: Bool { self == .checked } + + var isSent: Bool { + if case .sent = self { true } else { false } + } +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffLogTail.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffLogTail.swift new file mode 100644 index 00000000..70e8ff1a --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffLogTail.swift @@ -0,0 +1,21 @@ +import Foundation + +/// The end of a log or report as Send quotes it: where it failed is at the end, +/// and an agent's context is not the place for a whole build log. +enum HandoffLogTail { + private static let lineCount = 80 + /// What a read keeps for the tail to cut: blank and marker lines at the end go. + static var linesToRead: Int { lineCount * 2 } + + /// Its last lines, said so where some were cut. + static func lines(of text: String) -> (lines: [String], cutCount: Int) { + // A CRLF ending is one Character; a bare "\r" is a progress bar's frame, not a line. + let all = text.split(omittingEmptySubsequences: false) { $0 == "\n" || $0 == "\r\n" } + .map(String.init) + let trimmed = Array( + all.reversed().drop { $0.trimmingCharacters(in: .whitespaces).isEmpty }.reversed() + ) + let kept = trimmed.suffix(lineCount) + return (Array(kept), trimmed.count - kept.count) + } +} diff --git a/Sources/MultishellAppCore/Files/Panel/Review/ReviewRecipient.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffRecipient.swift similarity index 74% rename from Sources/MultishellAppCore/Files/Panel/Review/ReviewRecipient.swift rename to Sources/MultishellAppCore/Files/Panel/Handoff/HandoffRecipient.swift index 04108c39..44532bfc 100644 --- a/Sources/MultishellAppCore/Files/Panel/Review/ReviewRecipient.swift +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffRecipient.swift @@ -1,8 +1,8 @@ import Foundation import MultishellCore -/// An agent pane a review can be sent to, as Review's picker lists it. -public struct ReviewRecipient: Identifiable, Equatable, Sendable { +/// An agent pane a Send can go to, as a page's picker lists it. +public struct HandoffRecipient: Identifiable, Equatable, Sendable { public let id: TerminalSession.ID public let agentID: String public let agentName: String @@ -25,11 +25,11 @@ public struct ReviewRecipient: Identifiable, Equatable, Sendable { public func stateText(at now: Date) -> String { switch lane { case .working: - ElapsedText.short(since: since, now: now).map { t("review.recipient-working-for", $0) } + ElapsedText.short(since: since, now: now).map { t("handoff.recipient-working-for", $0) } ?? lane.title(inSentence: true) case .waiting: lane.title(inSentence: true) - case .done, .idle: t("review.recipient-at-prompt") + case .done, .idle: t("handoff.recipient-at-prompt") } } } diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffSendOutcome.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffSendOutcome.swift new file mode 100644 index 00000000..5d3602b3 --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffSendOutcome.swift @@ -0,0 +1,24 @@ +import MultishellCore + +/// What a PR or CI page's Send did, which `pr send` and `ci send` answer by. +public enum HandoffSendOutcome: Equatable, Sendable { + /// Another Send from the page is still under way. + case alreadySending + /// The script that asked hung up before the Send went, so nothing went. + case cancelled + /// The checks the Send needed could not be read, in the tool's words. + case checksNotRead(reason: String) + /// The worktree shows no pull request, or no run, to send from. + case noPage + /// No pane named or picked has an agent, or it closed while the logs were read. + case noRecipient + /// Nothing was left checked when it would have gone. + case nothingChecked + /// The pane took no paste: it closed, or its shell has not started. + case notPasted(to: TerminalSession.ID) + /// The file could not be written; its error was presented. + case notWritten + case sent(itemCount: Int, to: HandoffRecipient) + /// The threads the Send needed could not be read, in the tool's words. + case threadsNotRead(reason: String) +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffSendPhase.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffSendPhase.swift new file mode 100644 index 00000000..7303d901 --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffSendPhase.swift @@ -0,0 +1,7 @@ +/// Where a PR page Send with checks stands, which its foot says and which keeps +/// a second Send from reading the same logs. +enum HandoffSendPhase: Equatable, Sendable { + /// Claimed, reading the threads or working out what to send. + case preparing + case readingLogs(count: Int) +} diff --git a/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffState.swift b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffState.swift new file mode 100644 index 00000000..2aab781c --- /dev/null +++ b/Sources/MultishellAppCore/Files/Panel/Handoff/HandoffState.swift @@ -0,0 +1,20 @@ +import MultishellCore +import Observation + +/// What Send holds, by worktree. Its own observable, so a log read's count +/// redraws the foot and not every checkbox; see services/send-feedback.md. +@Observable +@MainActor +final class HandoffState { + /// The agent pane each worktree's picker was set to, shared by Review and the + /// PR and CI pages. + var recipientPicks: [Worktree.ID: TerminalSession.ID] = [:] + /// Each worktree's checkboxes and what each Send carried. + var choices: [Worktree.ID: HandoffChoices] = [:] + /// What each worktree's last Send from the PR or CI page said, per page. + var receipts: [Worktree.ID: [ServicePage: String]] = [:] + /// Each worktree's PR page Send with checks, while one is under way. + var sendPhases: [Worktree.ID: HandoffSendPhase] = [:] + /// Why each page's last Send sent nothing, until the next pick or Send there. + var misses: [Worktree.ID: [ServicePage: String]] = [:] +} diff --git a/Sources/MultishellAppCore/Files/Panel/Review/ReviewFooter.swift b/Sources/MultishellAppCore/Files/Panel/Review/ReviewFooter.swift deleted file mode 100644 index 4630a279..00000000 --- a/Sources/MultishellAppCore/Files/Panel/Review/ReviewFooter.swift +++ /dev/null @@ -1,7 +0,0 @@ -/// What Review's foot shows: what the last Send did until there is more to -/// send, else the picker and Send, else why there is nobody to send to. -public enum ReviewFooter: Equatable, Sendable { - case noRecipient(String) - case ready(picked: ReviewRecipient, recipients: [ReviewRecipient], canSend: Bool) - case sent(ReviewSendReceipt) -} diff --git a/Sources/MultishellAppCore/Files/Panel/Review/ReviewSendReceipt.swift b/Sources/MultishellAppCore/Files/Panel/Review/ReviewSendReceipt.swift index 6f774f30..143ef91a 100644 --- a/Sources/MultishellAppCore/Files/Panel/Review/ReviewSendReceipt.swift +++ b/Sources/MultishellAppCore/Files/Panel/Review/ReviewSendReceipt.swift @@ -7,6 +7,6 @@ public struct ReviewSendReceipt: Equatable, Sendable { /// "3 comments sent to Claude Code". public var summary: String { - t("review.sent-summary", t("count.comments", count), agentName) + t("handoff.sent-summary", t("count.comments", count), agentName) } } diff --git a/Sources/MultishellAppCore/Files/Review/ReviewHandoff.swift b/Sources/MultishellAppCore/Files/Review/ReviewHandoff.swift index c452e414..3db402c7 100644 --- a/Sources/MultishellAppCore/Files/Review/ReviewHandoff.swift +++ b/Sources/MultishellAppCore/Files/Review/ReviewHandoff.swift @@ -4,18 +4,14 @@ import MultishellCore /// What Send writes for the agent: every pending comment of a worktree as one /// note; see Docs/design/files/review-comments.md. enum ReviewHandoff { - private static var maxNameLength: Int { 200 } - static var introduction: String { t("review.handoff-introduction") } static func entries(of comments: [ReviewComment]) -> [AgentHandoffEntry] { comments.inReviewOrder.map(entry(of:)) } - /// Named for the worktree in the characters every file name takes, cut to a - /// length every disk takes. static func fileName(forWorktreeNamed name: String) -> String { - "review-\(name.portableName(maxLength: maxNameLength)).md" + AgentHandoff.fileName("review", forWorktreeNamed: name) } private static func entry(of comment: ReviewComment) -> AgentHandoffEntry { diff --git a/Sources/MultishellAppCore/Model/AppModel.swift b/Sources/MultishellAppCore/Model/AppModel.swift index 4bdb1079..c9cf5be3 100644 --- a/Sources/MultishellAppCore/Model/AppModel.swift +++ b/Sources/MultishellAppCore/Model/AppModel.swift @@ -197,12 +197,12 @@ public final class AppModel { @ObservationIgnored let reviewsDirectory: URL /// Each worktree's file written to this run, its writes landing in order. @ObservationIgnored var reviewFiles: [Worktree.ID: ReviewFile] = [:] - /// The agent pane Review's picker was set to in each worktree. Runtime state. - var reviewRecipientPicks: [Worktree.ID: TerminalSession.ID] = [:] /// What each worktree's last Send said, until a comment is added there. var reviewSendReceipts: [Worktree.ID: ReviewSendReceipt] = [:] + /// What Send's foot and picker hold by worktree. Runtime state. + @ObservationIgnored let handoff = HandoffState() /// Each worktree's panes by when they last took focus, newest first, which - /// picks the agent a review goes to. + /// picks the agent a Send goes to. var focusedSessionHistory: [Worktree.ID: [TerminalSession.ID]] = [:] /// The comment last clicked in each worktree's Review, its card outlined. var selectedReviewComments: [Worktree.ID: ReviewComment.ID] = [:] diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlHandoff.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlHandoff.swift new file mode 100644 index 00000000..77ed6be9 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlHandoff.swift @@ -0,0 +1,81 @@ +import Foundation +import MultishellCore +import MultishellServices + +/// `multishell pr send` and `ci send`: the PR and CI pages' Send. +extension AppModel { + func replyToSendPullRequestFeedback( + in id: String?, + to sessionID: UUID?, + includesChecks: Bool, + includesThreads: Bool, + ) async -> ControlReply { + await replyingInWorktree(id) { worktree in + // As `panes paste`: the pane keeps whatever had the keyboard. + let outcome = await sendPullRequestFeedback( + of: worktree.id, + to: sessionID, + takingFocus: false, + includesChecks: includesChecks, + includesThreads: includesThreads, + ) + return handoffReply(outcome, from: .pullRequest, in: worktree) + } + } + + func replyToSendCIFailures(in id: String?, to sessionID: UUID?) async -> ControlReply { + await replyingInWorktree(id) { worktree in + let outcome = sendCIFailures(of: worktree.id, to: sessionID, takingFocus: false) + return handoffReply(outcome, from: .ciRuns, in: worktree) + } + } + + /// What the Send did, in the refusal a script can act on. + private func handoffReply( + _ outcome: HandoffSendOutcome, + from page: ServicePage, + in worktree: Worktree, + ) -> ControlReply { + let worktreeControlID = ControlID.worktree(worktree.id) + switch outcome { + case .alreadySending: + return .refused(.handoffUnderWay(id: worktreeControlID)) + + case .cancelled: + // The helper hung up, so nothing reads the reply. + return .done + + case .checksNotRead(let reason): + return .refused(.checksNotRead(id: worktreeControlID, reason: reason)) + + case .noPage: + return .refused(.noServicePage(page, id: worktreeControlID)) + + case .nothingChecked: + return .refused(.nothingToHandOff(page, id: worktreeControlID)) + + case .notPasted(let sessionID): + return .refused(.paneNotLive(id: sessionID)) + + case .noRecipient: + return .refused(.noRecipient(id: worktreeControlID)) + + case .notWritten: + // The write's error was presented, and a request's alert is its answer. + return .done + + case .threadsNotRead(let reason): + return .refused(.threadsNotRead(id: worktreeControlID, reason: reason)) + + case .sent(let itemCount, let recipient): + return .json( + HandoffReceipt( + worktree: worktreeControlID, + pane: recipient.id, + agent: recipient.agentName, + itemCount: itemCount, + ) + ) + } + } +} diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlLookup.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlLookup.swift index 3e3040e5..a825ce93 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlLookup.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlLookup.swift @@ -10,4 +10,16 @@ extension AppModel { func worktree(withControlID id: String) -> Worktree? { workspace.worktrees.first { ControlID.worktree($0.id) == id } } + + /// `reply` in the worktree named, else the one in view; refused where there is none. + func replyingInWorktree( + _ id: String?, + _ reply: (Worktree) async -> ControlReply, + ) async -> ControlReply { + let named = id.map { worktree(withControlID: $0) } ?? worktreeInView + guard let worktree = named else { + return .refused(id.map { .noWorktree(id: $0) } ?? .nothingInView) + } + return await reply(worktree) + } } diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift index b022c625..aae6fbc0 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift @@ -102,6 +102,17 @@ extension AppModel { case .clearReviewComments(let worktree, let sentOnly): await replyToClearReviewComments(in: worktree, sentOnly: sentOnly) + case .sendPullRequestFeedback(let worktree, let sessionID, let checks, let threads): + await replyToSendPullRequestFeedback( + in: worktree, + to: sessionID, + includesChecks: checks, + includesThreads: threads, + ) + + case .sendCIFailures(let worktree, let sessionID): + await replyToSendCIFailures(in: worktree, to: sessionID) + case .filterFiles(let text): replyToFilterFiles(text) case .setFilesFolderExpanded(let path, let expanded): diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift index 414fda2f..1331e83e 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift @@ -4,13 +4,13 @@ import MultishellCore /// `multishell review`: Review's list, a composer's Add, Send and Clear sent. extension AppModel { func replyToListReviewComments(in id: String?) async -> ControlReply { - await replyingInReviewedWorktree(id) { worktree in reviewListing(of: worktree) } + await replyingInWorktree(id) { worktree in reviewListing(of: worktree) } } /// Quoted from the file's open tab, as a comment written there is; never /// the All changes tab (owner's pick). func replyToAddReviewComment(_ order: ReviewCommentOrder) async -> ControlReply { - await replyingInReviewedWorktree(order.worktreeID) { worktree in + await replyingInWorktree(order.worktreeID) { worktree in await replyToAdd(order, in: worktree) } } @@ -79,7 +79,7 @@ extension AppModel { } func replyToSendReview(in id: String?, to sessionID: UUID?) async -> ControlReply { - await replyingInReviewedWorktree(id) { worktree in replyToSend(of: worktree, to: sessionID) } + await replyingInWorktree(id) { worktree in replyToSend(of: worktree, to: sessionID) } } private func replyToSend(of worktree: Worktree, to sessionID: UUID?) -> ControlReply { @@ -87,13 +87,9 @@ extension AppModel { guard reviewComments(in: worktree.id).contains(where: \.isPending) else { return .refused(.nothingToSend(id: worktreeControlID)) } - let recipient = - if let sessionID { - reviewRecipients(in: worktree.id).first { $0.id == sessionID } - } else { - reviewRecipient(in: worktree.id) - } - guard let recipient else { return .refused(.noReviewRecipient(id: worktreeControlID)) } + guard let recipient = handoffRecipient(named: sessionID, in: worktree.id) else { + return .refused(.noRecipient(id: worktreeControlID)) + } // As `panes paste`: the pane keeps whatever had the keyboard. guard sendReview(of: worktree.id, to: recipient.id, takingFocus: false) else { return .refused(.paneNotLive(id: recipient.id)) @@ -102,7 +98,7 @@ extension AppModel { } func replyToClearReviewComments(in id: String?, sentOnly: Bool) async -> ControlReply { - await replyingInReviewedWorktree(id) { worktree in + await replyingInWorktree(id) { worktree in if sentOnly { clearSentReviewComments(in: worktree.id) } else { @@ -112,18 +108,6 @@ extension AppModel { } } - /// `reply` in the worktree named, else the one in view; refused where there is none. - private func replyingInReviewedWorktree( - _ id: String?, - _ reply: (Worktree) async -> ControlReply, - ) async -> ControlReply { - let named = id.map { worktree(withControlID: $0) } ?? worktreeInView - guard let worktree = named else { - return .refused(id.map { .noWorktree(id: $0) } ?? .nothingInView) - } - return await reply(worktree) - } - private func holdsRemovedLines( _ lines: ClosedRange, ofFile path: String, diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+CIHandoff.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+CIHandoff.swift new file mode 100644 index 00000000..79405171 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+CIHandoff.swift @@ -0,0 +1,85 @@ +import Foundation +import MultishellCore +import MultishellServices + +extension AppModel { + /// The newest run's failures the CI page can send: earlier runs are history. + func ciHandoffItems(of run: CIRun) -> [CIHandoffItem] { + ciWorkflowListing(of: run, sendsFailures: true).items + } + + /// What the page lists of `run`, read once per draw; only the newest run's + /// failures can be sent, earlier runs being history. + public func ciWorkflowListing(of run: CIRun, sendsFailures: Bool) -> CIWorkflowListing { + let workflows = ciWorkflows(ofRun: run) + // Before its workflows read, the whole report would be one Run output, sent + // again as jobs once they land. + return CIWorkflowListing( + run: run, + workflows: workflows ?? [], + report: failureReport(of: run), + sendsFailures: sendsFailures && workflows != nil, + ) + } + + /// `nil` where the newest run has nothing to send and nothing was sent from it; + /// over the items the page already built for its rows. + public func ciHandoffFooter( + of worktree: Worktree, + over listing: CIWorkflowListing, + ) -> HandoffFooter? { + handoffFooter(on: .ciRuns, of: listing.candidates, in: worktree) + } + + /// The newest run's checked failures written to one file and mentioned in the + /// prompt of the pane named, else the picker's, then marked sent. + @discardableResult + public func sendCIFailures( + of worktreeID: Worktree.ID, + to sessionID: TerminalSession.ID?, + takingFocus: Bool, + ) -> HandoffSendOutcome { + guard let worktree = workspace.worktree(worktreeID), case .run(let run) = ciPage(of: worktree) + else { return .noPage } + // Each Send says only its own outcome, not the last one's. + noteHandoffMiss(nil, on: .ciRuns, in: worktreeID) + let choices = handoff.choices[worktreeID] ?? HandoffChoices() + let items = ciHandoffItems(of: run).filter { choices.state(of: $0.candidate).isChecked } + guard !items.isEmpty else { return .nothingChecked } + guard let recipient = handoffRecipientNotingMiss(named: sessionID, on: .ciRuns, in: worktreeID) + else { + return .noRecipient + } + let provider = ciProviderName(of: worktree) ?? "" + let document = AgentHandoff.document( + introduction: CIHandoff.introduction(provider: provider), + entries: CIHandoff.entries( + of: items, + run: run, + provider: provider, + localTip: services(of: worktree).localTip, + ), + ) + let delivery = deliverHandoff( + document, + named: CIHandoff.fileName(forWorktreeNamed: workspace.displayName(of: worktree)), + sentence: { t("handoff.ci-sentence", $0) }, + to: recipient, + takingFocus: takingFocus, + ) + if let missed = outcomeNotingMiss(of: delivery, to: recipient, on: .ciRuns, in: worktreeID) { + return missed + } + let jobCount = items.count { $0.job != nil } + let count = + jobCount == items.count ? t("count.jobs", jobCount) : t("count.failures", items.count) + markHandoffItemsSent( + items.map(\.candidate.id), + on: .ciRuns, + in: worktreeID, + to: recipient.agentName, + summary: t("handoff.sent-summary", count, recipient.agentName), + ) + return .sent(itemCount: items.count, to: recipient) + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+ForgetHandoffState.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+ForgetHandoffState.swift new file mode 100644 index 00000000..2f709d7a --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+ForgetHandoffState.swift @@ -0,0 +1,15 @@ +import MultishellCore + +extension AppModel { + /// A removed worktree's Send state goes with it, the shared picker's included. + func forgetHandoffState(of gone: Set) { + for id in gone { + // A write of nil to a key never set still redraws every reader. + setIfChanged(\.handoff.recipientPicks[id], nil) + setIfChanged(\.focusedSessionHistory[id], nil) + setIfChanged(\.handoff.choices[id], nil) + setIfChanged(\.handoff.receipts[id], nil) + setIfChanged(\.handoff.misses[id], nil) + } + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffChoices.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffChoices.swift new file mode 100644 index 00000000..7c33c6cc --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffChoices.swift @@ -0,0 +1,108 @@ +import MultishellCore +import MultishellServices + +extension AppModel { + public func handoffState( + of candidate: HandoffCandidate, + in worktreeID: Worktree.ID, + ) -> HandoffItemState { + (handoff.choices[worktreeID] ?? HandoffChoices()).state(of: candidate) + } + + public func handoffGroupState( + of candidates: [HandoffCandidate], + in worktreeID: Worktree.ID, + ) -> HandoffGroupState? { + (handoff.choices[worktreeID] ?? HandoffChoices()).groupState(of: candidates) + } + + public func toggleHandoffItem(_ candidate: HandoffCandidate, in worktreeID: Worktree.ID) { + updateHandoffChoices(in: worktreeID) { choices in + choices.set(candidate.id, checked: !choices.state(of: candidate).isChecked) + } + } + + public func toggleHandoffGroup(_ candidates: [HandoffCandidate], in worktreeID: Worktree.ID) { + updateHandoffChoices(in: worktreeID) { $0.toggleGroup(candidates) } + } + + /// A click on the sent bubble, to send the item again. + public func unmarkHandoffItemSent(_ id: HandoffItemID, in worktreeID: Worktree.ID) { + updateHandoffChoices(in: worktreeID) { $0.unmarkSent(id) } + } + + /// "1 to send" over a collapsed list, since Send carries its checked items unseen. + public func handoffToSendText( + of candidates: [HandoffCandidate], + isCollapsed: Bool, + in worktreeID: Worktree.ID, + ) -> String? { + guard isCollapsed else { return nil } + let count = (handoff.choices[worktreeID] ?? HandoffChoices()).checked(among: candidates).count + return count == 0 ? nil : t("count.to-send", count) + } + + func markHandoffItemsSent( + _ ids: [HandoffItemID], + on page: ServicePage, + in worktreeID: Worktree.ID, + to agentName: String, + summary: String, + ) { + updateHandoffChoices(in: worktreeID) { $0.markSent(ids, to: agentName) } + var receipts = handoff.receipts[worktreeID] ?? [:] + receipts[page] = summary + setIfChanged(\.handoff.receipts[worktreeID], receipts) + } + + /// After `page` read: what it no longer lists is let go, each read's kind only + /// once that read answered, so an item whose details were dropped keeps its mark. + func pruneHandoffChoices(of worktree: Worktree, after page: ServicePage) { + guard handoff.choices[worktree.id] != nil else { return } + for (source, listed) in listedHandoffItems(of: worktree, on: page) { + updateHandoffChoices(in: worktree.id) { $0.keepOnly(listed, from: source) } + } + } + + /// Each read the page made that has answered, with what it lists. + private func listedHandoffItems( + of worktree: Worktree, + on page: ServicePage, + ) -> [HandoffItemSource: Set] { + switch page { + case .pullRequest: + guard case .pullRequest(let pullRequest) = pullRequestPage(of: worktree) else { return [:] } + let checks = mergeReadiness(of: pullRequest, in: worktree).checks + let threads = remoteState.threads[worktree.id] + let items = PullRequestHandoffItem.items( + checks: checks, + headCommit: pullRequest.headCommit, + threads: unresolvedThreads(of: pullRequest, in: worktree), + ) + .map(\.candidate.id) + var listed: [HandoffItemSource: Set] = [:] + if checks != nil { listed[.checks] = Set(items.filter { $0.source == .checks }) } + if pullRequest.state.isSettled + || (threads?.pullRequestNumber == pullRequest.number && threads?.threads != nil) + { + listed[.threads] = Set(items.filter { $0.source == .threads }) + } + return listed + + case .ciRuns: + guard case .run(let run) = ciPage(of: worktree), ciWorkflows(ofRun: run) != nil, + run.status != .failed || failureReport(of: run) != nil + else { return [:] } + return [.ciRun: Set(ciHandoffItems(of: run).map(\.candidate.id))] + } + } + + private func updateHandoffChoices( + in worktreeID: Worktree.ID, + _ update: (inout HandoffChoices) -> Void, + ) { + var choices = handoff.choices[worktreeID] ?? HandoffChoices() + update(&choices) + setIfChanged(\.handoff.choices[worktreeID], choices) + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffDelivery.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffDelivery.swift new file mode 100644 index 00000000..3bb27a94 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffDelivery.swift @@ -0,0 +1,72 @@ +import Foundation +import MultishellCore + +extension AppModel { + /// A note written to the drops directory and a mention of it pasted into the + /// agent's prompt, with no Return; no file is left where either fails. + func deliverHandoff( + _ document: String, + named fileName: String, + sentence: (String) -> String, + to recipient: HandoffRecipient, + takingFocus: Bool, + ) -> HandoffDelivery { + let file: URL + do { + file = try AgentHandoff.write(document, named: fileName, in: dropsDirectory) + } catch { + present(error) + return .notWritten + } + guard + let mention = handoffMention( + of: file, + prefixed: fileMentionPrefix(ofAgent: recipient.agentID), + sentence: sentence, + ), + host.paste(mention + " ", into: recipient.id) + else { + DropCopies.remove(file.deletingLastPathComponent()) + return .notPasted + } + if takingFocus { + store.focusSession(recipient.id) + reconcileSessions(takingFocus: true) + } + return .delivered + } + + /// A delivery that did not land as the Send's outcome, said over `page`'s foot; + /// `nil` for one that did. + func outcomeNotingMiss( + of delivery: HandoffDelivery, + to recipient: HandoffRecipient, + on page: ServicePage, + in worktreeID: Worktree.ID, + ) -> HandoffSendOutcome? { + switch delivery { + case .delivered: + return nil + + case .notPasted: + noteHandoffMiss(t("handoff.not-pasted", recipient.agentName), on: page, in: worktreeID) + return .notPasted(to: recipient.id) + + case .notWritten: + // Its error is presented already; a note under the alert would say it twice. + return .notWritten + } + } + + /// A mention where the agent reads them, else `sentence` around the path, which + /// alone says nothing. Absolute: the drops directory is outside every worktree. + private func handoffMention( + of file: URL, + prefixed prefix: String?, + sentence: (String) -> String, + ) -> String? { + guard let text = FilePathText.pastedText(for: [file], relativeTo: nil, mentionPrefix: prefix) + else { return nil } + return prefix == nil ? sentence(text) : text + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffFooter.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffFooter.swift new file mode 100644 index 00000000..39d4acb5 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffFooter.swift @@ -0,0 +1,33 @@ +import MultishellCore + +/// What a page's Send foot shows: the picker and Send, the last Send's receipt, +/// or why there is nobody to send to. +extension AppModel { + /// `nil` with nothing to send and nothing sent, so the page draws no foot. What + /// the last Send said stays until an unsent item is checked or none it sent is listed. + func handoffFooter( + on page: ServicePage, + of candidates: [HandoffCandidate], + in worktree: Worktree, + ) -> HandoffFooter? { + let choices = handoff.choices[worktree.id] ?? HandoffChoices() + let canSend = !choices.checked(among: candidates).isEmpty + // A receipt speaks of items still listed; a newer run or push lists others. + let listsASentItem = candidates.contains { choices.state(of: $0).isSent } + if !canSend, listsASentItem, let receipt = handoff.receipts[worktree.id]?[page] { + return .sent(summary: receipt) + } + guard !candidates.isEmpty else { return nil } + return handoffPickerFooter(of: worktree, canSend: canSend) + } + + /// A Send foot's picker and Send, on Review and the PR and CI pages alike, or why + /// there is nobody to send to. + func handoffPickerFooter(of worktree: Worktree, canSend: Bool) -> HandoffFooter { + let recipients = handoffRecipients(in: worktree.id) + guard let picked = handoffRecipient(from: recipients, in: worktree.id) else { + return .noRecipient(t("handoff.no-agent", workspace.displayName(of: worktree))) + } + return .ready(picked: picked, recipients: recipients, canSend: canSend) + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffMisses.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffMisses.swift new file mode 100644 index 00000000..f3b9bf13 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffMisses.swift @@ -0,0 +1,14 @@ +import MultishellCore + +/// Why a page's last Send sent nothing, said over its foot until the next pick or Send. +extension AppModel { + public func handoffMiss(of worktree: Worktree, on page: ServicePage) -> String? { + handoff.misses[worktree.id]?[page] + } + + func noteHandoffMiss(_ text: String?, on page: ServicePage, in worktreeID: Worktree.ID) { + var misses = handoff.misses[worktreeID] ?? [:] + misses[page] = text + setIfChanged(\.handoff.misses[worktreeID], misses.isEmpty ? nil : misses) + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffRecipients.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffRecipients.swift new file mode 100644 index 00000000..de175702 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+HandoffRecipients.swift @@ -0,0 +1,76 @@ +import Foundation +import MultishellCore + +extension AppModel { + /// How many panes a worktree's focus history keeps: the picker needs only the + /// newest agent among them. + private static var focusHistoryLength: Int { 16 } + + /// The worktree's live panes with an agent, working or not, in the board's order. + func handoffRecipients(in worktreeID: Worktree.ID) -> [HandoffRecipient] { + agentBoard.columns.flatMap(\.cards) + .filter { $0.worktreeID == worktreeID } + .compactMap(HandoffRecipient.init(card:)) + } + + /// The pane `id`, while it is the worktree's and has an agent. + func handoffRecipient(id: TerminalSession.ID, in worktreeID: Worktree.ID) -> HandoffRecipient? { + handoffRecipients(in: worktreeID).first { $0.id == id } + } + + /// The pane named, else the one the worktree's picker shows. + func handoffRecipient( + named id: TerminalSession.ID?, + in worktreeID: Worktree.ID, + ) -> HandoffRecipient? { + id.map { handoffRecipient(id: $0, in: worktreeID) } ?? handoffRecipient(in: worktreeID) + } + + /// As `handoffRecipient(named:in:)`, a pane named and gone said over `page`'s foot: + /// it closed after the picker drew. + func handoffRecipientNotingMiss( + named id: TerminalSession.ID?, + on page: ServicePage, + in worktreeID: Worktree.ID, + ) -> HandoffRecipient? { + let recipient = handoffRecipient(named: id, in: worktreeID) + // A pane still open but with no agent, a script's `--to` a shell, closed nothing. + if recipient == nil, let id, workspace.session(id) == nil { + noteHandoffMiss(t("handoff.pane-gone"), on: page, in: worktreeID) + } + return recipient + } + + /// The one picked, else the agent focused last in the worktree, else the first. + func handoffRecipient(in worktreeID: Worktree.ID) -> HandoffRecipient? { + handoffRecipient(from: handoffRecipients(in: worktreeID), in: worktreeID) + } + + func handoffRecipient( + from recipients: [HandoffRecipient], + in worktreeID: Worktree.ID, + ) -> HandoffRecipient? { + let preferred = [handoff.recipientPicks[worktreeID]] + (focusedSessionHistory[worktreeID] ?? []) + for case let id? in preferred { + if let recipient = recipients.first(where: { $0.id == id }) { return recipient } + } + return recipients.first + } + + public func pickHandoffRecipient(_ id: TerminalSession.ID, in worktreeID: Worktree.ID) { + setIfChanged(\.handoff.recipientPicks[worktreeID], id) + setIfChanged(\.handoff.misses[worktreeID], nil) + } + + /// What the reconciler reports as a pane takes focus. + func noteSessionFocused(_ id: TerminalSession.ID) { + guard let worktreeID = workspace.session(id)?.worktreeID else { return } + var history = focusedSessionHistory[worktreeID] ?? [] + history.removeAll { $0 == id } + history.insert(id, at: 0) + setIfChanged( + \.focusedSessionHistory[worktreeID], + Array(history.prefix(Self.focusHistoryLength)), + ) + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+PullRequestHandoff.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+PullRequestHandoff.swift new file mode 100644 index 00000000..fb4fcd39 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+PullRequestHandoff.swift @@ -0,0 +1,240 @@ +import Foundation +import MultishellCore +import MultishellServices + +extension AppModel { + /// What Send carries: the checked items of those read, `nil` checks where + /// `pr send` asked for threads alone. + private func itemsToSend( + of pullRequest: PullRequest, + in worktree: Worktree, + checks: PullRequestChecks?, + threads: [PullRequestThread], + ) -> [PullRequestHandoffItem] { + PullRequestHandoffItem.items( + checks: checks?.checks, + headCommit: checks?.headCommit ?? pullRequest.headCommit, + threads: threads, + ) + .filter { handoffState(of: $0.candidate, in: worktree.id).isChecked } + } + + /// Why a Send with nothing to carry sent nothing: a failed read, said over the + /// foot, checks first, else nothing checked. + private func outcomeSendingNothing( + checks: Result, + threads: Result<[PullRequestThread], ServiceReadFailure>, + integration: ServiceIntegration, + in worktreeID: Worktree.ID, + ) -> HandoffSendOutcome { + if case .failure(let failure) = checks { + let reason = failure.reason(integration: integration) + noteHandoffMiss(t("panel.checks-not-read", reason), on: .pullRequest, in: worktreeID) + return .checksNotRead(reason: reason) + } + if case .failure(let failure) = threads { + let reason = failure.reason(integration: integration) + noteHandoffMiss(t("panel.threads-not-read", reason), on: .pullRequest, in: worktreeID) + return .threadsNotRead(reason: reason) + } + return .nothingChecked + } + + /// What a step lists that Send can carry, from the threads the page read once. + public func mergePathStepItems( + of step: MergePath.Step, + in path: MergePath, + on pullRequest: PullRequest, + threads: [PullRequestThread], + ) -> MergePathStepItems { + MergePathStepItems(of: step, in: path, headCommit: pullRequest.headCommit, threads: threads) + } + + /// A step's hint, and while its list is collapsed how much it would send. + public func mergePathHint( + of step: MergePath.Step, + in path: MergePath, + base: String, + host: String, + items: MergePathStepItems, + isCollapsed: Bool, + in worktreeID: Worktree.ID, + ) -> String? { + let parts = [ + path.hint(of: step, base: base, host: host), + handoffToSendText(of: items.candidates, isCollapsed: isCollapsed, in: worktreeID), + ] + let hint = parts.compactMap(\.self) + return hint.isEmpty ? nil : hint.joined(separator: ". ") + } + + /// `nil` with nothing to send and nothing sent from the page; from the path + /// the page already drew, so its checks are not weighed again. + public func pullRequestHandoffFooter( + of worktree: Worktree, + along path: MergePath, + on pullRequest: PullRequest, + threads: [PullRequestThread], + ) -> HandoffFooter? { + // Claimed before its own reads, so a second click finds Send off rather than nothing. + switch handoff.sendPhases[worktree.id] { + case .readingLogs(let count): return .reading(t("count.reading-logs", count)) + case .preparing: return .reading(t("handoff.preparing")) + case nil: break + } + let items = PullRequestHandoffItem.items( + checks: path.checks, + headCommit: pullRequest.headCommit, + threads: threads, + ) + return handoffFooter(on: .pullRequest, of: items.map(\.candidate), in: worktree) + } + + /// The checked items, failing checks' logs read first, sent to the pane named, + /// else the picker's, or nowhere; see Docs/design/services/send-feedback.md. + @discardableResult + public func sendPullRequestFeedback( + of worktreeID: Worktree.ID, + to sessionID: TerminalSession.ID?, + takingFocus: Bool, + includesChecks: Bool = true, + includesThreads: Bool = true, + ) async -> HandoffSendOutcome { + guard let worktree = workspace.worktree(worktreeID), + let project = workspace.project(worktree.projectID), + let (integration, host) = pullRequestHost(for: project), + case .pullRequest(let pullRequest) = pullRequestPage(of: worktree) + else { return .noPage } + // Each Send says only its own outcome, not the last one's. + noteHandoffMiss(nil, on: .pullRequest, in: worktreeID) + // Claimed before any read, so a second click cannot read the same logs again. + if includesChecks { + guard handoff.sendPhases[worktreeID] == nil else { return .alreadySending } + handoff.sendPhases[worktreeID] = .preparing + } + defer { if includesChecks { handoff.sendPhases[worktreeID] = nil } } + async let checksRead: Result = + includesChecks + ? checksToSend(of: pullRequest, in: worktree, with: host).map(Optional.some) + : .success(nil) + async let threadsRead: Result<[PullRequestThread], ServiceReadFailure> = + includesThreads ? threadsToSend(of: pullRequest, in: worktree, with: host) : .success([]) + let (checks, threads) = await (checksRead, threadsRead) + let items = itemsToSend( + of: pullRequest, + in: worktree, + checks: (try? checks.get()) ?? nil, + threads: (try? threads.get()) ?? [], + ) + guard !items.isEmpty else { + return outcomeSendingNothing( + checks: checks, + threads: threads, + integration: integration, + in: worktreeID, + ) + } + guard + let named = handoffRecipientNotingMiss(named: sessionID, on: .pullRequest, in: worktreeID) + else { + return .noRecipient + } + let logs = await readFailedLogs(of: items, with: host, integration: integration, in: worktree) + // A script's Ctrl-C during the reads means the paste is no longer wanted. + guard !Task.isCancelled else { return .cancelled } + guard let recipient = handoffRecipient(id: named.id, in: worktreeID) else { + noteHandoffMiss( + t("handoff.gone-while-reading", named.agentName), + on: .pullRequest, + in: worktreeID, + ) + return .noRecipient + } + // A box unchecked, or an item sent, while the logs read is the user's last word. + let sending = items.filter { handoffState(of: $0.candidate, in: worktreeID).isChecked } + guard !sending.isEmpty else { return .nothingChecked } + return deliverPullRequestHandoff( + of: sending, + logs: logs, + on: pullRequest, + in: worktree, + to: recipient, + takingFocus: takingFocus, + ) + } + + /// The note written and pasted, then each item marked sent. + private func deliverPullRequestHandoff( + of items: [PullRequestHandoffItem], + logs: [HandoffItemID: CheckLogRead], + on pullRequest: PullRequest, + in worktree: Worktree, + to recipient: HandoffRecipient, + takingFocus: Bool, + ) -> HandoffSendOutcome { + let document = AgentHandoff.document( + introduction: PullRequestHandoff.introduction(number: pullRequest.number), + entries: PullRequestHandoff.entries( + of: items, + logs: logs, + localTip: services(of: worktree).localTip, + ), + ) + let delivery = deliverHandoff( + document, + named: PullRequestHandoff.fileName( + number: pullRequest.number, + worktreeNamed: workspace.displayName(of: worktree), + ), + sentence: { t("handoff.pull-request-sentence", $0) }, + to: recipient, + takingFocus: takingFocus, + ) + if let missed = outcomeNotingMiss( + of: delivery, + to: recipient, + on: .pullRequest, + in: worktree.id, + ) { + return missed + } + markHandoffItemsSent( + items.map(\.candidate.id), + on: .pullRequest, + in: worktree.id, + to: recipient.agentName, + summary: t("handoff.sent-summary", t("count.items", items.count), recipient.agentName), + ) + return .sent(itemCount: items.count, to: recipient) + } + + /// The checked failing checks' logs the host can read, a few at a time; Send is + /// off while they read, and a check from another CI goes without one. + private func readFailedLogs( + of items: [PullRequestHandoffItem], + with host: any PullRequestHost, + integration: ServiceIntegration, + in worktree: Worktree, + ) async -> [HandoffItemID: CheckLogRead] { + let checks = items.compactMap { item -> (HandoffItemID, PullRequestCheck)? in + guard case .check(let check, _) = item, host.readsFailedLog(of: check) else { return nil } + return (item.candidate.id, check) + } + guard !checks.isEmpty else { return [:] } + setIfChanged(\.handoff.sendPhases[worktree.id], .readingLogs(count: checks.count)) + defer { setIfChanged(\.handoff.sendPhases[worktree.id], .preparing) } + let directory = worktree.path + let lineLimit = HandoffLogTail.linesToRead + let logs = await checks.mapConcurrentlyUnordered(width: Self.concurrentServiceReads) { + item -> (HandoffItemID, CheckLogRead) in + let (id, check) = item + do { + let log = try await host.failedLog(of: check, keepingLast: lineLimit, in: directory) + return (id, log.map(CheckLogRead.read) ?? .noLog) + } catch { + return (id, .failed(ServiceReadFailure(error).reason(integration: integration))) + } + } + return Dictionary(logs, uniquingKeysWith: { first, _ in first }) + } +} diff --git a/Sources/MultishellAppCore/Model/Handoff/AppModel+PullRequestHandoffReads.swift b/Sources/MultishellAppCore/Model/Handoff/AppModel+PullRequestHandoffReads.swift new file mode 100644 index 00000000..82d73725 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Handoff/AppModel+PullRequestHandoffReads.swift @@ -0,0 +1,72 @@ +import Foundation +import MultishellCore +import MultishellServices + +/// What a PR page Send reads: on the page, what it read as it went; off it, read +/// at the Send, as nothing keeps it current there. +extension AppModel { + /// The checks a Send carries and the head they ran on: on the PR page, as it + /// read them; off it, read now, the head beside them, as a push moves both. + func checksToSend( + of pullRequest: PullRequest, + in worktree: Worktree, + with host: any PullRequestHost, + ) async -> Result { + if pullRequestPageKeepsPace(of: worktree) { + let reading = checksReading(of: pullRequest, in: worktree) + if reading?.checks == nil, let failure = reading?.failure { return .failure(failure) } + return .success( + PullRequestChecks( + pullRequestNumber: pullRequest.number, + headCommit: pullRequest.headCommit, + checks: reading?.checks, + ) + ) + } + do { + async let checks = host.checks(of: pullRequest, in: worktree.path) + async let head = host.headCommit(of: pullRequest, in: worktree.path) + return .success( + PullRequestChecks( + pullRequestNumber: pullRequest.number, + headCommit: try await head, + checks: try await checks, + ) + ) + } catch { + return .failure(ServiceReadFailure(error)) + } + } + + /// The threads a Send carries: on the PR page, as it read them, its failure where + /// that read failed, none it has yet to show; off it, read now. + func threadsToSend( + of pullRequest: PullRequest, + in worktree: Worktree, + with host: any PullRequestHost, + ) async -> Result<[PullRequestThread], ServiceReadFailure> { + guard !pullRequest.state.isSettled else { return .success([]) } + if pullRequestPageKeepsPace(of: worktree) { + guard let reading = remoteState.threads[worktree.id], + reading.pullRequestNumber == pullRequest.number + else { + // A box nobody has seen is not sent checked. + return .success([]) + } + if let threads = reading.threads { return .success(threads) } + return reading.failure.map { .failure($0) } ?? .success([]) + } + do { + return .success(try await host.unresolvedThreads(of: pullRequest, in: worktree.path)) + } catch { + return .failure(ServiceReadFailure(error)) + } + } + + /// The PR page on the panel for this worktree, with the app frontmost: the one + /// place its reads keep pace, as they pause in the background. + private func pullRequestPageKeepsPace(of worktree: Worktree) -> Bool { + isFilesPanelShowing(.pullRequest) && filesPanelWorktree?.id == worktree.id + && platform.isActive + } +} diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift index 0dce9abf..0e26add3 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift @@ -70,7 +70,7 @@ extension AppModel { } } - /// A removed worktree's review goes with it: comments, file, picks and receipts. + /// A removed worktree's review goes with it: comments, file and receipts. /// Its file stays known, so a quit before the removal lands removes it again. func forgetReviewState(of gone: Set) { for id in gone where reviewFiles[id] != nil { @@ -79,9 +79,7 @@ extension AppModel { for id in gone { worktreesWithReviewFilesRead.remove(id) // A write of nil to a key never set still redraws every file tab. - setIfChanged(\.reviewRecipientPicks[id], nil) setIfChanged(\.reviewSendReceipts[id], nil) - setIfChanged(\.focusedSessionHistory[id], nil) setIfChanged(\.selectedReviewComments[id], nil) } } diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift index 4ba7ba6f..b6640cfd 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift @@ -24,18 +24,14 @@ extension AppModel { ) } - public func reviewFooter(of worktree: Worktree) -> ReviewFooter { + public func reviewFooter(of worktree: Worktree) -> HandoffFooter { let comments = reviewComments(in: worktree.id) let hasPending = comments.contains(where: \.isPending) // Said only while what was sent is still listed: Clear sent or a last Dismiss ends it. if !hasPending, !comments.isEmpty, let receipt = reviewSendReceipts[worktree.id] { - return .sent(receipt) + return .sent(summary: receipt.summary) } - let recipients = reviewRecipients(in: worktree.id) - guard let picked = reviewRecipient(from: recipients, in: worktree.id) else { - return .noRecipient(t("review.no-agent", workspace.displayName(of: worktree))) - } - return .ready(picked: picked, recipients: recipients, canSend: hasPending) + return handoffPickerFooter(of: worktree, canSend: hasPending) } /// A click on a comment's row: its card outlined in the shown All changes tab diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewSend.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewSend.swift index c3e3a81b..8ac67180 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewSend.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewSend.swift @@ -2,49 +2,6 @@ import Foundation import MultishellCore extension AppModel { - /// How many panes a worktree's focus history keeps: the picker needs only the - /// newest agent among them. - private static var focusHistoryLength: Int { 16 } - - /// The worktree's live panes with an agent, working or not, in the board's order. - func reviewRecipients(in worktreeID: Worktree.ID) -> [ReviewRecipient] { - agentBoard.columns.flatMap(\.cards) - .filter { $0.worktreeID == worktreeID } - .compactMap(ReviewRecipient.init(card:)) - } - - /// The one picked, else the agent focused last in the worktree, else the first. - func reviewRecipient(in worktreeID: Worktree.ID) -> ReviewRecipient? { - reviewRecipient(from: reviewRecipients(in: worktreeID), in: worktreeID) - } - - func reviewRecipient( - from recipients: [ReviewRecipient], - in worktreeID: Worktree.ID, - ) -> ReviewRecipient? { - let preferred = [reviewRecipientPicks[worktreeID]] + (focusedSessionHistory[worktreeID] ?? []) - for case let id? in preferred { - if let recipient = recipients.first(where: { $0.id == id }) { return recipient } - } - return recipients.first - } - - public func pickReviewRecipient(_ id: TerminalSession.ID, in worktreeID: Worktree.ID) { - setIfChanged(\.reviewRecipientPicks[worktreeID], id) - } - - /// What the reconciler reports as a pane takes focus. - func noteSessionFocused(_ id: TerminalSession.ID) { - guard let worktreeID = workspace.session(id)?.worktreeID else { return } - var history = focusedSessionHistory[worktreeID] ?? [] - history.removeAll { $0 == id } - history.insert(id, at: 0) - setIfChanged( - \.focusedSessionHistory[worktreeID], - Array(history.prefix(Self.focusHistoryLength)), - ) - } - /// Every pending comment written to one file, mentioned in the agent's prompt, /// then marked sent; nothing is marked where any step fails. The pane named, /// never another: Send's picker showed it, and a script named it. @@ -56,29 +13,20 @@ extension AppModel { ) -> Bool { let pending = reviewComments(in: worktreeID).filter(\.isPending) guard !pending.isEmpty, let worktree = workspace.worktree(worktreeID), - let recipient = reviewRecipients(in: worktreeID).first(where: { $0.id == sessionID }) + let recipient = handoffRecipient(id: sessionID, in: worktreeID) else { return false } - let mentionPrefix = fileMentionPrefix(ofAgent: recipient.agentID) - let file: URL - do { - file = try AgentHandoff.write( + guard + deliverHandoff( AgentHandoff.document( introduction: ReviewHandoff.introduction, entries: ReviewHandoff.entries(of: pending), ), named: ReviewHandoff.fileName(forWorktreeNamed: workspace.displayName(of: worktree)), - in: dropsDirectory, - ) - } catch { - present(error) - return false - } - guard let mention = handoffMention(of: file, prefixed: mentionPrefix), - host.paste(mention + " ", into: sessionID) - else { - DropCopies.remove(file.deletingLastPathComponent()) - return false - } + sentence: { t("review.handoff-sentence", $0) }, + to: recipient, + takingFocus: takingFocus, + ) == .delivered + else { return false } markReviewCommentsSent( Set(pending.map(\.id)), in: worktreeID, @@ -89,18 +37,6 @@ extension AppModel { count: pending.count, agentName: recipient.agentName, ) - if takingFocus { - store.focusSession(sessionID) - reconcileSessions(takingFocus: true) - } return true } - - /// A mention where the agent reads them, else a sentence around the path, which - /// alone says nothing. Absolute: the drops directory is outside every worktree. - private func handoffMention(of file: URL, prefixed prefix: String?) -> String? { - guard let text = FilePathText.pastedText(for: [file], relativeTo: nil, mentionPrefix: prefix) - else { return nil } - return prefix == nil ? t("review.handoff-sentence", text) : text - } } diff --git a/Sources/MultishellAppCore/Model/Services/AppModel+PanelServiceReads.swift b/Sources/MultishellAppCore/Model/Services/AppModel+PanelServiceReads.swift index f8e2c46b..5333193b 100644 --- a/Sources/MultishellAppCore/Model/Services/AppModel+PanelServiceReads.swift +++ b/Sources/MultishellAppCore/Model/Services/AppModel+PanelServiceReads.swift @@ -21,6 +21,10 @@ extension AppModel { \.remoteState.checks, remoteState.checks.filter { !withoutHost.contains($0.key) }, ) + setIfChanged( + \.remoteState.threads, + remoteState.threads.filter { !withoutHost.contains($0.key) }, + ) setIfChanged( \.remoteState.pendingMerges, remoteState.pendingMerges.filter { !withoutHost.contains($0.key) }, @@ -54,6 +58,7 @@ extension AppModel { guard !Task.isCancelled, let self else { return } remoteState.pendingPanelRead = nil pruneRunDetails() + prunePanelThreads() guard let worktree = workspace.worktree(id) else { return } await readPanelServicesIfDue(of: worktree) } @@ -84,7 +89,11 @@ extension AppModel { pruneRunDetails() let changesBefore = remoteState.integrationChanges[worktree.projectID] switch page { - case .pullRequest: await readChecks(of: worktree) + case .pullRequest: + async let checks: Void = readChecks(of: worktree) + async let threads: Void = readThreads(of: worktree) + _ = await (checks, threads) + case .ciRuns: await readCIHistory(of: worktree) case .files, .changes, .review: break } @@ -92,6 +101,9 @@ extension AppModel { remoteState.panelReadLog.markDue(read) return false } + if let servicePage = ServicePage(page) { + pruneHandoffChoices(of: worktree, after: servicePage) + } return true } @@ -147,6 +159,43 @@ extension AppModel { if headMovedPastTheList { Task { await refreshServices(ofProject: project.id) } } } + /// Thread text is kept for the panel's worktree alone, whatever page it shows. + private func prunePanelThreads() { + let panel = filesPanelWorktree?.id + setIfChanged(\.remoteState.threads, remoteState.threads.filter { $0.key == panel }) + } + + /// An open pull request's unresolved threads; a settled one lists none, and + /// other worktrees' are dropped, thread text being kept for the panel's alone. + private func readThreads(of worktree: Worktree) async { + prunePanelThreads() + guard let project = workspace.project(worktree.projectID), + let (integration, host) = pullRequestHost(for: project), + let pullRequest = services(of: worktree).shownPullRequest, + !pullRequest.state.isSettled + else { + setIfChanged(\.remoteState.threads[worktree.id], nil) + return + } + var reading = + remoteState.threads[worktree.id].flatMap { reading in + reading.pullRequestNumber == pullRequest.number ? reading : nil + } ?? PullRequestThreads(pullRequestNumber: pullRequest.number) + let changesBefore = remoteState.integrationChanges[project.id] + do { + reading.threads = try await host.unresolvedThreads(of: pullRequest, in: worktree.path) + reading.failure = nil + } catch { + reading.failure = ServiceReadFailure(error) + } + // Thread text is kept for the panel's worktree alone, which may have moved on. + guard workspace.worktree(worktree.id) != nil, filesPanelWorktree?.id == worktree.id, + pullRequestHost(for: project)?.0 == integration, + remoteState.integrationChanges[project.id] == changesBefore + else { return } + setIfChanged(\.remoteState.threads[worktree.id], reading) + } + private func readCIHistory(of worktree: Worktree) async { // Taken before any await, the provider chosen below among them. let changesBefore = remoteState.integrationChanges[worktree.projectID] @@ -213,10 +262,12 @@ extension AppModel { let services = services(of: worktree) switch shownFilesPanelMode { case .pullRequest: - // Another pull request on the same head has checks of its own. + // Another pull request on the same head has checks of its own; another + // worktree's read dropped this one's threads. let checks = remoteState.checks[worktree.id] return services.shownPullRequest?.headCommit != checks?.headCommit || services.shownPullRequest?.number != checks?.pullRequestNumber + || lacksThreads(services.shownPullRequest, of: worktree) case .ciRuns: // A history of the branch it followed before is no history at all, where @@ -229,6 +280,12 @@ extension AppModel { } } + /// An open pull request whose threads were never read, or were dropped. + private func lacksThreads(_ pullRequest: PullRequest?, of worktree: Worktree) -> Bool { + guard let pullRequest, !pullRequest.state.isSettled else { return false } + return remoteState.threads[worktree.id]?.pullRequestNumber != pullRequest.number + } + private func panelHasSomethingUnderWay(_ worktree: Worktree) -> Bool { switch shownFilesPanelMode { case .pullRequest: diff --git a/Sources/MultishellAppCore/Model/Services/AppModel+PullRequestActions.swift b/Sources/MultishellAppCore/Model/Services/AppModel+PullRequestActions.swift index 037bea50..b82c7009 100644 --- a/Sources/MultishellAppCore/Model/Services/AppModel+PullRequestActions.swift +++ b/Sources/MultishellAppCore/Model/Services/AppModel+PullRequestActions.swift @@ -44,6 +44,11 @@ extension AppModel { platform.openWebPage(page) } + public func openThread(_ thread: PullRequestThread) { + guard let page = thread.webPage else { return } + platform.openWebPage(page) + } + /// The host's new pull request page against the trunk. A branch the remote /// lacks, or commits it lacks, is asked about first; see services/create-and-merge.md. public func createPullRequest(for worktree: Worktree) async { diff --git a/Sources/MultishellAppCore/Model/Services/AppModel+ServicePages.swift b/Sources/MultishellAppCore/Model/Services/AppModel+ServicePages.swift index 98f0a6e3..d2c9f90a 100644 --- a/Sources/MultishellAppCore/Model/Services/AppModel+ServicePages.swift +++ b/Sources/MultishellAppCore/Model/Services/AppModel+ServicePages.swift @@ -71,7 +71,7 @@ extension AppModel { } /// An earlier head's checks, or their failed read, say nothing of this one's. - private func checksReading( + func checksReading( of pullRequest: PullRequest, in worktree: Worktree, ) -> PullRequestChecks? { @@ -91,9 +91,33 @@ extension AppModel { isMergeTaken: isMergeTaken(in: worktree), isOutgrown: services(of: worktree).outgrownPullRequest?.url == pullRequest.url, checksReadProblem: checksReadProblem(of: pullRequest, in: worktree), + unresolvedThreadCount: unresolvedThreads(of: pullRequest, in: worktree).count, ) } + /// The shown pull request's unresolved threads, oldest first, as last read; a + /// merged or closed one lists none, though a read before it settled is kept. + public func unresolvedThreads( + of pullRequest: PullRequest, + in worktree: Worktree, + ) -> [PullRequestThread] { + guard !pullRequest.state.isSettled, let reading = remoteState.threads[worktree.id], + reading.pullRequestNumber == pullRequest.number + else { return [] } + return reading.threads ?? [] + } + + /// Why the threads' last read failed, said under the card until one answers; a + /// merged or closed pull request lists no threads, so says nothing of them. + public func threadsReadProblem(of pullRequest: PullRequest, in worktree: Worktree) -> String? { + guard !pullRequest.state.isSettled, let reading = remoteState.threads[worktree.id], + reading.pullRequestNumber == pullRequest.number, let failure = reading.failure, + let project = workspace.project(worktree.projectID), + let (integration, _) = pullRequestHost(for: project) + else { return nil } + return t("panel.threads-not-read", failure.reason(integration: integration)) + } + private func checksReadProblem(of pullRequest: PullRequest, in worktree: Worktree) -> String? { guard let failure = checksReading(of: pullRequest, in: worktree)?.failure, let project = workspace.project(worktree.projectID), diff --git a/Sources/MultishellAppCore/Model/Services/AppModel+ServiceStandIn.swift b/Sources/MultishellAppCore/Model/Services/AppModel+ServiceStandIn.swift index 228eb1fb..c459c26a 100644 --- a/Sources/MultishellAppCore/Model/Services/AppModel+ServiceStandIn.swift +++ b/Sources/MultishellAppCore/Model/Services/AppModel+ServiceStandIn.swift @@ -20,6 +20,7 @@ extension AppModel { recomputeWorktreeServices(ofProject: id) } setIfChanged(\.remoteState.checks, [:]) + setIfChanged(\.remoteState.threads, [:]) setIfChanged(\.remoteState.ciHistories, [:]) pruneRunDetails() // Its own reads below cover what turns readable, which would read it twice. diff --git a/Sources/MultishellAppCore/Model/Worktrees/AppModel+ForgetWorktrees.swift b/Sources/MultishellAppCore/Model/Worktrees/AppModel+ForgetWorktrees.swift index 94083e3a..67e427d0 100644 --- a/Sources/MultishellAppCore/Model/Worktrees/AppModel+ForgetWorktrees.swift +++ b/Sources/MultishellAppCore/Model/Worktrees/AppModel+ForgetWorktrees.swift @@ -20,6 +20,7 @@ extension AppModel { remoteState.publishingWorktrees.subtracting(gone), ) setIfChanged(\.remoteState.checks, remoteState.checks.filter { !gone.contains($0.key) }) + setIfChanged(\.remoteState.threads, remoteState.threads.filter { !gone.contains($0.key) }) setIfChanged( \.remoteState.ciHistories, remoteState.ciHistories.filter { !gone.contains($0.key) }, @@ -48,6 +49,7 @@ extension AppModel { filesPanelStates[id] = nil } forgetReviewState(of: gone) + forgetHandoffState(of: gone) forgetFileListings(where: gone.contains) panelFolderReads.cancel { gone.contains($0.worktreeID) } setIfChanged(\.submoduleReadings, submoduleReadings.filter { !gone.contains($0.key) }) diff --git a/Sources/MultishellAppCore/Services/CI/CIHandoff.swift b/Sources/MultishellAppCore/Services/CI/CIHandoff.swift new file mode 100644 index 00000000..464f93c5 --- /dev/null +++ b/Sources/MultishellAppCore/Services/CI/CIHandoff.swift @@ -0,0 +1,53 @@ +import Foundation +import MultishellCore +import MultishellServices + +/// What the CI page's Send writes for the agent: the checked failures of the +/// newest run as one note; see Docs/design/services/send-feedback.md. +enum CIHandoff { + static func introduction(provider: String) -> String { + t("handoff.ci-introduction", provider) + } + + /// A `localTip` other than the run's commit is said, without guessing which is ahead. + static func entries( + of items: [CIHandoffItem], + run: CIRun, + provider: String, + localTip: String?, + ) -> [AgentHandoffEntry] { + let ranElsewhere = localTip.map { !run.ran($0) } ?? false + return items.map { item in + let tail = item.excerpt.map(HandoffLogTail.lines(of:)) + let caveats = [ + ranElsewhere ? t("handoff.ran-on-other-commit", run.shortCommit) : nil, + tail == nil ? reportMissing(of: item) : nil, + (tail?.cutCount ?? 0) > 0 ? t("handoff.earlier-lines-cut", tail?.cutCount ?? 0) : nil, + ] + .compactMap(\.self) + return AgentHandoffEntry( + heading: item.heading, + caveat: caveats.isEmpty ? nil : caveats.joined(separator: " "), + quote: tail?.lines ?? [], + text: text(of: item, provider: provider), + ) + } + } + + static func fileName(forWorktreeNamed name: String) -> String { + AgentHandoff.fileName("ci", forWorktreeNamed: name) + } + + /// A run still going reads its report once it ends; an ended one's was read, + /// naming no job here, or never was. + private static func reportMissing(of item: CIHandoffItem) -> String { + if item.awaitsReport { return t("handoff.ci-report-unread") } + return item.isReportRead ? t("handoff.ci-report-silent") : t("handoff.ci-report-not-read") + } + + private static func text(of item: CIHandoffItem, provider: String) -> String { + guard let job = item.job else { return t("handoff.ci-run-output-text", provider) } + return job.id.map { t("handoff.ci-job-text-with-id", provider, $0) } + ?? t("handoff.ci-job-text", provider) + } +} diff --git a/Sources/MultishellAppCore/Services/CI/CIHandoffItem.swift b/Sources/MultishellAppCore/Services/CI/CIHandoffItem.swift new file mode 100644 index 00000000..7dcc470f --- /dev/null +++ b/Sources/MultishellAppCore/Services/CI/CIHandoffItem.swift @@ -0,0 +1,74 @@ +import MultishellCore +import MultishellServices + +/// What the CI page can send of its newest run: each failed job, and the report's +/// text no listed job holds; see Docs/design/services/send-feedback.md. +public struct CIHandoffItem: Hashable, Sendable { + public let candidate: HandoffCandidate + /// `nil` for the report's text that names no listed job. + let workflow: String? + let job: CIJob? + /// `nil` until the report is read, which waits for the run to end. + let excerpt: String? + /// "build / test", or "Run output" for the text no job holds. + public var heading: String { + guard let workflow, let job else { return t("handoff.run-output") } + return "\(workflow) / \(job.name)" + } + + /// A job failed while its run still goes: its report is read once it ends. + public var awaitsReport: Bool { excerpt == nil && !isRunFinished } + private let isRunFinished: Bool + /// Whether the run's report was read: one read that names no job here differs + /// from one never read, a cancelled run's or a failed read. + let isReportRead: Bool + /// Where the page lists it, two workflows being able to share a name; `nil` + /// for the report's text that names no listed job. + let position: CIJobPosition? + + /// In the page's order: the failed jobs, and any the report speaks of, then + /// the report's `unplaced` text, which can be the only failure, a config error. + static func items( + of run: CIRun, + workflows: [CIWorkflow], + report: CIFailureReport?, + unplaced: [String], + ) -> [Self] { + guard run.status != .passed else { return [] } + var items: [Self] = workflows.enumerated().flatMap { workflowIndex, workflow in + workflow.jobs.enumerated().compactMap { jobIndex, job -> Self? in + let excerpt = report?.excerpt(ofJob: job.name, inWorkflow: workflow.name) + // A job the report speaks of shows its text under its row, so it can be sent + // whatever unclear status it has; one that passed shares a failed one's names. + guard job.status == .failed || (excerpt != nil && job.status != .passed) else { + return nil + } + let position = CIJobPosition(workflow: workflowIndex, job: jobIndex) + return Self( + candidate: HandoffCandidate(.ciJob(runID: run.id, position: position, jobID: job.id)), + workflow: workflow.name, + job: job, + excerpt: excerpt, + isRunFinished: run.isFinished, + isReportRead: report != nil, + position: position, + ) + } + } + if !unplaced.isEmpty { + let text = unplaced.joined(separator: "\n\n") + items.append( + Self( + candidate: HandoffCandidate(.ciRunOutput(runID: run.id, textHash: text.hashValue)), + workflow: nil, + job: nil, + excerpt: text, + isRunFinished: run.isFinished, + isReportRead: true, + position: nil, + ) + ) + } + return items + } +} diff --git a/Sources/MultishellAppCore/Services/CI/CIJobPosition.swift b/Sources/MultishellAppCore/Services/CI/CIJobPosition.swift new file mode 100644 index 00000000..be057333 --- /dev/null +++ b/Sources/MultishellAppCore/Services/CI/CIJobPosition.swift @@ -0,0 +1,10 @@ +/// A job's place on the CI page: its workflow's index in the run, then its own. +public struct CIJobPosition: Hashable, Sendable { + let workflow: Int + let job: Int + + public init(workflow: Int, job: Int) { + self.workflow = workflow + self.job = job + } +} diff --git a/Sources/MultishellAppCore/Services/CI/CIWorkflowListing.swift b/Sources/MultishellAppCore/Services/CI/CIWorkflowListing.swift new file mode 100644 index 00000000..8991a77d --- /dev/null +++ b/Sources/MultishellAppCore/Services/CI/CIWorkflowListing.swift @@ -0,0 +1,58 @@ +import MultishellServices + +/// What the CI page lists of a run: its workflows, each job's report text and, +/// on the newest run, what Send can carry; see Docs/design/services/send-feedback.md. +public struct CIWorkflowListing: Equatable, Sendable { + public let workflows: [CIWorkflow] + /// The newest run's; none for an earlier run, which is history. + let items: [CIHandoffItem] + /// The report's text no listed job holds, shown after the workflows. + public let unplacedExcerpts: [String] + private let report: CIFailureReport? + + /// What the Latest run's checkbox and the foot cover. + public var candidates: [HandoffCandidate] { items.map(\.candidate) } + + /// Every job row keeps the trailing slot while any job can be sent. + public var showsHandoffSlot: Bool { items.contains { $0.position != nil } } + + /// The report's text that names no listed job, where it can be sent. + public var runOutput: CIHandoffItem? { items.first { $0.position == nil } } + + /// Only the newest run's failures can be sent: earlier runs are history. + init(run: CIRun, workflows: [CIWorkflow], report: CIFailureReport?, sendsFailures: Bool) { + let unplaced = report?.unplaced(among: workflows) ?? [] + self.init( + workflows: workflows, + report: report, + items: sendsFailures + ? CIHandoffItem.items(of: run, workflows: workflows, report: report, unplaced: unplaced) + : [], + unplacedExcerpts: unplaced, + ) + } + + private init( + workflows: [CIWorkflow], + report: CIFailureReport?, + items: [CIHandoffItem], + unplacedExcerpts: [String], + ) { + self.workflows = workflows + self.report = report + self.items = items + self.unplacedExcerpts = unplacedExcerpts + } + + /// The job at `position` that can be sent, `nil` for one that cannot. + public func item(at position: CIJobPosition) -> CIHandoffItem? { + items.first { $0.position == position } + } + + /// What the report says of the job at `position`. + public func excerpt(ofJobAt position: CIJobPosition) -> String? { + if let item = item(at: position) { return item.excerpt } + let workflow = workflows[position.workflow] + return report?.excerpt(ofJob: workflow.jobs[position.job].name, inWorkflow: workflow.name) + } +} diff --git a/Sources/MultishellAppCore/Services/Merge/MergePath+Wording.swift b/Sources/MultishellAppCore/Services/Merge/MergePath+Wording.swift index f305aa69..3aef5c1c 100644 --- a/Sources/MultishellAppCore/Services/Merge/MergePath+Wording.swift +++ b/Sources/MultishellAppCore/Services/Merge/MergePath+Wording.swift @@ -66,6 +66,7 @@ extension MergePath { case .blockedByRules: t("merge-path.rule", base) case .checks: t("merge-path.checks") case .checksNotRead: checksNotReadTitle + case .comments: t("merge-path.comments") case .conflicts: Self.conflictsTitle(step.status, base: base) case .draft: t("readiness.draft") case .review: Self.reviewTitle(step.status) @@ -80,12 +81,24 @@ extension MergePath { case .blockedByRules: t("merge-path.rule-hint", host) case .checks: checks.map(Self.summary(of:)) case .checksNotRead: checksReadProblem.map { t("merge-path.read-again", $0) } + case .comments: t("count.merge-path-unresolved", unresolvedThreadCount) case .conflicts: step.status == .failed ? t("merge-path.merge-base", base) : nil case .draft: t("merge-path.draft-hint", host) - case .review: step.status == .onHold ? t("merge-path.review-hint") : nil + case .review: reviewHint(step.status) } } + /// A person's wait, then the threads listed under it. + private func reviewHint(_ status: CIRunStatus) -> String? { + let parts = [ + status == .onHold ? t("merge-path.review-hint") : nil, + threadsStep == .review + ? t("count.merge-path-unresolved-comments", unresolvedThreadCount) : nil, + ] + .compactMap(\.self) + return parts.isEmpty ? nil : parts.joined(separator: ". ") + } + public func endTitle(base: String) -> String { switch end { case .closed: t("pull-request.closed") diff --git a/Sources/MultishellAppCore/Services/Merge/MergePath.swift b/Sources/MultishellAppCore/Services/Merge/MergePath.swift index 88d01225..d17f02e1 100644 --- a/Sources/MultishellAppCore/Services/Merge/MergePath.swift +++ b/Sources/MultishellAppCore/Services/Merge/MergePath.swift @@ -10,6 +10,8 @@ public struct MergePath: Equatable, Sendable { case checks /// Being read, or the read failed with none read before it. case checksNotRead + /// Unresolved review threads where no review step holds them. + case comments case conflicts case draft case review @@ -45,6 +47,15 @@ public struct MergePath: Equatable, Sendable { public let end: End /// Why the checks' last read failed. let checksReadProblem: String? + /// An open pull request's unresolved review threads, listed under the review + /// step or a Comments step of their own; a settled one lists none. + let unresolvedThreadCount: Int + + /// The step the threads list under: the review's, else Comments. + var threadsStep: Step.Kind? { + guard unresolvedThreadCount > 0 else { return nil } + return steps.contains { $0.kind == .review } ? .review : .comments + } init( _ pullRequest: PullRequest, @@ -52,11 +63,14 @@ public struct MergePath: Equatable, Sendable { isMergeTaken: Bool, isOutgrown: Bool, checksReadProblem: String?, + unresolvedThreadCount: Int = 0, ) { - let steps = Self.steps(of: pullRequest, readiness: readiness) + let threads = pullRequest.state.isSettled ? 0 : unresolvedThreadCount + let steps = Self.steps(of: pullRequest, readiness: readiness, unresolvedThreads: threads) self.steps = steps checks = readiness.checks self.checksReadProblem = checksReadProblem + self.unresolvedThreadCount = threads end = switch pullRequest.state { case .closed: .closed @@ -74,7 +88,11 @@ public struct MergePath: Equatable, Sendable { } } - private static func steps(of pullRequest: PullRequest, readiness: MergeReadiness) -> [Step] { + private static func steps( + of pullRequest: PullRequest, + readiness: MergeReadiness, + unresolvedThreads: Int, + ) -> [Step] { var steps: [Step] = [] // A merged or closed one has nothing left to merge, though GitHub still // answers it BLOCKED or BEHIND, and its conflicts UNKNOWN for good. @@ -91,6 +109,8 @@ public struct MergePath: Equatable, Sendable { } if let review = reviewStatus(of: pullRequest) { steps.append(Step(kind: .review, status: review)) + } else if unresolvedThreads > 0 { + steps.append(Step(kind: .comments, status: .unknown)) } if isOpen, readiness.blockers.contains(.blockedByRules) { steps.append(Step(kind: .blockedByRules, status: .failed)) @@ -121,8 +141,9 @@ public struct MergePath: Equatable, Sendable { } private static func wait(readiness: MergeReadiness, steps: [Step]) -> Wait { - // Machines alone holding it back would offer Merge When Ready, so the only - // machine wait left here is Multishell's read of the checks. - readiness.awaitsChecksRead ? .checksRead : .steps(steps.count { $0.status != .passed }) + // Only Multishell's checks read is a machine wait here: machines alone would + // offer Merge When Ready. Threads hold no merge back, so are not counted. + readiness.awaitsChecksRead + ? .checksRead : .steps(steps.count { $0.status != .passed && $0.kind != .comments }) } } diff --git a/Sources/MultishellAppCore/Services/Merge/MergePathStepItems.swift b/Sources/MultishellAppCore/Services/Merge/MergePathStepItems.swift new file mode 100644 index 00000000..8b87d6b7 --- /dev/null +++ b/Sources/MultishellAppCore/Services/Merge/MergePathStepItems.swift @@ -0,0 +1,68 @@ +import MultishellCore +import MultishellServices + +/// What one merge path step lists that Send can carry: the checks step its +/// failing checks, the step holding the threads each thread. +public struct MergePathStepItems: Equatable, Sendable { + /// The list under a step, which its title collapses. + public enum CollapsibleList: Equatable, Sendable { + case checks + case threads + } + + /// Each failing check's, a passing one having none. + public let checkCandidates: [PullRequestCheck: HandoffCandidate] + public let threads: [PullRequestThread] + /// Every item's in the order the step lists them, which its own checkbox covers. + public let candidates: [HandoffCandidate] + /// `nil` for a step with no list under it. + public let collapsibleList: CollapsibleList? + /// By thread id. + private let threadCandidates: [String: HandoffCandidate] + + /// What the step's own checkbox sends, which its title, a status, does not say. + public var sendAllLabel: String { + collapsibleList == .threads ? t("handoff.send-all-threads") : t("handoff.send-all-checks") + } + + /// Whether every check row keeps the trailing slot, so the Required tags line up. + public var showsCheckSlot: Bool { !checkCandidates.isEmpty } + + /// `threads` is the pull request's, listed only where `step` holds them; which + /// checks are sendable is `PullRequestHandoffItem.items`'s rule, as the foot's. + init( + of step: MergePath.Step, + in path: MergePath, + headCommit: String, + threads: [PullRequestThread], + ) { + let items = PullRequestHandoffItem.items( + checks: step.kind == .checks ? path.checks : nil, + headCommit: headCommit, + threads: path.threadsStep == step.kind ? threads : [], + ) + var checkCandidates: [PullRequestCheck: HandoffCandidate] = [:] + var threadCandidates: [String: HandoffCandidate] = [:] + var listedThreads: [PullRequestThread] = [] + for item in items { + switch item { + case .check(let check, _): + checkCandidates[check] = item.candidate + + case .thread(let thread): + threadCandidates[thread.id] = item.candidate + listedThreads.append(thread) + } + } + self.checkCandidates = checkCandidates + self.threadCandidates = threadCandidates + self.threads = listedThreads + candidates = items.map(\.candidate) + collapsibleList = + if step.kind == .checks { .checks } else if !listedThreads.isEmpty { .threads } else { nil } + } + + public func candidate(of thread: PullRequestThread) -> HandoffCandidate? { + threadCandidates[thread.id] + } +} diff --git a/Sources/MultishellAppCore/Services/PullRequests/CheckLogRead.swift b/Sources/MultishellAppCore/Services/PullRequests/CheckLogRead.swift new file mode 100644 index 00000000..b575e947 --- /dev/null +++ b/Sources/MultishellAppCore/Services/PullRequests/CheckLogRead.swift @@ -0,0 +1,10 @@ +import MultishellServices + +/// What Send read of a failing check's log. +enum CheckLogRead: Equatable, Sendable { + /// The tool's words for why it could not read it. + case failed(String) + /// A check from another CI, which the host's tool has no log of. + case noLog + case read(FailedCheckLog) +} diff --git a/Sources/MultishellAppCore/Services/PullRequests/PullRequestCheck+WebPage.swift b/Sources/MultishellAppCore/Services/PullRequests/PullRequestCheck+WebPage.swift index a52bc010..57b869d5 100644 --- a/Sources/MultishellAppCore/Services/PullRequests/PullRequestCheck+WebPage.swift +++ b/Sources/MultishellAppCore/Services/PullRequests/PullRequestCheck+WebPage.swift @@ -4,8 +4,5 @@ import MultishellServices extension PullRequestCheck { /// The check's own page where its host gave a web link; any other scheme is /// never opened, and its row is no button. - public var webPage: URL? { - guard let link, ["http", "https"].contains(link.scheme?.lowercased()) else { return nil } - return link - } + public var webPage: URL? { link?.asWebPage } } diff --git a/Sources/MultishellAppCore/Services/PullRequests/PullRequestChecks.swift b/Sources/MultishellAppCore/Services/PullRequests/PullRequestChecks.swift index f0d6b1ce..80cf7231 100644 --- a/Sources/MultishellAppCore/Services/PullRequests/PullRequestChecks.swift +++ b/Sources/MultishellAppCore/Services/PullRequests/PullRequestChecks.swift @@ -1,7 +1,7 @@ import MultishellServices -/// The checks on a pull request's head, read while the panel shows it. -/// Runtime only; see Docs/design/services/marks-and-pages.md. +/// The checks on a pull request's head, read while the panel shows it, or at a +/// Send off its page. Runtime only; see Docs/design/services/marks-and-pages.md. struct PullRequestChecks: Equatable, Sendable { let pullRequestNumber: Int /// The head they were last asked about, answered or not: a push moves it, diff --git a/Sources/MultishellAppCore/Services/PullRequests/PullRequestHandoff.swift b/Sources/MultishellAppCore/Services/PullRequests/PullRequestHandoff.swift new file mode 100644 index 00000000..710d3608 --- /dev/null +++ b/Sources/MultishellAppCore/Services/PullRequests/PullRequestHandoff.swift @@ -0,0 +1,101 @@ +import Foundation +import MultishellCore +import MultishellServices + +/// What the PR page's Send writes: checked failing checks with their logs' tails, +/// then checked threads; see Docs/design/services/send-feedback.md. +enum PullRequestHandoff { + /// A comment's diff ends at its line; the lines just above it place it. + private static var hunkLineCount: Int { 8 } + + static func introduction(number: Int) -> String { + t("handoff.pull-request-introduction", number) + } + + static func fileName(number: Int, worktreeNamed name: String) -> String { + AgentHandoff.fileName("pr-\(number)", forWorktreeNamed: name) + } + + /// `logs` by item, a failed read's words in place of one; a `localTip` other + /// than the head the checks ran on is said, without guessing which is ahead. + static func entries( + of items: [PullRequestHandoffItem], + logs: [HandoffItemID: CheckLogRead], + localTip: String?, + ) -> [AgentHandoffEntry] { + items.map { item in + switch item { + case .check(let check, let head): + entry( + of: check, + head: head, + log: logs[item.candidate.id] ?? .noLog, + localTip: localTip, + ) + + case .thread(let thread): + entry(of: thread) + } + } + } + + private static func entry( + of check: PullRequestCheck, + head: String, + log: CheckLogRead, + localTip: String?, + ) -> AgentHandoffEntry { + let ranElsewhere = localTip.map { !$0.namesSameCommit(as: head) } ?? false + var caveats: [String] = [] + if ranElsewhere { caveats.append(t("handoff.ran-on-other-commit", head.abbreviatedCommit)) } + var quote: [String] = [] + switch log { + case .read(let log): + let tail = HandoffLogTail.lines(of: log.text) + quote = tail.lines + let cutCount = log.earlierLineCount + tail.cutCount + if cutCount > 0 { caveats.append(t("handoff.earlier-lines-cut", cutCount)) } + if tail.lines.isEmpty { caveats.append(t("handoff.log-empty")) } + + case .noLog: + break + + case .failed(let reason): + caveats.append(t("handoff.log-not-read", reason)) + } + let text = + check.link.map { t("handoff.check-text", $0.absoluteString) } + ?? t("handoff.check-text-no-link") + return AgentHandoffEntry( + heading: check.displayName, + caveat: caveats.isEmpty ? nil : caveats.joined(separator: " "), + quote: quote, + text: text, + ) + } + + private static func entry(of thread: PullRequestThread) -> AgentHandoffEntry { + let comments = thread.comments.map { comment in + t("handoff.thread-comment", comment.author ?? t("handoff.thread-ghost"), comment.body) + } + let link = thread.webPage.map { t("handoff.thread-link", $0.absoluteString) } + return AgentHandoffEntry( + heading: thread.placeLabel, + caveat: thread.isOutdated ? t("handoff.thread-outdated") : nil, + quote: hunkLines(of: thread), + text: (comments + [link].compactMap(\.self)).joined(separator: "\n\n"), + ) + } + + /// The end of the hunk the thread was written on; a comment on a whole file has none. + private static func hunkLines(of thread: PullRequestThread) -> [String] { + guard !thread.diffHunk.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return [] + } + return Array( + thread.diffHunk.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) + .map(String.init) + .suffix(hunkLineCount) + ) + } +} diff --git a/Sources/MultishellAppCore/Services/PullRequests/PullRequestHandoffItem.swift b/Sources/MultishellAppCore/Services/PullRequests/PullRequestHandoffItem.swift new file mode 100644 index 00000000..549d2a76 --- /dev/null +++ b/Sources/MultishellAppCore/Services/PullRequests/PullRequestHandoffItem.swift @@ -0,0 +1,37 @@ +import Foundation +import MultishellServices + +/// What the PR page can send: a failing check, or an unresolved review thread; +/// see Docs/design/services/send-feedback.md. +enum PullRequestHandoffItem: Hashable, Sendable { + /// With the head its checks were read at, a link outliving a push. + case check(PullRequestCheck, headCommit: String) + case thread(PullRequestThread) + + /// A failing required check starts checked, an optional one unchecked; a + /// thread checked. A rerun, a push or a new comment makes a new item. + var candidate: HandoffCandidate { + switch self { + case .check(let check, let head): + HandoffCandidate( + .check(name: check.displayName, link: check.link, headCommit: head), + startsChecked: check.isRequired, + ) + + case .thread(let thread): + HandoffCandidate( + .thread(id: thread.id, newestCommentID: thread.comments.last?.id ?? thread.id) + ) + } + } + + /// The failing checks in the host's order, then the threads oldest first. + static func items( + checks: [PullRequestCheck]?, + headCommit: String, + threads: [PullRequestThread], + ) -> [Self] { + (checks ?? []).filter { $0.status == .failed }.map { .check($0, headCommit: headCommit) } + + threads.map(Self.thread) + } +} diff --git a/Sources/MultishellAppCore/Services/PullRequests/PullRequestThread+Wording.swift b/Sources/MultishellAppCore/Services/PullRequests/PullRequestThread+Wording.swift new file mode 100644 index 00000000..9fcd5821 --- /dev/null +++ b/Sources/MultishellAppCore/Services/PullRequests/PullRequestThread+Wording.swift @@ -0,0 +1,17 @@ +import Foundation +import MultishellCore +import MultishellServices + +extension PullRequestThread { + /// "Sources/App.swift:12", an outdated one by the line it was written on, + /// one on the whole file by its path alone. + public var placeLabel: String { + (line ?? originalLine).map { "\(path):\($0)" } ?? path + } + + /// Who started it, a deleted account by those words. + public var authorName: String { comments.first?.author ?? t("handoff.thread-ghost") } + + /// Its first comment's page where the host gave a web link. + public var webPage: URL? { comments.first?.url?.asWebPage } +} diff --git a/Sources/MultishellAppCore/Services/PullRequests/PullRequestThreads.swift b/Sources/MultishellAppCore/Services/PullRequests/PullRequestThreads.swift new file mode 100644 index 00000000..6c0dd86c --- /dev/null +++ b/Sources/MultishellAppCore/Services/PullRequests/PullRequestThreads.swift @@ -0,0 +1,10 @@ +import MultishellServices + +/// The unresolved review threads of the panel worktree's open pull request, +/// read while its page shows. Runtime only; see Docs/design/services/send-feedback.md. +struct PullRequestThreads: Equatable, Sendable { + let pullRequestNumber: Int + /// The last read's, kept through a failed read after it; `nil` until one answers. + var threads: [PullRequestThread]? + var failure: ServiceReadFailure? +} diff --git a/Sources/MultishellAppCore/Services/RemoteState.swift b/Sources/MultishellAppCore/Services/RemoteState.swift index b8294c4b..f7c139ef 100644 --- a/Sources/MultishellAppCore/Services/RemoteState.swift +++ b/Sources/MultishellAppCore/Services/RemoteState.swift @@ -54,6 +54,9 @@ final class RemoteState { /// The panel's pull request checks and run history, read only while it /// shows them, by worktree; and each failed run's report. var checks: [Worktree.ID: PullRequestChecks] = [:] + /// The panel's worktree's alone, as run details are: thread text is not kept + /// for rows passed by. + var threads: [Worktree.ID: PullRequestThreads] = [:] var ciHistories: [Worktree.ID: CIRunHistory] = [:] var failureReports: [CIRun.ID: CIRunDetail] = [:] /// Why each run's last workflows or report read failed, until one answers. diff --git a/Sources/MultishellAppCore/Settings/Project/IntegrationAvailability+Wording.swift b/Sources/MultishellAppCore/Settings/Project/IntegrationAvailability+Wording.swift index 4f80dce5..2ecee885 100644 --- a/Sources/MultishellAppCore/Settings/Project/IntegrationAvailability+Wording.swift +++ b/Sources/MultishellAppCore/Settings/Project/IntegrationAvailability+Wording.swift @@ -25,8 +25,8 @@ extension IntegrationAvailability { case .tool(.loggedOut): return t("integrations.logged-out", tool, "\(tool) auth login") - case .tool(.unsupportedVersion(let version)): - return t("integrations.too-old", tool, version, tool) + case .tool(.unsupportedVersion(let version, let minimum)): + return t("integrations.too-old", tool, version, minimum, tool) case .tool(.unreadable(let said)): return t("integrations.unreadable", tool, said) diff --git a/Sources/MultishellAppCore/Support/URL+WebPage.swift b/Sources/MultishellAppCore/Support/URL+WebPage.swift new file mode 100644 index 00000000..53cc6249 --- /dev/null +++ b/Sources/MultishellAppCore/Support/URL+WebPage.swift @@ -0,0 +1,8 @@ +import Foundation + +extension URL { + /// Itself where it is a web page a host linked; any other scheme is never opened. + var asWebPage: URL? { + ["http", "https"].contains(scheme?.lowercased()) ? self : nil + } +} diff --git a/Sources/MultishellAppCore/Terminals/Panes/AgentHandoff.swift b/Sources/MultishellAppCore/Terminals/Panes/AgentHandoff.swift index 91ab6ff3..69b5d5a7 100644 --- a/Sources/MultishellAppCore/Terminals/Panes/AgentHandoff.swift +++ b/Sources/MultishellAppCore/Terminals/Panes/AgentHandoff.swift @@ -4,6 +4,14 @@ import MultishellCore /// A note too long to paste, written to the drops directory for an agent to read: /// Claude Code folds a long paste. See terminals/paste-and-drop.md. enum AgentHandoff { + private static var maxNameLength: Int { 200 } + + /// `-.md`, the worktree named in the characters every file name + /// takes, cut to a length every disk takes. + static func fileName(_ stem: String, forWorktreeNamed name: String) -> String { + "\(stem)-\(name.portableName(maxLength: maxNameLength)).md" + } + /// Markdown, each entry under a heading. Code is indented rather than fenced, /// so a quoted line holding a fence cannot end the block. static func document(introduction: String, entries: [AgentHandoffEntry]) -> String { diff --git a/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffCheckbox.swift b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffCheckbox.swift new file mode 100644 index 00000000..727d9d4f --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffCheckbox.swift @@ -0,0 +1,53 @@ +import AppKit +import MultishellAppCore +import SwiftUI + +/// AppKit's own checkbox: SwiftUI's draws no mixed state from a single value, +/// which a step's checkbox over some of its items needs. +struct HandoffCheckbox: NSViewRepresentable { + @MainActor final class Coordinator: NSObject { + var toggle: () -> Void + var state: NSControl.StateValue = .off + + init(toggle: @escaping () -> Void) { + self.toggle = toggle + } + + /// The model decides the state, so AppKit's own cycling on the click is + /// undone: a toggle that changes nothing would otherwise leave it showing. + @objc func click(_ sender: NSButton) { + sender.state = state + toggle() + } + } + + let state: HandoffGroupState + let label: String + let toggle: () -> Void + + func makeNSView(context: Context) -> NSButton { + let button = NSButton( + checkboxWithTitle: "", + target: context.coordinator, + action: #selector(Coordinator.click(_:)), + ) + button.allowsMixedState = true + button.controlSize = .small + button.setContentHuggingPriority(.required, for: .horizontal) + return button + } + + func updateNSView(_ button: NSButton, context: Context) { + context.coordinator.toggle = toggle + context.coordinator.state = + switch state { + case .checked: .on + case .unchecked: .off + case .mixed: .mixed + } + button.state = context.coordinator.state + button.setAccessibilityLabel(label) + } + + func makeCoordinator() -> Coordinator { Coordinator(toggle: toggle) } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffItemControl.swift b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffItemControl.swift new file mode 100644 index 00000000..5e66f87a --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffItemControl.swift @@ -0,0 +1,46 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// A sendable row's trailing slot: its checkbox, or the sent bubble once sent. +/// A row with nothing to send keeps the slot empty, so its column holds. +struct HandoffItemControl: View { + let model: AppModel + /// `nil` for a row that keeps the slot with nothing to send. + let candidate: HandoffCandidate? + let worktreeID: Worktree.ID + /// What VoiceOver names the checkbox for, the row's check or job. + let itemName: String + let theme: Theme + + var body: some View { + let metrics = model.metrics + let state = candidate.map { model.handoffState(of: $0, in: worktreeID) } + Group { + switch state { + case .sent(let agentName): + HandoffSentBubble( + agentName: agentName, + size: metrics.servicePageRowGlyphSize + 2, + theme: theme, + ) { + guard let candidate else { return } + model.unmarkHandoffItemSent(candidate.id, in: worktreeID) + } + + case .checked, .unchecked: + HandoffCheckbox( + state: state == .checked ? .checked : .unchecked, + label: t("handoff.send-item", itemName), + ) { + guard let candidate else { return } + model.toggleHandoffItem(candidate, in: worktreeID) + } + + case nil: + Color.clear + } + } + .frame(width: metrics.handoffSlotWidth, alignment: .trailing) + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Review/ReviewRecipientMenu.swift b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffRecipientMenu.swift similarity index 78% rename from Sources/MultishellAppUI/Files/Panel/Review/ReviewRecipientMenu.swift rename to Sources/MultishellAppUI/Files/Panel/Handoff/HandoffRecipientMenu.swift index 67912461..bb595a3c 100644 --- a/Sources/MultishellAppUI/Files/Panel/Review/ReviewRecipientMenu.swift +++ b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffRecipientMenu.swift @@ -2,10 +2,10 @@ import MultishellAppCore import MultishellCore import SwiftUI -/// Which agent pane a review goes to: each with its mark, its tab and its state. -struct ReviewRecipientMenu: View { - let recipients: [ReviewRecipient] - let picked: ReviewRecipient +/// Which agent pane a Send goes to: each with its mark, its tab and its state. +struct HandoffRecipientMenu: View { + let recipients: [HandoffRecipient] + let picked: HandoffRecipient let now: Date let theme: Theme let pick: (TerminalSession.ID) -> Void @@ -19,7 +19,7 @@ struct ReviewRecipientMenu: View { Label { Text( t( - "review.recipient-item", + "handoff.recipient-item", recipient.agentName, recipient.tabTitle, recipient.stateText(at: now), @@ -47,10 +47,10 @@ struct ReviewRecipientMenu: View { .menuIndicator(.hidden) .buttonStyle(ThemedButtonStyle(fill: theme.filesPanel.fill, text: theme.filesPanel.text)) .fixedSize(horizontal: false, vertical: true) - .accessibilityLabel(t("review.recipient-menu")) + .accessibilityLabel(t("handoff.recipient-menu")) } - private func mark(of recipient: ReviewRecipient) -> Image? { + private func mark(of recipient: HandoffRecipient) -> Image? { AgentMarkImage.image(for: recipient.agentID, tint: theme.agentMarkRGB(recipient.agentID)) } } diff --git a/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffSendFooter.swift b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffSendFooter.swift new file mode 100644 index 00000000..dea4f661 --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffSendFooter.swift @@ -0,0 +1,121 @@ +import MultishellAppCore +import MultishellCore +import MultishellServices +import SwiftUI + +/// A page's foot: "Send to [agent] Send", what the last Send did, or why there is +/// nobody to send to. Review, the PR page and the CI page each feed it. +struct HandoffSendFooter: View { + let footer: HandoffFooter + /// Why the last Send sent nothing, said over the row until the next. + var note: String? + let metrics: UIMetrics + let theme: Theme + let pick: (TerminalSession.ID) -> Void + let send: (TerminalSession.ID) -> Void + + /// The picker's "working for 6m", kept current while the page is shown. + @State private var now = Date() + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + if let note { + Text(note) + .foregroundStyle(theme.color(for: .attention, on: theme.filesPanel)) + .fixedSize(horizontal: false, vertical: true) + } + row + } + .font(metrics.font(size: metrics.secondary)) + .controlSize(.small) + .padding(.horizontal, UIMetrics.panelSideInset) + .padding(.vertical, 10) + .hairline(.top, theme.filesPanel) + .ticking($now, every: .seconds(60)) + } + + @ViewBuilder private var row: some View { + Group { + switch footer { + case .reading(let text): + HStack(spacing: 8) { + CIRunGlyph( + status: .running, + theme: theme, + palette: theme.filesPanel, + size: metrics.servicePageRowGlyphSize, + ) + Text(text) + .foregroundStyle(theme.filesPanel.textSecondary) + .lineLimit(1) + Spacer(minLength: 0) + disabledSendButton + } + + case .sent(let summary): + HStack(spacing: 8) { + Text(summary) + .foregroundStyle(theme.filesPanel.textSecondary) + .lineLimit(1) + Spacer(minLength: 0) + } + + case .ready(let picked, let recipients, let canSend): + // A narrow panel drops "Send to" rather than wrap it a letter a line. + ViewThatFits(in: .horizontal) { + readyRow(picked: picked, recipients: recipients, canSend: canSend, labelled: true) + readyRow(picked: picked, recipients: recipients, canSend: canSend, labelled: false) + } + + case .noRecipient(let text): + HStack(spacing: 8) { + Text(text) + .foregroundStyle(theme.filesPanel.textSecondary) + Spacer(minLength: 0) + disabledSendButton + } + } + } + } + + private var disabledSendButton: some View { + Button(t("handoff.send")) {} + .buttonStyle(sendButtonStyle) + .fixedSize() + .disabled(true) + } + + private var sendButtonStyle: ThemedButtonStyle { + ThemedButtonStyle( + fill: theme.color(for: .attention, on: theme.filesPanel), + text: theme.filesPanel.background, + ) + } + + private func readyRow( + picked: HandoffRecipient, + recipients: [HandoffRecipient], + canSend: Bool, + labelled: Bool, + ) -> some View { + HStack(spacing: 8) { + if labelled { + Text(t("handoff.send-to")) + .foregroundStyle(theme.filesPanel.textSecondary) + .fixedSize() + } + HandoffRecipientMenu( + recipients: recipients, + picked: picked, + now: now, + theme: theme, + pick: pick, + ) + Spacer(minLength: 0) + Button(t("handoff.send")) { send(picked.id) } + .buttonStyle(sendButtonStyle) + .fixedSize() + .disabled(!canSend) + } + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffSentBubble.swift b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffSentBubble.swift new file mode 100644 index 00000000..8a6c85d2 --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Handoff/HandoffSentBubble.swift @@ -0,0 +1,33 @@ +import MultishellAppCore +import MultishellCore +import MultishellServices +import SwiftUI + +/// A sent item's mark: a paper plane on a green disc. A click turns it back +/// into a checked box, to send the item again. +struct HandoffSentBubble: View { + let agentName: String + let size: Double + let theme: Theme + let checkAgain: () -> Void + + var body: some View { + Button(action: checkAgain) { + ZStack { + Circle().fill(theme.color(for: CIRunStatus.passed, on: theme.filesPanel)) + PaperPlaneShape() + .stroke( + theme.filesPanel.background, + style: StrokeStyle(lineWidth: size / 12, lineCap: .round, lineJoin: .round), + ) + .padding(size * 0.22) + } + .frame(width: size, height: size) + .contentShape(.circle) + } + .buttonStyle(.plain) + .help(t("handoff.sent-to", agentName)) + .accessibilityLabel(t("handoff.sent-to", agentName)) + .accessibilityHint(t("handoff.send-again-hint")) + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Handoff/PaperPlaneShape.swift b/Sources/MultishellAppUI/Files/Panel/Handoff/PaperPlaneShape.swift new file mode 100644 index 00000000..38d16a35 --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Handoff/PaperPlaneShape.swift @@ -0,0 +1,17 @@ +import SwiftUI + +/// The sent bubble's paper plane, nose to the upper right. A 16-unit square, scaled. +struct PaperPlaneShape: Shape { + func path(in rect: CGRect) -> Path { + let grid = GlyphGrid(fitting: rect) + var path = Path() + path.move(to: grid.point(2.5, 7.8)) + path.addLine(to: grid.point(13.5, 2.5)) + path.addLine(to: grid.point(10.8, 13.5)) + path.addLine(to: grid.point(7.8, 8.8)) + path.closeSubpath() + path.move(to: grid.point(7.8, 8.8)) + path.addLine(to: grid.point(13.5, 2.5)) + return path + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Review/ReviewSendFooter.swift b/Sources/MultishellAppUI/Files/Panel/Review/ReviewSendFooter.swift index 155cf32f..19d5349b 100644 --- a/Sources/MultishellAppUI/Files/Panel/Review/ReviewSendFooter.swift +++ b/Sources/MultishellAppUI/Files/Panel/Review/ReviewSendFooter.swift @@ -2,85 +2,22 @@ import MultishellAppCore import MultishellCore import SwiftUI -/// Review's foot: "Send to [agent] Send", what the last Send did, or why there is -/// nobody to send to. +/// Review's foot, its own view so an agent's state change redraws it and not the +/// page's cards. struct ReviewSendFooter: View { let model: AppModel let worktree: Worktree let theme: Theme - /// The picker's "working for 6m", kept current while Review is shown. - @State private var now = Date() - var body: some View { - let metrics = model.metrics - Group { - switch model.reviewFooter(of: worktree) { - case .sent(let receipt): - HStack(spacing: 8) { - Text(receipt.summary) - .foregroundStyle(theme.filesPanel.textSecondary) - .lineLimit(1) - Spacer(minLength: 0) - } - - case .ready(let picked, let recipients, let canSend): - // A narrow panel drops "Send to" rather than wrap it a letter a line. - ViewThatFits(in: .horizontal) { - readyRow(picked: picked, recipients: recipients, canSend: canSend, labelled: true) - readyRow(picked: picked, recipients: recipients, canSend: canSend, labelled: false) - } - - case .noRecipient(let text): - HStack(spacing: 8) { - Text(text) - .foregroundStyle(theme.filesPanel.textSecondary) - Spacer(minLength: 0) - Button(t("review.send")) {} - .buttonStyle(sendButtonStyle) - .fixedSize() - .disabled(true) - } - } - } - .font(metrics.font(size: metrics.secondary)) - .controlSize(.small) - .padding(.horizontal, UIMetrics.panelSideInset) - .padding(.vertical, 10) - .hairline(.top, theme.filesPanel) - .ticking($now, every: .seconds(60)) - } - - private var sendButtonStyle: ThemedButtonStyle { - ThemedButtonStyle( - fill: theme.color(for: .attention, on: theme.filesPanel), - text: theme.filesPanel.background, - ) - } - - private func readyRow( - picked: ReviewRecipient, - recipients: [ReviewRecipient], - canSend: Bool, - labelled: Bool, - ) -> some View { - HStack(spacing: 8) { - if labelled { - Text(t("review.send-to")) - .foregroundStyle(theme.filesPanel.textSecondary) - .fixedSize() - } - ReviewRecipientMenu(recipients: recipients, picked: picked, now: now, theme: theme) { - sessionID in - model.pickReviewRecipient(sessionID, in: worktree.id) - } - Spacer(minLength: 0) - Button(t("review.send")) { - model.sendReview(of: worktree.id, to: picked.id, takingFocus: true) - } - .buttonStyle(sendButtonStyle) - .fixedSize() - .disabled(!canSend) + HandoffSendFooter( + footer: model.reviewFooter(of: worktree), + metrics: model.metrics, + theme: theme, + ) { sessionID in + model.pickHandoffRecipient(sessionID, in: worktree.id) + } send: { sessionID in + model.sendReview(of: worktree.id, to: sessionID, takingFocus: true) } } } diff --git a/Sources/MultishellAppUI/Files/Panel/Services/CIHistoryRow.swift b/Sources/MultishellAppUI/Files/Panel/Services/CIHistoryRow.swift index 4244ae1b..db60184c 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/CIHistoryRow.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/CIHistoryRow.swift @@ -54,7 +54,13 @@ struct CIHistoryRow: View { .buttonStyle(.plain) .accessibilityValue(AccessibilityText.ciStatus(run.status, isExpanded: isExpanded)) if isExpanded { - CIWorkflowList(model: model, worktree: worktree, run: run, theme: theme) + CIWorkflowList( + model: model, + worktree: worktree, + run: run, + listing: model.ciWorkflowListing(of: run, sendsFailures: false), + theme: theme, + ) } } } diff --git a/Sources/MultishellAppUI/Files/Panel/Services/CIJobRow.swift b/Sources/MultishellAppUI/Files/Panel/Services/CIJobRow.swift index df0e1e1e..b6111717 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/CIJobRow.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/CIJobRow.swift @@ -3,15 +3,22 @@ import MultishellCore import MultishellServices import SwiftUI -/// One job of a workflow, which opens on the provider at a click. +/// One job of a workflow, which opens on the provider at a click, and on the +/// newest run a failed one's checkbox or sent bubble at its trailing edge. struct CIJobRow: View { let model: AppModel let worktree: Worktree let job: CIJob + /// On the newest run every job keeps the trailing slot, so the column holds. + let showsHandoffSlot: Bool + /// What the slot sends, for a failed job of the newest run. + let candidate: HandoffCandidate? let theme: Theme var body: some View { let metrics = model.metrics + // The slot sits over the button, so the whole row's height still opens the job. + let slotClearance = showsHandoffSlot ? metrics.handoffSlotWidth + 7 : 0 Button { Task { await model.openCIJob(job, of: worktree) } } label: { @@ -32,7 +39,7 @@ struct CIJobRow: View { Spacer(minLength: 0) } .padding(.leading, UIMetrics.servicePageSideInset + metrics.servicePageJobIndent) - .padding(.trailing, UIMetrics.servicePageSideInset) + .padding(.trailing, UIMetrics.servicePageSideInset + slotClearance) .frame(height: metrics.paneRowHeight) .contentShape(.rect) } @@ -40,5 +47,17 @@ struct CIJobRow: View { .disabled(job.id == nil) .accessibilityValue(AccessibilityText.ciStatus(job.status)) .help(t("action.open-job", job.name)) + .overlay(alignment: .trailing) { + if showsHandoffSlot { + HandoffItemControl( + model: model, + candidate: candidate, + worktreeID: worktree.id, + itemName: job.name, + theme: theme, + ) + .padding(.trailing, UIMetrics.servicePageSideInset) + } + } } } diff --git a/Sources/MultishellAppUI/Files/Panel/Services/CIPanelPage.swift b/Sources/MultishellAppUI/Files/Panel/Services/CIPanelPage.swift index aaf57b4f..24271932 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/CIPanelPage.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/CIPanelPage.swift @@ -3,8 +3,8 @@ import MultishellCore import MultishellServices import SwiftUI -/// The panel's CI page: the branch's newest run in a card, its workflows and -/// jobs under Latest Run, and its earlier runs; see Docs/design/services/marks-and-pages.md. +/// The panel's CI page: the newest run's card, workflows and jobs, earlier runs, +/// and Send while it has failures; see Docs/design/services/marks-and-pages.md. struct CIPanelPage: View { /// Often enough that a run's "Started 4 minutes ago" is never a minute out. private static let ageTickInterval: Duration = .seconds(30) @@ -21,39 +21,44 @@ struct CIPanelPage: View { let metrics = model.metrics let page = model.ciPage(of: worktree) if case .run(let run) = page { - ScrollView { - VStack(alignment: .leading, spacing: 0) { - CIRunCard(model: model, worktree: worktree, run: run, now: now, theme: theme) - ServicePageSectionHeader( - title: t("panel.latest-run"), - isExpanded: $showsLatestRun, - theme: theme, - metrics: metrics, - ) - if showsLatestRun { - CIWorkflowList(model: model, worktree: worktree, run: run, theme: theme) - } - let earlier = model.earlierCIRuns(of: worktree) - if !earlier.isEmpty { - ServicePageSectionHeader( - title: t("panel.earlier-runs", earlier.count), - isExpanded: $showsEarlierRuns, - theme: theme, - metrics: metrics, - ) - if showsEarlierRuns { - ForEach(earlier) { run in - CIHistoryRow(model: model, worktree: worktree, run: run, now: now, theme: theme) + let listing = model.ciWorkflowListing(of: run, sendsFailures: true) + VStack(spacing: 0) { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + CIRunCard(model: model, worktree: worktree, run: run, now: now, theme: theme) + latestRunHeader(listing, metrics: metrics) + if showsLatestRun { + CIWorkflowList( + model: model, + worktree: worktree, + run: run, + listing: listing, + theme: theme, + ) + } + let earlier = model.earlierCIRuns(of: worktree) + if !earlier.isEmpty { + ServicePageSectionHeader( + title: t("panel.earlier-runs", earlier.count), + isExpanded: $showsEarlierRuns, + theme: theme, + metrics: metrics, + ) + if showsEarlierRuns { + ForEach(earlier) { run in + CIHistoryRow(model: model, worktree: worktree, run: run, now: now, theme: theme) + } } } + if let problem = model.panelReadProblem(of: worktree) { + ServicePageNote(text: problem, theme: theme, metrics: metrics) + } } - if let problem = model.panelReadProblem(of: worktree) { - ServicePageNote(text: problem, theme: theme, metrics: metrics) - } + .padding(.bottom, 8) } - .padding(.bottom, 8) + .ticking($now, every: Self.ageTickInterval) + CISendFooter(model: model, worktree: worktree, listing: listing, theme: theme) } - .ticking($now, every: Self.ageTickInterval) } else if let text = page.emptyText { PanelPageEmptyState( text: text, @@ -65,4 +70,26 @@ struct CIPanelPage: View { } } } + + private func latestRunHeader(_ listing: CIWorkflowListing, metrics: UIMetrics) -> some View { + let candidates = listing.candidates + return ServicePageSectionHeader( + title: t("panel.latest-run"), + isExpanded: $showsLatestRun, + theme: theme, + metrics: metrics, + detail: model.handoffToSendText( + of: candidates, + isCollapsed: !showsLatestRun, + in: worktree.id, + ), + ) { + if let state = model.handoffGroupState(of: candidates, in: worktree.id) { + HandoffCheckbox(state: state, label: t("handoff.send-all-failures")) { + model.toggleHandoffGroup(candidates, in: worktree.id) + } + .frame(width: metrics.handoffSlotWidth, alignment: .trailing) + } + } + } } diff --git a/Sources/MultishellAppUI/Files/Panel/Services/CIRunOutputRow.swift b/Sources/MultishellAppUI/Files/Panel/Services/CIRunOutputRow.swift new file mode 100644 index 00000000..8f03db87 --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Services/CIRunOutputRow.swift @@ -0,0 +1,32 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// "Run output" over the report's text that names no listed job, with its +/// checkbox: it can be the only failure, a config error before any job ran. +struct CIRunOutputRow: View { + let model: AppModel + let worktree: Worktree + let output: CIHandoffItem + let theme: Theme + + var body: some View { + let metrics = model.metrics + HStack(spacing: 7) { + Text(output.heading) + .font(metrics.font(size: metrics.secondary, weight: .semibold)) + .foregroundStyle(theme.filesPanel.text) + .lineLimit(1) + Spacer(minLength: 0) + HandoffItemControl( + model: model, + candidate: output.candidate, + worktreeID: worktree.id, + itemName: output.heading, + theme: theme, + ) + } + .padding(.horizontal, UIMetrics.servicePageSideInset) + .frame(height: metrics.paneRowHeight) + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Services/CISendFooter.swift b/Sources/MultishellAppUI/Files/Panel/Services/CISendFooter.swift new file mode 100644 index 00000000..683adb5a --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Services/CISendFooter.swift @@ -0,0 +1,27 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// The CI page's foot, while the newest run has failures. Its own view, so an +/// agent's state change redraws it and not the run's workflows. +struct CISendFooter: View { + let model: AppModel + let worktree: Worktree + let listing: CIWorkflowListing + let theme: Theme + + var body: some View { + if let footer = model.ciHandoffFooter(of: worktree, over: listing) { + HandoffSendFooter( + footer: footer, + note: model.handoffMiss(of: worktree, on: .ciRuns), + metrics: model.metrics, + theme: theme, + ) { sessionID in + model.pickHandoffRecipient(sessionID, in: worktree.id) + } send: { sessionID in + model.sendCIFailures(of: worktree.id, to: sessionID, takingFocus: true) + } + } + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Services/CIWorkflowList.swift b/Sources/MultishellAppUI/Files/Panel/Services/CIWorkflowList.swift index 0d893d65..dfe7e7c3 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/CIWorkflowList.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/CIWorkflowList.swift @@ -3,21 +3,21 @@ import MultishellCore import MultishellServices import SwiftUI -/// A run's workflows and their jobs, a job opening on the provider at a click, -/// and under each failed job what the run's failure report says of it. +/// A run's workflows and jobs, under each failed job what its report says, and +/// on the newest run each failure's checkbox; see services/send-feedback.md. struct CIWorkflowList: View { let model: AppModel let worktree: Worktree let run: CIRun + /// The run's workflows, report text and, on the newest run, what can be sent. + let listing: CIWorkflowListing let theme: Theme var body: some View { let metrics = model.metrics - let workflows = model.ciWorkflows(ofRun: run) ?? [] - let report = model.failureReport(of: run) VStack(alignment: .leading, spacing: 0) { - ForEach(Array(workflows.enumerated()), id: \.offset) { - _, + ForEach(Array(listing.workflows.enumerated()), id: \.offset) { + workflowIndex, workflow in HStack(spacing: 7) { CIRunGlyph( @@ -35,15 +35,35 @@ struct CIWorkflowList: View { .frame(height: metrics.paneRowHeight) .accessibilityElement(children: .combine) .accessibilityValue(AccessibilityText.ciStatus(workflow.status)) - ForEach(Array(workflow.jobs.enumerated()), id: \.offset) { _, job in - CIJobRow(model: model, worktree: worktree, job: job, theme: theme) - if let excerpt = report?.excerpt(ofJob: job.name, inWorkflow: workflow.name) { + ForEach(Array(workflow.jobs.enumerated()), id: \.offset) { jobIndex, job in + let position = CIJobPosition(workflow: workflowIndex, job: jobIndex) + let item = listing.item(at: position) + CIJobRow( + model: model, + worktree: worktree, + job: job, + showsHandoffSlot: listing.showsHandoffSlot, + candidate: item?.candidate, + theme: theme, + ) + if let excerpt = listing.excerpt(ofJobAt: position) { CIFailureExcerptView(text: excerpt, theme: theme, metrics: metrics) .padding(.leading, metrics.servicePageJobIndent) + } else if item?.awaitsReport == true { + Text(t("panel.ci-report-after-run")) + .font(metrics.font(size: metrics.caption)) + .foregroundStyle(theme.filesPanel.textSecondary) + .fixedSize(horizontal: false, vertical: true) + .padding(.leading, UIMetrics.servicePageSideInset + 2 * metrics.servicePageJobIndent) + .padding(.trailing, UIMetrics.servicePageSideInset) + .padding(.bottom, 4) } } } - ForEach(Array((report?.unplaced(among: workflows) ?? []).enumerated()), id: \.offset) { + if let output = listing.runOutput { + CIRunOutputRow(model: model, worktree: worktree, output: output, theme: theme) + } + ForEach(Array(listing.unplacedExcerpts.enumerated()), id: \.offset) { _, excerpt in CIFailureExcerptView(text: excerpt, theme: theme, metrics: metrics) diff --git a/Sources/MultishellAppUI/Files/Panel/Services/MergePathStepRow.swift b/Sources/MultishellAppUI/Files/Panel/Services/MergePathStepRow.swift index f1811bac..48603c58 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/MergePathStepRow.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/MergePathStepRow.swift @@ -3,8 +3,8 @@ import MultishellCore import MultishellServices import SwiftUI -/// One step of the merge path: its glyph on the rail, its title and hint, -/// and for the checks step every check under it. +/// One merge path step: its glyph on the rail, title and hint, its checks or +/// threads, and its own checkbox where it has something to send. struct MergePathStepRow: View { private static let railWidth = 1.5 /// Between the glyph and the rail under it. @@ -15,15 +15,22 @@ struct MergePathStepRow: View { private static let passedRailOpacity = 0.55 let model: AppModel + let worktree: Worktree + let pullRequest: PullRequest let path: MergePath let step: MergePath.Step + /// The pull request's unresolved threads, read once for every step. + let threads: [PullRequestThread] let base: String let host: String let theme: Theme @Binding var showsChecks: Bool + @Binding var showsThreads: Bool var body: some View { let metrics = model.metrics + let items = model.mergePathStepItems(of: step, in: path, on: pullRequest, threads: threads) + let isExpanded = isExpanded(items) HStack(alignment: .top, spacing: UIMetrics.servicePageGlyphSpacing) { VStack(spacing: Self.railGap) { glyph @@ -35,21 +42,53 @@ struct MergePathStepRow: View { .frame(maxHeight: .infinity) } VStack(alignment: .leading, spacing: 0) { - MergePathWords( - hint: path.hint(of: step, base: base, host: host), - metrics: metrics, - theme: theme, - ) { - heading + HStack(alignment: .top, spacing: 8) { + MergePathWords( + hint: hint(items, isCollapsed: isExpanded?.wrappedValue == false), + metrics: metrics, + theme: theme, + ) { + heading(isExpanded) + } + Spacer(minLength: 0) + if let state = model.handoffGroupState(of: items.candidates, in: worktree.id) { + HandoffCheckbox(state: state, label: items.sendAllLabel) { + model.toggleHandoffGroup(items.candidates, in: worktree.id) + } + .frame(width: metrics.handoffSlotWidth, alignment: .trailing) + } } if step.kind == .checks, showsChecks, let checks = path.checks { VStack(spacing: 0) { ForEach(Array(checks.enumerated()), id: \.offset) { _, check in - PullRequestCheckRow(model: model, check: check, theme: theme) + PullRequestCheckRow( + model: model, + check: check, + worktreeID: worktree.id, + showsHandoffSlot: items.showsCheckSlot, + candidate: items.checkCandidates[check], + theme: theme, + ) } } .padding(.top, 7) } + if !items.threads.isEmpty, showsThreads { + VStack(spacing: 0) { + ForEach(items.threads, id: \.id) { thread in + if let candidate = items.candidate(of: thread) { + PullRequestThreadRow( + model: model, + thread: thread, + candidate: candidate, + worktreeID: worktree.id, + theme: theme, + ) + } + } + } + .padding(.top, 5) + } } .padding(.bottom, Self.stepSpacing) } @@ -57,6 +96,8 @@ struct MergePathStepRow: View { .padding(.horizontal, UIMetrics.servicePageSideInset) } + private var stepTitle: String { path.title(of: step, base: base) } + @ViewBuilder private var glyph: some View { let metrics = model.metrics if step.warnsOfConflicts { @@ -70,6 +111,16 @@ struct MergePathStepRow: View { ), ) .accessibilityHidden(true) + } else if step.kind == .comments { + SpeechBubbleShape() + .stroke( + theme.filesPanel.textSecondary, + style: StrokeStyle( + lineWidth: UIMetrics.statusGlyphLineWidth(side: metrics.serviceGlyphSize), + lineJoin: .round, + ), + ) + .accessibilityHidden(true) } else { CIRunGlyph( status: step.status, @@ -80,20 +131,45 @@ struct MergePathStepRow: View { } } - @ViewBuilder private var heading: some View { - let metrics = model.metrics - let title = Text(path.title(of: step, base: base)).mergePathTitle( - metrics: metrics, - theme: theme, + private var railColor: Color { + guard step.status == .passed else { return theme.filesPanel.border } + return theme.color(for: CIRunStatus.passed, on: theme.filesPanel).opacity( + Self.passedRailOpacity ) - if step.kind == .checks { + } + + /// Whether the step's list shows; `nil` where it has none. + private func isExpanded(_ items: MergePathStepItems) -> Binding? { + switch items.collapsibleList { + case .checks: $showsChecks + case .threads: $showsThreads + case nil: nil + } + } + + private func hint(_ items: MergePathStepItems, isCollapsed: Bool) -> String? { + model.mergePathHint( + of: step, + in: path, + base: base, + host: host, + items: items, + isCollapsed: isCollapsed, + in: worktree.id, + ) + } + + @ViewBuilder private func heading(_ isExpanded: Binding?) -> some View { + let metrics = model.metrics + let title = Text(stepTitle).mergePathTitle(metrics: metrics, theme: theme) + if let isExpanded { Button { - showsChecks.toggle() + isExpanded.wrappedValue.toggle() } label: { HStack(spacing: 6) { title DisclosureChevron( - isExpanded: showsChecks, + isExpanded: isExpanded.wrappedValue, size: metrics.servicePageMarkSize, weight: .semibold, metrics: metrics, @@ -103,16 +179,9 @@ struct MergePathStepRow: View { .contentShape(.rect) } .buttonStyle(.plain) - .accessibilityValue(AccessibilityText.disclosure(isExpanded: showsChecks)) + .accessibilityValue(AccessibilityText.disclosure(isExpanded: isExpanded.wrappedValue)) } else { title } } - - private var railColor: Color { - guard step.status == .passed else { return theme.filesPanel.border } - return theme.color(for: CIRunStatus.passed, on: theme.filesPanel).opacity( - Self.passedRailOpacity - ) - } } diff --git a/Sources/MultishellAppUI/Files/Panel/Services/PullRequestCheckRow.swift b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestCheckRow.swift index 705e3fa9..86044c75 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/PullRequestCheckRow.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestCheckRow.swift @@ -4,22 +4,38 @@ import MultishellServices import SwiftUI /// One check under the merge path's Checks step; one with a page of its own -/// opens it at a click. +/// opens it at a click. A failing one carries its checkbox or sent bubble. struct PullRequestCheckRow: View { let model: AppModel let check: PullRequestCheck + let worktreeID: Worktree.ID + /// Every row keeps the trailing slot while any check can be sent, so the + /// Required tags stay in one column. + let showsHandoffSlot: Bool + let candidate: HandoffCandidate? let theme: Theme var body: some View { - if check.webPage != nil { - Button { - model.openCheck(check) - } label: { - row.contentShape(.rect) + HStack(spacing: 8) { + if check.webPage != nil { + Button { + model.openCheck(check) + } label: { + row.contentShape(.rect) + } + .buttonStyle(.plain) + } else { + row + } + if showsHandoffSlot { + HandoffItemControl( + model: model, + candidate: candidate, + worktreeID: worktreeID, + itemName: check.displayName, + theme: theme, + ) } - .buttonStyle(.plain) - } else { - row } } diff --git a/Sources/MultishellAppUI/Files/Panel/Services/PullRequestPanelPage.swift b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestPanelPage.swift index b6a24918..ffb3acd8 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/PullRequestPanelPage.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestPanelPage.swift @@ -3,14 +3,15 @@ import MultishellCore import MultishellServices import SwiftUI -/// The pull request in a card, then the steps toward its merge ending on the -/// merge, or the merge form in their place; see Docs/design/services/. +/// The pull request's card, the steps to its merge or the merge form, and Send +/// while a check fails or a thread is unresolved; see Docs/design/services/. struct PullRequestPanelPage: View { let model: AppModel let worktree: Worktree let theme: Theme @State private var showsChecks = true + @State private var showsThreads = true var body: some View { let page = model.pullRequestPage(of: worktree) @@ -24,28 +25,40 @@ struct PullRequestPanelPage: View { theme: theme, ) } else { - ScrollView { - VStack(alignment: .leading, spacing: 0) { - ServicePageCard(theme: theme) { - PullRequestSummary( - model: model, - worktree: worktree, - pullRequest: pullRequest, - theme: theme, - ) + let path = model.mergePath(of: pullRequest, in: worktree) + let threads = model.unresolvedThreads(of: pullRequest, in: worktree) + VStack(spacing: 0) { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + ServicePageCard(theme: theme) { + PullRequestSummary( + model: model, + worktree: worktree, + pullRequest: pullRequest, + theme: theme, + ) + } + let services = model.services(of: worktree) + let notes = [ + services.outgrownText, services.pullRequestReadProblemText, path.staleChecksNote, + model.threadsReadProblem(of: pullRequest, in: worktree), + ] + ForEach(Array(notes.compactMap(\.self).enumerated()), id: \.offset) { _, note in + ServicePageNote(text: note, theme: theme, metrics: model.metrics) + } + mergePath(path, of: pullRequest, threads: threads) + .padding(.top, 10) } - let path = model.mergePath(of: pullRequest, in: worktree) - let services = model.services(of: worktree) - let notes = [ - services.outgrownText, services.pullRequestReadProblemText, path.staleChecksNote, - ] - ForEach(Array(notes.compactMap(\.self).enumerated()), id: \.offset) { _, note in - ServicePageNote(text: note, theme: theme, metrics: model.metrics) - } - mergePath(path, base: pullRequest.baseBranch) - .padding(.top, 10) + .padding(.bottom, 8) } - .padding(.bottom, 8) + PullRequestSendFooter( + model: model, + worktree: worktree, + pullRequest: pullRequest, + path: path, + threads: threads, + theme: theme, + ) } } } else if let text = page.emptyText { @@ -60,18 +73,27 @@ struct PullRequestPanelPage: View { } } - private func mergePath(_ path: MergePath, base: String) -> some View { + private func mergePath( + _ path: MergePath, + of pullRequest: PullRequest, + threads: [PullRequestThread], + ) -> some View { let host = model.pullRequestHostName(of: worktree) ?? "" + let base = pullRequest.baseBranch return VStack(alignment: .leading, spacing: 0) { ForEach(Array(path.steps.enumerated()), id: \.offset) { _, step in MergePathStepRow( model: model, + worktree: worktree, + pullRequest: pullRequest, path: path, step: step, + threads: threads, base: base, host: host, theme: theme, showsChecks: $showsChecks, + showsThreads: $showsThreads, ) } MergePathEndRow( diff --git a/Sources/MultishellAppUI/Files/Panel/Services/PullRequestSendFooter.swift b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestSendFooter.swift new file mode 100644 index 00000000..fd0542e9 --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestSendFooter.swift @@ -0,0 +1,37 @@ +import MultishellAppCore +import MultishellCore +import MultishellServices +import SwiftUI + +/// The PR page's foot, while a check fails or a thread is unresolved. Its own view, +/// so an agent's state or a log read's count redraws it and not the merge path. +struct PullRequestSendFooter: View { + let model: AppModel + let worktree: Worktree + let pullRequest: PullRequest + let path: MergePath + let threads: [PullRequestThread] + let theme: Theme + + var body: some View { + if let footer = model.pullRequestHandoffFooter( + of: worktree, + along: path, + on: pullRequest, + threads: threads, + ) { + HandoffSendFooter( + footer: footer, + note: model.handoffMiss(of: worktree, on: .pullRequest), + metrics: model.metrics, + theme: theme, + ) { sessionID in + model.pickHandoffRecipient(sessionID, in: worktree.id) + } send: { sessionID in + Task { + await model.sendPullRequestFeedback(of: worktree.id, to: sessionID, takingFocus: true) + } + } + } + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Services/PullRequestThreadRow.swift b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestThreadRow.swift new file mode 100644 index 00000000..64533c41 --- /dev/null +++ b/Sources/MultishellAppUI/Files/Panel/Services/PullRequestThreadRow.swift @@ -0,0 +1,66 @@ +import MultishellAppCore +import MultishellCore +import MultishellServices +import SwiftUI + +/// An unresolved thread: its author, place and two lines of its first comment, +/// opening on the host at a click, then its checkbox or sent bubble. +struct PullRequestThreadRow: View { + let model: AppModel + let thread: PullRequestThread + let candidate: HandoffCandidate + let worktreeID: Worktree.ID + let theme: Theme + + var body: some View { + let metrics = model.metrics + let first = thread.comments.first + HStack(alignment: .top, spacing: 8) { + Button { + model.openThread(thread) + } label: { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 6) { + Text(thread.authorName) + .font(metrics.font(size: metrics.secondary, weight: .semibold)) + .foregroundStyle(theme.filesPanel.text) + .lineLimit(1) + .fixedSize() + Text(thread.placeLabel) + .font(.system(size: metrics.caption, design: .monospaced)) + .foregroundStyle(theme.filesPanel.textSecondary) + .lineLimit(1) + .truncationMode(.head) + if thread.isOutdated { + ReviewChipLabel( + chip: .outdated, + palette: theme.filesPanel, + theme: theme, + metrics: metrics, + ) + .fixedSize() + } + } + Text(first?.body ?? "") + .font(metrics.font(size: metrics.secondary)) + .foregroundStyle(theme.filesPanel.text) + .lineLimit(2) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(.rect) + } + .buttonStyle(.plain) + .disabled(thread.webPage == nil) + .accessibilityElement(children: .combine) + HandoffItemControl( + model: model, + candidate: candidate, + worktreeID: worktreeID, + itemName: thread.placeLabel, + theme: theme, + ) + } + .padding(.vertical, 5) + } +} diff --git a/Sources/MultishellAppUI/Files/Panel/Services/ServicePageSectionHeader.swift b/Sources/MultishellAppUI/Files/Panel/Services/ServicePageSectionHeader.swift index e67438b4..84e6eab8 100644 --- a/Sources/MultishellAppUI/Files/Panel/Services/ServicePageSectionHeader.swift +++ b/Sources/MultishellAppUI/Files/Panel/Services/ServicePageSectionHeader.swift @@ -2,12 +2,16 @@ import MultishellAppCore import MultishellCore import SwiftUI -/// A services' page's collapsible section: a chevron and its title in caps. -struct ServicePageSectionHeader: View { +/// A services' page's collapsible section: a chevron and its title in caps, and +/// whatever sits at its trailing edge, such as Latest run's checkbox. +struct ServicePageSectionHeader: View { let title: String @Binding var isExpanded: Bool let theme: Theme let metrics: UIMetrics + /// After the title in its own case, such as "1 to send" over a collapsed list. + var detail: String? + @ViewBuilder let trailing: () -> Trailing var body: some View { Button { @@ -23,6 +27,9 @@ struct ServicePageSectionHeader: View { Text(title.uppercased()) .font(metrics.font(size: metrics.small, weight: .semibold)) .tracking(UIMetrics.filesPanelHeadingTracking) + if let detail { + Text(detail).font(metrics.font(size: metrics.caption)) + } Spacer(minLength: 0) } .foregroundStyle(theme.filesPanel.textTertiary) @@ -31,7 +38,19 @@ struct ServicePageSectionHeader: View { .contentShape(.rect) } .buttonStyle(.plain) - .accessibilityLabel(title) + .accessibilityLabel([title, detail].compactMap(\.self).joined(separator: ", ")) .accessibilityValue(AccessibilityText.disclosure(isExpanded: isExpanded)) + // Over the button rather than beside it, so the whole row still toggles. + .overlay(alignment: .trailing) { + trailing().padding(.trailing, UIMetrics.servicePageSideInset) + } + } +} + +extension ServicePageSectionHeader where Trailing == EmptyView { + init(title: String, isExpanded: Binding, theme: Theme, metrics: UIMetrics) { + self.init(title: title, isExpanded: isExpanded, theme: theme, metrics: metrics, detail: nil) { + EmptyView() + } } } diff --git a/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings b/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings index 9964f58f..ec79ef28 100644 --- a/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings +++ b/Sources/MultishellAppUI/Resources/en.lproj/Localizable.strings @@ -190,6 +190,14 @@ "general.show-hidden-files-info" = "On, the Files panel lists what git ignores, greyed, and the quick switcher finds those files. Off, git's ignored files are neither read nor listed."; "general.state-file" = "State file:"; "general.state-file-info" = "Projects, worktrees, tabs and these settings. Running shells are not saved."; +"handoff.recipient-item" = "%1$@ · %2$@ · %3$@"; +"handoff.recipient-menu" = "Agent to send to"; +"handoff.send" = "Send"; +"handoff.send-again-hint" = "Click to send it again"; +"handoff.send-all-failures" = "Send all failures"; +"handoff.send-item" = "Send %@"; +"handoff.send-to" = "Send to"; +"handoff.sent-to" = "Sent to %@"; "hooks.copied-paths" = "Copy into new worktrees"; "hooks.copied-paths-info" = "Copied from the repository into the new worktree before the post-create hook. One path per line from the repository root; * and ? match within a name. A list in %@ fills a blank one."; "hooks.create" = "Create"; @@ -255,6 +263,7 @@ "merge-form.subject" = "Commit subject"; "notifications.header" = "Post a notification when a tab you are not looking at reports"; "panel.branch-into-base" = "%1$@ → %2$@"; +"panel.ci-report-after-run" = "Its report is read once the run ends. Sent now, it goes without it."; "panel.latest-run" = "Latest run"; "panel.required" = "Required"; "paste.unsafe-message" = "The program in this pane could run this text as it lands, reading a line break or a sequence inside it as keys. Check it before pasting."; @@ -343,10 +352,6 @@ "review.composer-placeholder" = "What should the agent change here?"; "review.edit" = "Edit"; "review.quote-heading" = "When you wrote it, the lines read:"; -"review.recipient-item" = "%1$@ · %2$@ · %3$@"; -"review.recipient-menu" = "Agent to send the review to"; -"review.send" = "Send"; -"review.send-to" = "Send to"; "review.title" = "Review"; "rotor.changes" = "Changes"; "settings.agent-hooks" = "Agent hooks"; diff --git a/Sources/MultishellAppUI/Support/Appearance/UIMetrics+ServicePages.swift b/Sources/MultishellAppUI/Support/Appearance/UIMetrics+ServicePages.swift index 27bdb562..afed3fb3 100644 --- a/Sources/MultishellAppUI/Support/Appearance/UIMetrics+ServicePages.swift +++ b/Sources/MultishellAppUI/Support/Appearance/UIMetrics+ServicePages.swift @@ -16,6 +16,9 @@ extension UIMetrics { var servicePageJobIndent: Double { badge + 8 } /// A section's or an earlier run's chevron, and a check's Required tag. var servicePageMarkSize: Double { small - 1 } + /// The trailing column a sendable row's checkbox or sent bubble sits in, and + /// a step's own checkbox above them, on the PR and CI pages alike. + var handoffSlotWidth: Double { badge + 6 } /// A card's lines under its title, so they start where the title does. var servicePageCardTextIndent: Double { serviceGlyphSize + Self.servicePageGlyphSpacing } /// How far a merge path glyph sits down, so it centres on its title's first line. diff --git a/Sources/MultishellCLI/Control/ControlCommand.swift b/Sources/MultishellCLI/Control/ControlCommand.swift index 8aeb8783..de9463b1 100644 --- a/Sources/MultishellCLI/Control/ControlCommand.swift +++ b/Sources/MultishellCLI/Control/ControlCommand.swift @@ -2,6 +2,7 @@ /// usage errors and `help` name. enum ControlCommand: String, CaseIterable { case board + case ciRuns = "ci" case config case debug case files @@ -9,6 +10,7 @@ enum ControlCommand: String, CaseIterable { case open case panes case projects + case pullRequest = "pr" case quit case review case sidebar diff --git a/Sources/MultishellCLI/Control/ControlRefusal+Wording.swift b/Sources/MultishellCLI/Control/ControlRefusal+Wording.swift index 4e93f6e2..3b1754b7 100644 --- a/Sources/MultishellCLI/Control/ControlRefusal+Wording.swift +++ b/Sources/MultishellCLI/Control/ControlRefusal+Wording.swift @@ -9,6 +9,10 @@ extension ControlRefusal { case .agentWorking: "an agent is working there; --force goes ahead anyway" case .alert(let title, let message): "\(title) \(message)" case .autoRenameUnavailable(let id): "Auto Rename is greyed out for worktree \(id)" + + case .checksNotRead(let id, let reason): + "worktree \(id)'s checks could not be read, so nothing was sent: \(reason)" + case .debugToolsOff: "debug tools are off; `multishell debug tools on` turns them on" case .fileNotOpenable(let path): @@ -26,6 +30,10 @@ extension ControlRefusal { + "`multishell ui menu \"View > Files Pane\"` opens it on its list" case .gitNotFound: "git is not on the login shell's PATH, so nothing is read from it" + + case .handoffUnderWay(let id): + "worktree \(id)'s pull request page has a Send under way; ask again once it has sent" + case .invalidBranchName(let name): "git would refuse the branch name \(name)" case .invalidValue(let key, let value): "\(key) takes no value \"\(value)\"" case .menuItemDisabled(let path): "\(path) is greyed out in the menu now" @@ -72,7 +80,7 @@ extension ControlRefusal { case .noReviewTab(let path): "no file tab of the worktree shows \(path); `multishell tabs open-file` opens one" - case .noReviewRecipient(let id): + case .noRecipient(let id): "worktree \(id) has no pane with an agent to send to, " + "or not the one named; `multishell tabs list` names its panes" @@ -99,6 +107,15 @@ extension ControlRefusal { case .noTab(let id): "no tab \(id); `multishell tabs list` names them" case .nothingInView: "no worktree's tabs are on screen" case .nothingPresented: "no alert, dialog, sheet or field is up" + + case .nothingToHandOff(.ciRuns, let id): + "worktree \(id)'s CI page has no failure checked and not sent already; it reads " + + "the newest run's jobs only while shown: `multishell ui show ci \(id)`" + + case .nothingToHandOff(.pullRequest, let id): + "worktree \(id)'s pull request has no failing check or unresolved thread checked " + + "and not sent already" + case .nothingToSend(let id): "worktree \(id) has no review comment waiting to be sent" case .noWindow: "the main window is closed" @@ -106,6 +123,9 @@ extension ControlRefusal { case .onlyTabInGroup(let id): "tab \(id) is its group's only tab" + case .threadsNotRead(let id, let reason): + "worktree \(id)'s review threads could not be read, so nothing was sent: \(reason)" + case .paneNotLive(let id): "pane \(id) has no shell yet; `multishell worktrees select WORKTREE_ID` starts its worktree's" diff --git a/Sources/MultishellCLI/Control/Helper+Arguments.swift b/Sources/MultishellCLI/Control/Helper+Arguments.swift index 70a824ab..bdb28915 100644 --- a/Sources/MultishellCLI/Control/Helper+Arguments.swift +++ b/Sources/MultishellCLI/Control/Helper+Arguments.swift @@ -61,6 +61,17 @@ extension Helper { return text } + /// `--worktree`'s id; `nil` where none is given, which the app takes for the one in view. + static func worktreeOption(in options: CommandOptions, topic: String) throws -> String? { + try options["worktree"].map { try worktreeID($0, topic: topic) } + } + + /// A Send's `--to`; `nil` where none is given, which the app takes for the + /// agent the page's picker shows. + static func recipientOption(in options: CommandOptions, topic: String) throws -> UUID? { + try options["to"].map { try tabOrPaneID($0, topic: topic) } + } + /// What comes before `--` and the command after it, `nil` where there is no `--`. static func splitAtDoubleDash( _ arguments: ArraySlice diff --git a/Sources/MultishellCLI/Control/Helper+CICommands.swift b/Sources/MultishellCLI/Control/Helper+CICommands.swift new file mode 100644 index 00000000..52633010 --- /dev/null +++ b/Sources/MultishellCLI/Control/Helper+CICommands.swift @@ -0,0 +1,22 @@ +import MultishellCore + +extension Helper { + static func runCI( + _ arguments: ArraySlice, + environment: [String: String], + ) throws + -> Int32 + { + let topic = ControlCommand.ciRuns.rawValue + let (words, optionWords) = positionals(arguments.dropFirst()) + guard arguments.first == "send", words.isEmpty else { + throw UsageError("ci needs: send", topic: topic) + } + let options = try CommandOptions(optionWords, valued: ["worktree", "to"], topic: topic) + let request = ControlRequest.sendCIFailures( + worktree: try worktreeOption(in: options, topic: topic), + to: try recipientOption(in: options, topic: topic), + ) + return try ask(request, environment: environment) + } +} diff --git a/Sources/MultishellCLI/Control/Helper+PullRequestCommands.swift b/Sources/MultishellCLI/Control/Helper+PullRequestCommands.swift new file mode 100644 index 00000000..98ccbb98 --- /dev/null +++ b/Sources/MultishellCLI/Control/Helper+PullRequestCommands.swift @@ -0,0 +1,32 @@ +import MultishellCore + +extension Helper { + static func runPullRequest( + _ arguments: ArraySlice, + environment: [String: String], + ) throws + -> Int32 + { + let topic = ControlCommand.pullRequest.rawValue + let (words, optionWords) = positionals(arguments.dropFirst()) + guard arguments.first == "send", words.isEmpty else { + throw UsageError("pr needs: send", topic: topic) + } + let options = try CommandOptions( + optionWords, + valued: ["worktree", "to"], + flags: ["checks", "threads"], + topic: topic, + ) + // Neither flag is the page's Send, both kinds. + let isOneKind = options.has("checks") != options.has("threads") + let request = ControlRequest.sendPullRequestFeedback( + worktree: try worktreeOption(in: options, topic: topic), + to: try recipientOption(in: options, topic: topic), + includesChecks: !isOneKind || options.has("checks"), + includesThreads: !isOneKind || options.has("threads"), + ) + // Its answer waits on every checked check's log, which can outlast the usual 30 s. + return try ask(request, environment: environment, timeout: nil) + } +} diff --git a/Sources/MultishellCLI/Control/Helper+ReviewCommands.swift b/Sources/MultishellCLI/Control/Helper+ReviewCommands.swift index f6d2f8aa..7b0ab29f 100644 --- a/Sources/MultishellCLI/Control/Helper+ReviewCommands.swift +++ b/Sources/MultishellCLI/Control/Helper+ReviewCommands.swift @@ -13,7 +13,7 @@ extension Helper { switch (arguments.first, words.count) { case ("list", 0): let options = try CommandOptions(optionWords, valued: ["worktree"], topic: topic) - let worktree = try reviewedWorktree(in: options, topic: topic) + let worktree = try worktreeOption(in: options, topic: topic) return try ask(.listReviewComments(worktree: worktree), environment: environment) case ("add", 3): @@ -24,7 +24,7 @@ extension Helper { topic: topic, ) let order = ReviewCommentOrder( - worktreeID: try reviewedWorktree(in: options, topic: topic), + worktreeID: try worktreeOption(in: options, topic: topic), path: words[0], side: options.has("removed") ? .committed : .onDisk, lines: try reviewLines(words[1], topic: topic), @@ -37,8 +37,8 @@ extension Helper { case ("send", 0): let options = try CommandOptions(optionWords, valued: ["worktree", "to"], topic: topic) let request = ControlRequest.sendReview( - worktree: try reviewedWorktree(in: options, topic: topic), - to: try options["to"].map { try tabOrPaneID($0, topic: topic) }, + worktree: try worktreeOption(in: options, topic: topic), + to: try recipientOption(in: options, topic: topic), ) return try ask(request, environment: environment) @@ -50,7 +50,7 @@ extension Helper { topic: topic, ) let request = ControlRequest.clearReviewComments( - worktree: try reviewedWorktree(in: options, topic: topic), + worktree: try worktreeOption(in: options, topic: topic), sentOnly: options.has("sent"), ) return try ask(request, environment: environment) @@ -63,11 +63,6 @@ extension Helper { } } - private static func reviewedWorktree(in options: CommandOptions, topic: String) throws -> String? - { - try options["worktree"].map { try worktreeID($0, topic: topic) } - } - /// `806` or `806-810`, numbers from 1 with the first no later than the last. private static func reviewLines(_ text: String, topic: String) throws -> ClosedRange { let parts = text.split(separator: "-", omittingEmptySubsequences: false).map { Int($0) } diff --git a/Sources/MultishellCLI/Helper.swift b/Sources/MultishellCLI/Helper.swift index 2483d350..41f490ee 100644 --- a/Sources/MultishellCLI/Helper.swift +++ b/Sources/MultishellCLI/Helper.swift @@ -121,6 +121,8 @@ enum Helper { case .tabs: return try runTabs(rest, environment: environment) case .files: return try runFiles(rest, environment: environment) case .review: return try runReview(rest, environment: environment) + case .pullRequest: return try runPullRequest(rest, environment: environment) + case .ciRuns: return try runCI(rest, environment: environment) case .panes: return try runPanes(rest, environment: environment) case .userInterface: return try runUI(rest, environment: environment) case .board: return try runBoard(rest, environment: environment) diff --git a/Sources/MultishellCLI/Usage/Helper+CIUsage.swift b/Sources/MultishellCLI/Usage/Helper+CIUsage.swift new file mode 100644 index 00000000..86b8c181 --- /dev/null +++ b/Sources/MultishellCLI/Usage/Helper+CIUsage.swift @@ -0,0 +1,15 @@ +extension Helper { + static let ciUsage = """ + usage: multishell ci send [--to PANE_ID] [--worktree WORKTREE_ID] + Write the failures the CI page has checked in the newest run, each + failed job with its part of the run's report, to a file and paste a + mention of it into the agent's prompt, as the page's Send does, then + print how many went to which pane. No newline is typed. Every + failure starts checked. The page reads the run's jobs only while it + shows, so show it first with `multishell ui show ci`. PANE_ID is a + pane with an agent in the worktree, working or not; where none is + named, the one the page's picker shows. The worktree in view where + none is named. + + """ +} diff --git a/Sources/MultishellCLI/Usage/Helper+PullRequestUsage.swift b/Sources/MultishellCLI/Usage/Helper+PullRequestUsage.swift new file mode 100644 index 00000000..6287912c --- /dev/null +++ b/Sources/MultishellCLI/Usage/Helper+PullRequestUsage.swift @@ -0,0 +1,18 @@ +extension Helper { + static let pullRequestUsage = """ + usage: multishell pr send [--checks] [--threads] [--to PANE_ID] [--worktree WORKTREE_ID] + Write the items the pull request page has checked, its failing + checks with their logs' tails and its unresolved review threads, to + a file and paste a mention of it into the agent's prompt, as the + page's Send does, then print how many went to which pane. No newline + is typed. --checks sends only the checks and --threads only the + threads; neither sends both. Failing required checks and every + thread start checked. Where the page is not showing the worktree, or + the app is in the background, its checks and threads are read for + the Send. + PANE_ID is a pane with an agent in the worktree, working or not; + where none is named, the one the page's picker shows. The worktree + in view where none is named. + + """ +} diff --git a/Sources/MultishellCLI/Usage/Helper+Usage.swift b/Sources/MultishellCLI/Usage/Helper+Usage.swift index cd56e9e6..e8af698e 100644 --- a/Sources/MultishellCLI/Usage/Helper+Usage.swift +++ b/Sources/MultishellCLI/Usage/Helper+Usage.swift @@ -34,6 +34,9 @@ extension Helper { files list|filter|expand|collapse The Files panel's list review list|add|send|clear Review's comments + pr send Send the pull request page's checked items to + an agent + ci send Send the CI page's checked failures to an agent board list The Agents board's columns and cards sidebar list The sidebar's rows as drawn ui show|hide|filter|dismiss|menu|switcher @@ -87,11 +90,13 @@ extension Helper { switch command { case .info, .open, .quit: appUsage case .board: boardUsage + case .ciRuns: ciUsage case .config: configUsage case .debug: debugUsage case .files: filesUsage case .panes: paneUsage case .projects: projectUsage + case .pullRequest: pullRequestUsage case .review: reviewUsage case .sidebar: sidebarUsage case .tabs: tabUsage diff --git a/Sources/MultishellCore/Control/ControlRefusal.swift b/Sources/MultishellCore/Control/ControlRefusal.swift index 770b7f7e..dd575ad1 100644 --- a/Sources/MultishellCore/Control/ControlRefusal.swift +++ b/Sources/MultishellCore/Control/ControlRefusal.swift @@ -10,6 +10,8 @@ public enum ControlRefusal: Error, Codable, Equatable, Sendable { case alert(title: String, message: String) /// Auto Rename is greyed out for the worktree. case autoRenameUnavailable(id: String) + /// A worktree's checks could not be read for a Send, in the tool's words. + case checksNotRead(id: String, reason: String) case debugToolsOff /// Not a file the worktree holds that opens as text or an image, which a click beeps at. case fileNotOpenable(path: String) @@ -23,6 +25,8 @@ public enum ControlRefusal: Error, Codable, Equatable, Sendable { case fileTabShowsNotice(id: UUID) /// No git on the login shell's PATH, which every git read needs. case gitNotFound + /// A Send from the pull request page is still under way. + case handoffUnderWay(id: String) case invalidBranchName(String) case invalidValue(key: String, value: String) /// Greyed out in the menu now, as a click would find it. @@ -51,12 +55,12 @@ public enum ControlRefusal: Error, Codable, Equatable, Sendable { case noProjectChosen /// The directory a request came from is in no project or worktree. case noProjectHolding(path: String) + /// The worktree has no live pane with an agent, or not the one named. + case noRecipient(id: String) /// `--removed` on lines that hold no removed line, which are the file on disk's. case noRemovedLines(path: String) /// The file's tab holds no such lines on that side. case noReviewLines(path: String) - /// The worktree has no live pane with an agent, or not the one named. - case noReviewRecipient(id: String) /// No file tab of the worktree shows the file. case noReviewTab(path: String) /// The worktree's row draws no glyph for the page, having nothing on it. @@ -75,6 +79,8 @@ public enum ControlRefusal: Error, Codable, Equatable, Sendable { case nothingInView /// No alert, dialog, sheet or field is up to dismiss. case nothingPresented + /// Nothing checked and unsent; the CI page reads its run's jobs only while shown. + case nothingToHandOff(ServicePage, id: String) /// Review holds no comment waiting to be sent. case nothingToSend(id: String) /// The main window is closed, so there is nothing to size or draw. @@ -123,6 +129,8 @@ public enum ControlRefusal: Error, Codable, Equatable, Sendable { case tabShowsAllChanges(id: UUID) /// A terminal tab, which has no file's bar to step or find in. case tabShowsNoFile(id: UUID) + /// A worktree's review threads could not be read for a Send, in the tool's words. + case threadsNotRead(id: String, reason: String) /// A panel width a drag could not reach, in points. case widthOutOfRange(minimum: Double, maximum: Double) /// Open but behind another window or on another Space, where nothing reads a diff --git a/Sources/MultishellCore/Control/ControlRequest.swift b/Sources/MultishellCore/Control/ControlRequest.swift index cd663daf..246ff149 100644 --- a/Sources/MultishellCore/Control/ControlRequest.swift +++ b/Sources/MultishellCore/Control/ControlRequest.swift @@ -96,6 +96,16 @@ public enum ControlRequest: Codable, Equatable, Sendable { case selectPane(id: UUID) case selectTab(id: UUID) case selectWorktree(id: String) + /// The CI page's Send: the newest run's checked failures, to the agent pane + /// named, else the one its picker shows. + case sendCIFailures(worktree: String?, to: UUID?) + /// The pull request page's Send: its checked checks and threads, or one kind alone. + case sendPullRequestFeedback( + worktree: String?, + to: UUID?, + includesChecks: Bool, + includesThreads: Bool, + ) /// Review's Send: to the agent pane named, else the one its picker shows. case sendReview(worktree: String?, to: UUID?) case setDebugInfo(shown: Bool) diff --git a/Sources/MultishellCore/Control/ServicePage.swift b/Sources/MultishellCore/Control/ServicePage.swift index 58ec569d..0974e642 100644 --- a/Sources/MultishellCore/Control/ServicePage.swift +++ b/Sources/MultishellCore/Control/ServicePage.swift @@ -10,4 +10,13 @@ public enum ServicePage: String, Codable, CaseIterable, Sendable { case .pullRequest: .pullRequest } } + + /// The services' page `mode` shows, `nil` for one that lists files or comments. + public init?(_ mode: FilesPanelMode) { + switch mode { + case .ciRuns: self = .ciRuns + case .pullRequest: self = .pullRequest + case .changes, .files, .review: return nil + } + } } diff --git a/Sources/MultishellCore/Resources/en.lproj/Localizable.strings b/Sources/MultishellCore/Resources/en.lproj/Localizable.strings index d4a34044..35eb9ae2 100644 --- a/Sources/MultishellCore/Resources/en.lproj/Localizable.strings +++ b/Sources/MultishellCore/Resources/en.lproj/Localizable.strings @@ -280,6 +280,36 @@ "files-panel.tracked-capped" = "Listing stops at %d tracked files."; "find.count" = "%1$d/%2$d"; "find.count-unselected" = "-/%d"; +"handoff.check-text" = "Failed. Its page: %@"; +"handoff.check-text-no-link" = "Failed. The host gives it no page."; +"handoff.ci-introduction" = "Failed jobs from this branch's newest run on %@. Fix each, or say why it cannot be fixed here."; +"handoff.ci-job-text" = "Failed on %@."; +"handoff.ci-job-text-with-id" = "Failed on %1$@, job %2$@."; +"handoff.ci-report-not-read" = "Its report was not read."; +"handoff.ci-report-silent" = "The run's report says nothing of this job."; +"handoff.ci-report-unread" = "Its report was not read yet: the run was still going."; +"handoff.ci-run-output-text" = "What %@'s report says of this run that names no listed job."; +"handoff.ci-sentence" = "Fix the CI failures in %@"; +"handoff.gone-while-reading" = "%@ was gone by the time the logs were read. Nothing was sent."; +"handoff.log-empty" = "Its log printed nothing."; +"handoff.log-not-read" = "Its log could not be read: %@"; +"handoff.no-agent" = "No agent in %@"; +"handoff.not-pasted" = "Nothing was sent to %@: its pane took no paste."; +"handoff.pane-gone" = "The pane picked has closed. Pick another."; +"handoff.preparing" = "Reading what to send"; +"handoff.pull-request-introduction" = "Failing checks and unresolved review comments on pull request #%d. Fix each, or say why it should stay as it is."; +"handoff.pull-request-sentence" = "Address the pull request feedback in %@"; +"handoff.ran-on-other-commit" = "This ran on %@, not the worktree's current commit."; +"handoff.recipient-at-prompt" = "at its prompt"; +"handoff.recipient-working-for" = "working for %@"; +"handoff.run-output" = "Run output"; +"handoff.send-all-checks" = "Send every failing check"; +"handoff.send-all-threads" = "Send every unresolved comment"; +"handoff.sent-summary" = "%1$@ sent to %2$@"; +"handoff.thread-comment" = "%1$@: %2$@"; +"handoff.thread-ghost" = "A deleted account"; +"handoff.thread-link" = "On the pull request: %@"; +"handoff.thread-outdated" = "Outdated: the lines it was written on have changed since."; "hook-variable.branch" = "Its branch"; "hook-variable.port" = "First port of its block"; "hook-variable.project-name" = "Repository folder name"; @@ -316,6 +346,7 @@ "integration.no-version" = "It did not say which version it is."; "integration.not-run" = "%@ could not be run"; "integration.page-names-no-repository" = "The pull request's page, %@, names no repository to ask how it may merge."; +"integration.page-names-no-threads" = "The pull request's page, %@, names no repository to read its review comments from."; "integration.timed-out" = "It did not answer in time."; "integration.unreadable-answer" = "Its answer could not be read."; "integrations.checking" = "Asking %@…"; @@ -330,7 +361,7 @@ "integrations.not-installed" = "%1$@ is not on your login shell's PATH. Install it with brew install %2$@."; "integrations.ready" = "%1$@ %2$@, logged in."; "integrations.ready-as" = "%1$@ %2$@, logged in as %3$@."; -"integrations.too-old" = "%1$@ %2$@ is too old: version 1 or later is needed. Run brew upgrade %3$@."; +"integrations.too-old" = "%1$@ %2$@ is too old: version %3$@ or later is needed. Run brew upgrade %4$@."; "integrations.unreadable" = "%1$@ said: %2$@"; "kind.bare" = "Bare repository"; "kind.bare-in-sentence" = "bare repository"; @@ -371,6 +402,7 @@ "merge-path.auto-merges-hint" = "Once the steps above clear"; "merge-path.checks" = "Checks"; "merge-path.closed-hint" = "Open a new one, or reopen it on %@ where it allows"; +"merge-path.comments" = "Comments"; "merge-path.draft-hint" = "Mark it ready for review on %@"; "merge-path.merge-base" = "Merge %@ into this branch and push"; "merge-path.merge-into" = "Merge into %@"; @@ -425,6 +457,7 @@ "option.shell-path" = "%1$@ %2$@"; "option.system-font" = "System"; "option.system-monospace" = "System monospace"; +"panel.checks-not-read" = "Checks not read: %@"; "panel.ci-not-applicable" = "A worktree with no branch has no runs"; "panel.ci-not-configured" = "This repository does not use a supported CI."; "panel.ci-off" = "CI is turned off for this project"; @@ -438,6 +471,7 @@ "panel.pull-request-not-applicable" = "A worktree with no branch has no pull request"; "panel.pull-request-trunk" = "The trunk has no pull request"; "panel.pull-requests-off" = "Pull requests are turned off for this project"; +"panel.threads-not-read" = "Review comments not read: %@"; "panel.turned-off-detail" = "Turn it on in the project's Integrations settings."; "port-block.caption" = "No port block ending by %2$d is left for %1$@, so MULTISHELL_PORT is unset there."; "port-block.worktree" = "%1$@ (%2$@)"; @@ -502,15 +536,11 @@ "review.handoff-sentence" = "Address the review comments in %@"; "review.line" = "Line %d"; "review.lines" = "Lines %1$d–%2$d"; -"review.no-agent" = "No agent in %@"; -"review.recipient-at-prompt" = "at its prompt"; -"review.recipient-working-for" = "working for %@"; "review.removed-line" = "Removed line %d"; "review.removed-lines" = "Removed lines %1$d–%2$d"; "review.save" = "Save"; "review.scope-branch" = "(Branch)"; "review.scope-modified" = "(Modified)"; -"review.sent-summary" = "%1$@ sent to %2$@"; "services.logged-out" = "%@ is not logged in"; "services.never-read" = "Not read yet: %@"; "services.not-hosted" = "This repository is not on %@"; diff --git a/Sources/MultishellCore/Resources/en.lproj/Localizable.stringsdict b/Sources/MultishellCore/Resources/en.lproj/Localizable.stringsdict index 8654d7af..3918224d 100644 --- a/Sources/MultishellCore/Resources/en.lproj/Localizable.stringsdict +++ b/Sources/MultishellCore/Resources/en.lproj/Localizable.stringsdict @@ -88,6 +88,42 @@ other%d failed + count.failures + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + one%d failure + other%d failures + + + count.items + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + one%d item + other%d items + + + count.jobs + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + one%d job + other%d jobs + + count.matches NSStringLocalizedFormatKey @@ -172,6 +208,30 @@ other%d steps above to clear first + count.merge-path-unresolved + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + one%d unresolved + other%d unresolved + + + count.merge-path-unresolved-comments + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + one%d unresolved comment + other%d unresolved comments + + count.processes NSStringLocalizedFormatKey @@ -184,6 +244,18 @@ other%d processes + count.reading-logs + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + oneReading %d log + otherReading %d logs + + count.runs NSStringLocalizedFormatKey @@ -352,6 +424,18 @@ other%d more new files not listed. + handoff.earlier-lines-cut + + NSStringLocalizedFormatKey + %#@count@ + count + + NSStringFormatSpecTypeKeyNSStringPluralRuleType + NSStringFormatValueTypeKeyd + one%d earlier line cut. + other%d earlier lines cut. + + hook.stopped-after-seconds NSStringLocalizedFormatKey diff --git a/Sources/MultishellServices/CI/CircleCI/CircleCIToolReport.swift b/Sources/MultishellServices/CI/CircleCI/CircleCIToolReport.swift index be778aa9..9b2f12a1 100644 --- a/Sources/MultishellServices/CI/CircleCI/CircleCIToolReport.swift +++ b/Sources/MultishellServices/CI/CircleCI/CircleCIToolReport.swift @@ -9,7 +9,9 @@ enum CircleCIToolReport { guard let (version, major) = version(in: versionOutput) else { return .unreadable(versionOutput.firstLine) } - guard major >= firstMajorWithRuns else { return .unsupportedVersion(version) } + guard major >= firstMajorWithRuns else { + return .unsupportedVersion(version, minimum: String(firstMajorWithRuns)) + } guard authMe.succeeded else { let text = authMe.standardOutput + "\n" + authMe.standardError switch CircleCIErrorText.failure(from: text) { diff --git a/Sources/MultishellServices/CI/Core/CIRun.swift b/Sources/MultishellServices/CI/Core/CIRun.swift index e2334fd0..5e118e52 100644 --- a/Sources/MultishellServices/CI/Core/CIRun.swift +++ b/Sources/MultishellServices/CI/Core/CIRun.swift @@ -3,9 +3,6 @@ import Foundation /// One CI run of a branch, its newest as the service lists them. Runtime /// only; see Docs/develop/state-on-disk.md. public struct CIRun: Hashable, Sendable, Identifiable { - /// git's own shortest abbreviation; anything shorter names too many commits. - private static let shortestCommitPrefix = 7 - public let id: String /// The branch it ran on, by its name on the remote. public let branch: String @@ -22,7 +19,7 @@ public struct CIRun: Hashable, Sendable, Identifiable { public let repository: RemoteRepository? /// The commit as git abbreviates it, which is all 1.11 prints anyway. - public var shortCommit: String { String(commit.prefix(Self.shortestCommitPrefix)) } + public var shortCommit: String { commit.abbreviatedCommit } /// Its phase's word, not its status's, which says failed while jobs still /// run; one on hold waits on a person, perhaps for days. @@ -50,9 +47,6 @@ public struct CIRun: Hashable, Sendable, Identifiable { /// Whether it ran `commit`, which a provider may name by a prefix of it. public func ran(_ commit: String?) -> Bool { - guard let commit else { return false } - if commit == self.commit { return true } - guard min(commit.count, self.commit.count) >= Self.shortestCommitPrefix else { return false } - return commit.hasPrefix(self.commit) || self.commit.hasPrefix(commit) + commit?.namesSameCommit(as: self.commit) ?? false } } diff --git a/Sources/MultishellServices/SCM/Core/FailedCheckLog.swift b/Sources/MultishellServices/SCM/Core/FailedCheckLog.swift new file mode 100644 index 00000000..5abf0eb9 --- /dev/null +++ b/Sources/MultishellServices/SCM/Core/FailedCheckLog.swift @@ -0,0 +1,6 @@ +/// The end of a failed check's log, as much as was asked for, and how many lines +/// of the whole log came before it. +public struct FailedCheckLog: Equatable, Sendable { + public let text: String + public let earlierLineCount: Int +} diff --git a/Sources/MultishellServices/SCM/Core/PullRequestHost.swift b/Sources/MultishellServices/SCM/Core/PullRequestHost.swift index 0d0c39c5..a38dee82 100644 --- a/Sources/MultishellServices/SCM/Core/PullRequestHost.swift +++ b/Sources/MultishellServices/SCM/Core/PullRequestHost.swift @@ -18,6 +18,24 @@ public protocol PullRequestHost: Sendable { /// The checks on the pull request's head, each once, and which are required. func checks(of pullRequest: PullRequest, in directory: URL) async throws -> [PullRequestCheck] + /// Whether `failedLog` can read the check's log: it ran on the host's own CI. + func readsFailedLog(of check: PullRequestCheck) -> Bool + + /// The last `lineLimit` lines of a failed check's failed steps; `nil` for a check + /// from anywhere else. Throws `ServiceReadFailure`. + func failedLog( + of check: PullRequestCheck, + keepingLast lineLimit: Int, + in directory: URL, + ) async throws -> FailedCheckLog? + + /// The pull request's unresolved review threads, oldest first. Throws + /// `ServiceReadFailure`. + func unresolvedThreads( + of pullRequest: PullRequest, + in directory: URL, + ) async throws -> [PullRequestThread] + /// The commit the pull request heads now, which a list read may be behind. /// Throws `ServiceReadFailure`. func headCommit(of pullRequest: PullRequest, in directory: URL) async throws -> String diff --git a/Sources/MultishellServices/SCM/Core/PullRequestThread.swift b/Sources/MultishellServices/SCM/Core/PullRequestThread.swift new file mode 100644 index 00000000..e6a09188 --- /dev/null +++ b/Sources/MultishellServices/SCM/Core/PullRequestThread.swift @@ -0,0 +1,18 @@ +import Foundation + +/// An unresolved review thread on a pull request: a comment on its diff and the +/// replies under it. Runtime only, read while the PR page shows. +public struct PullRequestThread: Hashable, Sendable { + public let id: String + public let path: String + /// Where it sits in the head's file; `nil` for a comment on the whole file + /// or an outdated one, whose lines the head has moved past. + public let line: Int? + /// Where it sat when written, which an outdated thread is labelled by. + public let originalLine: Int? + public let isOutdated: Bool + /// The diff its first comment was written on, ending at its line. + public let diffHunk: String + /// Oldest first; never empty, a thread being its first comment. + public let comments: [PullRequestThreadComment] +} diff --git a/Sources/MultishellServices/SCM/Core/PullRequestThreadComment.swift b/Sources/MultishellServices/SCM/Core/PullRequestThreadComment.swift new file mode 100644 index 00000000..c07f10d7 --- /dev/null +++ b/Sources/MultishellServices/SCM/Core/PullRequestThreadComment.swift @@ -0,0 +1,10 @@ +import Foundation + +/// One comment of a review thread, as the host words it. +public struct PullRequestThreadComment: Hashable, Sendable { + public let id: String + /// The author's login; `nil` for a deleted account. + public let author: String? + public let body: String + public let url: URL? +} diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubHost.swift b/Sources/MultishellServices/SCM/GitHub/GitHubHost.swift index 75e9d753..a0c3050e 100644 --- a/Sources/MultishellServices/SCM/GitHub/GitHubHost.swift +++ b/Sources/MultishellServices/SCM/GitHub/GitHubHost.swift @@ -11,6 +11,9 @@ public struct GitHubHost: PullRequestHost { static let listLimit = 100 /// Every pull request one branch has headed, reopened as new ones included. static let branchListLimit = 10 + /// Ten pages of a hundred threads: a pull request past that is not one an + /// agent is handed whole. + private static let threadPageLimit = 10 /// No prompt, no colour and no update check, which writes a state file. A /// login shell's `CLICOLOR_FORCE` outranks `NO_COLOR` and colours `--json`. @@ -106,6 +109,61 @@ public struct GitHubHost: PullRequestHost { ) } + /// One job's log, by the job its link names. A check from another CI links elsewhere. + public func readsFailedLog(of check: PullRequestCheck) -> Bool { + check.link.flatMap(GitHubJobAddress.init) != nil + } + + public func failedLog( + of check: PullRequestCheck, + keepingLast lineLimit: Int, + in directory: URL, + ) async throws -> FailedCheckLog? { + guard let link = check.link, let job = GitHubJobAddress(link) else { return nil } + // `gh run view --job` refuses every job until the whole run ends. + let output = try await runner.read( + ["api", "--hostname", job.host, "--allow-escape-sequences", job.logsEndpoint], + in: directory, + failure: GitHubErrorText.failure(from:), + ) + return GitHubJobLog.log( + from: String(decoding: output, as: UTF8.self), + keepingLast: lineLimit, + ) + } + + /// No `gh pr` command says whether a thread is resolved, so this asks the + /// GraphQL API through `gh api`, a page of a hundred at a time. + public func unresolvedThreads( + of pullRequest: PullRequest, + in directory: URL, + ) async throws -> [PullRequestThread] { + guard let address = GitHubPullRequestAddress(pullRequest.url) else { + throw ServiceReadFailure.failed( + t("integration.page-names-no-threads", pullRequest.url.absoluteString) + ) + } + var threads: [PullRequestThread] = [] + var cursor: String? + for _ in 0.. String { let json = try await runner.read( diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubJobAddress.swift b/Sources/MultishellServices/SCM/GitHub/GitHubJobAddress.swift new file mode 100644 index 00000000..bfe8d6db --- /dev/null +++ b/Sources/MultishellServices/SCM/GitHub/GitHubJobAddress.swift @@ -0,0 +1,23 @@ +import Foundation + +/// An Actions job from a check's link, `…///actions/runs//job/`; +/// a check from any other CI links elsewhere. +struct GitHubJobAddress: Equatable { + let host: String + private let repository: RemoteRepository + private let jobID: String + + var logsEndpoint: String { + "repos/\(repository.owner)/\(repository.name)/actions/jobs/\(jobID)/logs" + } + + init?(_ url: URL) { + guard let path = GitHubRepositoryPath(url), path.pageParts.count >= 5, + path.pageParts[0] == "actions", path.pageParts[1] == "runs", path.pageParts[3] == "job", + UInt64(path.pageParts[4]) != nil + else { return nil } + host = path.host + repository = path.repository + jobID = path.pageParts[4] + } +} diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubJobLog.swift b/Sources/MultishellServices/SCM/GitHub/GitHubJobLog.swift new file mode 100644 index 00000000..d177d1bd --- /dev/null +++ b/Sources/MultishellServices/SCM/GitHub/GitHubJobLog.swift @@ -0,0 +1,69 @@ +import Foundation + +/// A job's log from the Actions REST endpoint as an agent reads it: each line +/// starts with a timestamp and may carry colour, and the runner's cleanup follows the failure. +enum GitHubJobLog { + private static let newline = UInt8(ascii: "\n") + private static let errorMarker = Array("##[error]".utf8) + + /// Only its last `lineLimit` lines up to the last `##[error]` are cleaned, a line + /// ending at `\n` alone; why in services/send-feedback.md. + static func log(from output: String, keepingLast lineLimit: Int) -> FailedCheckLog { + // A step's first line opens with a byte-order mark before its timestamp. + let timestamp = /^\x{FEFF}?\d{4}-\d\d-\d\dT[0-9:.]+Z ?/ + let controlCode = /\x1b\[[0-9;?]*[A-Za-z]/ + let groupStart = /^##\[group\]/ + let failure = Substring(output.utf8[.. String? in + let message = line.replacing(timestamp, with: "").replacing(controlCode, with: "") + // A fold's end says nothing; its start names the step. `##[error]` stays. + if message == "##[endgroup]" { return nil } + return message.replacing(groupStart, with: "") + } + // A fold end dropped from the tail is a line cut, so the count is the whole log's. + return FailedCheckLog( + text: cleaned.joined(separator: "\n"), + earlierLineCount: max(0, lineCount - cleaned.count), + ) + } + + /// Where the last line naming `##[error]` ends, or the log's end where none + /// does. Found walking back, as the post-job steps after it are few. + private static func endOfLastErrorLine(in bytes: String.UTF8View) -> String.Index { + var index = bytes.endIndex + var lineEnd = bytes.endIndex + while index > bytes.startIndex { + let previous = bytes.index(before: index) + if bytes[previous] == newline { + lineEnd = previous + } else if bytes[previous...].starts(with: errorMarker) { + return lineEnd + } + index = previous + } + return bytes.endIndex + } + + /// Its last `lineLimit` lines, `\r\n` ends trimmed, found walking back through the + /// bytes: splitting the whole log first costs as many strings as it has lines. + private static func tail(of output: Substring, lineLimit: Int) -> [String] { + let bytes = output.utf8 + var start = bytes.endIndex + var newlines = 0 + while start > bytes.startIndex { + let previous = bytes.index(before: start) + if bytes[previous] == newline { + newlines += 1 + if newlines == lineLimit { break } + } + start = previous + } + return bytes[start...].split(separator: newline, omittingEmptySubsequences: false).map { line in + let text = String(decoding: line, as: UTF8.self) + return text.hasSuffix("\r") ? String(text.dropLast()) : text + } + } +} diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubPullRequestAddress.swift b/Sources/MultishellServices/SCM/GitHub/GitHubPullRequestAddress.swift index 9b3fd3f8..9c43ea42 100644 --- a/Sources/MultishellServices/SCM/GitHub/GitHubPullRequestAddress.swift +++ b/Sources/MultishellServices/SCM/GitHub/GitHubPullRequestAddress.swift @@ -7,9 +7,10 @@ struct GitHubPullRequestAddress: Equatable { let repository: RemoteRepository init?(_ url: URL) { - let parts = url.pathComponents.filter { $0 != "/" } - guard let host = url.host(), parts.count >= 4, parts[2] == "pull" else { return nil } - self.host = host - repository = RemoteRepository(owner: parts[0], name: parts[1]) + guard let path = GitHubRepositoryPath(url), path.pageParts.count >= 2, + path.pageParts[0] == "pull" + else { return nil } + host = path.host + repository = path.repository } } diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubRepositoryPath.swift b/Sources/MultishellServices/SCM/GitHub/GitHubRepositoryPath.swift new file mode 100644 index 00000000..0a973dc6 --- /dev/null +++ b/Sources/MultishellServices/SCM/GitHub/GitHubRepositoryPath.swift @@ -0,0 +1,17 @@ +import Foundation + +/// A GitHub page's host and repository, `https://///…`, and +/// the path under the repository that says which page it is. +struct GitHubRepositoryPath: Equatable { + let host: String + let repository: RemoteRepository + let pageParts: [String] + + init?(_ url: URL) { + let parts = url.pathComponents.filter { $0 != "/" } + guard let host = url.host(), parts.count >= 2 else { return nil } + self.host = host + repository = RemoteRepository(owner: parts[0], name: parts[1]) + pageParts = Array(parts.dropFirst(2)) + } +} diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubReviewThreadRecord.swift b/Sources/MultishellServices/SCM/GitHub/GitHubReviewThreadRecord.swift new file mode 100644 index 00000000..f1f51f68 --- /dev/null +++ b/Sources/MultishellServices/SCM/GitHub/GitHubReviewThreadRecord.swift @@ -0,0 +1,112 @@ +import Foundation +import MultishellCore + +/// One page of `query`'s answer: a pull request's review threads, resolved or +/// not, and where the next page starts. +struct GitHubReviewThreadRecord: Decodable { + /// The answer's `data`; `gh` exits non-zero for any `errors` beside it. + struct Envelope: Decodable { + struct Answer: Decodable { + let repository: Repository? + } + + let data: Answer? + } + + struct Repository: Decodable { + let pullRequest: PullRequestRecord? + } + + struct PullRequestRecord: Decodable { + let reviewThreads: Connection + } + + struct Connection: Decodable { + let pageInfo: PageInfo + let nodes: [GitHubReviewThreadRecord] + } + + struct PageInfo: Decodable { + let hasNextPage: Bool + let endCursor: String? + } + + struct Comments: Decodable { + let nodes: [Comment] + } + + struct Hunks: Decodable { + struct Hunk: Decodable { + let diffHunk: String + } + + let nodes: [Hunk] + } + + struct Comment: Decodable { + struct Author: Decodable { + let login: String + } + + let id: String + let author: Author? + let body: String + let url: URL? + } + + /// A hundred threads a page, the most GitHub gives, and a thread's first + /// hundred comments; the hunk only of the first, which places the thread. + static let query = """ + query($owner: String!, $name: String!, $number: Int!, $after: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { + id isResolved isOutdated path line originalLine + firstComment: comments(first: 1) { nodes { diffHunk } } + comments(first: 100) { nodes { id author { login } body url } } + } + } + } + } + } + """ + + let id: String + let isResolved: Bool + let isOutdated: Bool + let path: String + let line: Int? + let originalLine: Int? + let firstComment: Hunks + let comments: Comments + + /// The unresolved threads of one page, and the cursor of the next where there is one. + static func page(from json: Data) throws -> (threads: [PullRequestThread], next: String?) { + let envelope = try ToolAnswer.decode(Envelope.self, from: json) + guard let connection = envelope.data?.repository?.pullRequest?.reviewThreads else { + throw ServiceReadFailure.failed(t("integration.unreadable-answer")) + } + let threads = connection.nodes.filter { !$0.isResolved && !$0.comments.nodes.isEmpty } + .map { record in + PullRequestThread( + id: record.id, + path: record.path, + line: record.line, + originalLine: record.originalLine, + isOutdated: record.isOutdated, + diffHunk: record.firstComment.nodes.first?.diffHunk ?? "", + comments: record.comments.nodes.map { comment in + PullRequestThreadComment( + id: comment.id, + author: comment.author?.login, + body: comment.body, + url: comment.url, + ) + }, + ) + } + return (threads, connection.pageInfo.hasNextPage ? connection.pageInfo.endCursor : nil) + } +} diff --git a/Sources/MultishellServices/SCM/GitHub/GitHubToolReport.swift b/Sources/MultishellServices/SCM/GitHub/GitHubToolReport.swift index 06626dd4..91d32e2a 100644 --- a/Sources/MultishellServices/SCM/GitHub/GitHubToolReport.swift +++ b/Sources/MultishellServices/SCM/GitHub/GitHubToolReport.swift @@ -4,6 +4,8 @@ import MultishellProcess /// writes the login to stderr and says "as"; newer to stdout and "account". enum GitHubToolReport { private static let failureMark = "X " + /// The first whose `gh api` takes `--allow-escape-sequences`, which a job's log needs. + private static let minimumVersion = "2.97.0" static func status(versionOutput: String, authStatus: ProcessOutput) -> ServiceToolStatus { let words = versionOutput.split(whereSeparator: \.isWhitespace) @@ -12,13 +14,28 @@ enum GitHubToolReport { } let version = String(words[2]) let text = authStatus.standardOutput + "\n" + authStatus.standardError - // One host's lapsed login fails the whole status, though the others work. - if let account = account(in: text) { return .ready(version: version, account: account) } - guard authStatus.succeeded else { + let account = account(in: text) + // One host's lapsed login fails the whole status, though the others work. A + // login is asked first: an older gh still reads all but logs, none without one. + if account == nil, !authStatus.succeeded { let failure = GitHubErrorText.failure(from: text) return failure == .loggedOut ? .loggedOut : .unreadable(failureReason(in: text)) } - return .ready(version: version, account: nil) + if let installed = numbers(of: version), let minimum = numbers(of: minimumVersion), + installed.lexicographicallyPrecedes(minimum) + { + return .unsupportedVersion(version, minimum: minimumVersion) + } + return .ready(version: version, account: account) + } + + /// `2.97.0` and `2.97` as `[2, 97, 0]`, a later part missing or not a number + /// counting as 0; `nil` for a build from source, `DEV`, whose age cannot be told. + private static func numbers(of version: String) -> [Int]? { + let parts = version.split(separator: ".") + guard let major = parts.first.flatMap({ Int($0) }) else { return nil } + let later = parts.dropFirst().map { Int($0) ?? 0 } + return [major] + later + Array(repeating: 0, count: max(0, 2 - later.count)) } /// The line `gh` marks failed, without its mark; the first line is the host's diff --git a/Sources/MultishellServices/StandIn/ServiceStandIn.swift b/Sources/MultishellServices/StandIn/ServiceStandIn.swift index 687fc848..dd7f26d2 100644 --- a/Sources/MultishellServices/StandIn/ServiceStandIn.swift +++ b/Sources/MultishellServices/StandIn/ServiceStandIn.swift @@ -10,6 +10,11 @@ public struct ServiceStandIn: Sendable { let pullRequests: [PullRequest] /// By `key(of:)`: two repositories' may share a number. let checks: [String: [PullRequestCheck]] + /// By `key(of:)`, as checks are. + let threads: [String: [PullRequestThread]] + /// Two pull requests' identical checks share the first one's log: the read + /// is handed the check alone. + let logs: [PullRequestCheck: String] /// Newest first, undated ones last, ties in the order given. let runs: [CIRun] let workflows: [CIRun.ID: [CIWorkflow]] @@ -51,8 +56,20 @@ public struct ServiceStandIn: Sendable { "#\(built[repeated].0.number) into \(built[repeated].0.baseBranch) is given twice", ) } + try Self.refuseThreadsWithoutComments(in: pullRequests) self.pullRequests = built.map(\.0).newestFirst(by: \.updatedAt) checks = Dictionary(uniqueKeysWithValues: built.map { (Self.key(of: $0.0), $0.1) }) + threads = Dictionary( + uniqueKeysWithValues: zip(built, pullRequests).map { built, record in + (Self.key(of: built.0), (record.threads ?? []).map(\.thread)) + } + ) + logs = Dictionary( + pullRequests.flatMap { record in + (record.checks ?? []).compactMap { check in check.log.map { (check.check, $0) } } + }, + uniquingKeysWith: { first, _ in first }, + ) self.runs = runs.map(\.run).newestFirst { $0.createdAt ?? .distantPast } workflows = Dictionary( uniqueKeysWithValues: runs.map { ($0.id, ($0.workflows ?? []).map(\.workflow)) } @@ -64,6 +81,21 @@ public struct ServiceStandIn: Sendable { ) } + /// A thread is its first comment and the replies under it, so it has one. + private static func refuseThreadsWithoutComments( + in pullRequests: [ServiceStandInRecord.PullRequestRecord] + ) throws(ServiceStandInUnreadable) { + for (index, record) in pullRequests.enumerated() { + guard let empty = (record.threads ?? []).firstIndex(where: \.comments.isEmpty) else { + continue + } + throw ServiceStandInUnreadable( + at: "pullRequests.\(index).threads.\(empty).comments", + "a thread holds at least its first comment", + ) + } + } + /// What tells one pull request from another: its head repository, number and /// base, numbers being a base repository's, which a stand-in does not name. static func key(of pullRequest: PullRequest) -> String { diff --git a/Sources/MultishellServices/StandIn/ServiceStandInFields.swift b/Sources/MultishellServices/StandIn/ServiceStandInFields.swift index 675ca095..09d7a5ca 100644 --- a/Sources/MultishellServices/StandIn/ServiceStandInFields.swift +++ b/Sources/MultishellServices/StandIn/ServiceStandInFields.swift @@ -7,9 +7,13 @@ enum ServiceStandInFields { private static let pullRequest: Set = [ "number", "title", "url", "state", "review", "blocker", "autoMergesWhenReady", "isReadyToMerge", "headBranch", "headCommit", "headRepository", "baseBranch", "updatedAt", - "checks", + "checks", "threads", ] - private static let check: Set = ["name", "workflow", "status", "isRequired", "link"] + private static let check: Set = ["name", "workflow", "status", "isRequired", "link", "log"] + private static let thread: Set = [ + "id", "path", "line", "originalLine", "isOutdated", "diffHunk", "comments", + ] + private static let comment: Set = ["id", "author", "body", "url"] private static let run: Set = [ "id", "branch", "commit", "subject", "status", "isFinished", "createdAt", "repository", "workflows", "failures", @@ -33,6 +37,16 @@ enum ServiceStandInFields { path throws(ServiceStandInUnreadable) in try refuseUnknownKeys(of: item, allowed: check, at: path) } + try each(record["threads"], at: path + ["threads"]) { + item, + path throws(ServiceStandInUnreadable) in + try refuseUnknownKeys(of: item, allowed: thread, at: path) + try each(item["comments"], at: path + ["comments"]) { + entry, + path throws(ServiceStandInUnreadable) in + try refuseUnknownKeys(of: entry, allowed: comment, at: path) + } + } } try each(root["ciRuns"], at: ["ciRuns"]) { record, path throws(ServiceStandInUnreadable) in try refuseUnknownKeys(of: record, allowed: run, at: path) diff --git a/Sources/MultishellServices/StandIn/ServiceStandInRecord.swift b/Sources/MultishellServices/StandIn/ServiceStandInRecord.swift index 62d43190..558b43e9 100644 --- a/Sources/MultishellServices/StandIn/ServiceStandInRecord.swift +++ b/Sources/MultishellServices/StandIn/ServiceStandInRecord.swift @@ -18,6 +18,7 @@ struct ServiceStandInRecord: Decodable { let baseBranch: String? let updatedAt: Date? let checks: [CheckRecord]? + let threads: [ThreadRecord]? /// Its page on GitHub where no `url` is given, the slot it fills being GitHub's. /// Undated is the oldest, as an undated run is, which only orders them. @@ -73,6 +74,8 @@ struct ServiceStandInRecord: Decodable { let status: CIRunStatus let isRequired: Bool? let link: URL? + /// What the host's failed log read gives for the check. + let log: String? var check: PullRequestCheck { PullRequestCheck( @@ -85,6 +88,39 @@ struct ServiceStandInRecord: Decodable { } } + struct ThreadRecord: Decodable { + let id: String + let path: String + let line: Int? + let originalLine: Int? + let isOutdated: Bool? + let diffHunk: String? + let comments: [CommentRecord] + + var thread: PullRequestThread { + PullRequestThread( + id: id, + path: path, + line: line, + originalLine: originalLine, + isOutdated: isOutdated ?? false, + diffHunk: diffHunk ?? "", + comments: comments.map(\.comment), + ) + } + } + + struct CommentRecord: Decodable { + let id: String + let author: String? + let body: String + let url: URL? + + var comment: PullRequestThreadComment { + PullRequestThreadComment(id: id, author: author, body: body, url: url) + } + } + struct RunRecord: Decodable { let id: String let branch: String diff --git a/Sources/MultishellServices/StandIn/StandInPullRequestHost.swift b/Sources/MultishellServices/StandIn/StandInPullRequestHost.swift index 23d84ee6..f23e03d0 100644 --- a/Sources/MultishellServices/StandIn/StandInPullRequestHost.swift +++ b/Sources/MultishellServices/StandIn/StandInPullRequestHost.swift @@ -25,6 +25,25 @@ struct StandInPullRequestHost: PullRequestHost { standIn.checks[ServiceStandIn.key(of: pullRequest)] ?? [] } + func readsFailedLog(of check: PullRequestCheck) -> Bool { + standIn.logs[check] != nil + } + + func failedLog( + of check: PullRequestCheck, + keepingLast lineLimit: Int, + in directory: URL, + ) async throws -> FailedCheckLog? { + standIn.logs[check].map { FailedCheckLog(text: $0, earlierLineCount: 0) } + } + + func unresolvedThreads( + of pullRequest: PullRequest, + in directory: URL, + ) async throws -> [PullRequestThread] { + standIn.threads[ServiceStandIn.key(of: pullRequest)] ?? [] + } + /// A stand-in's pull requests move only as its list says. func headCommit(of pullRequest: PullRequest, in directory: URL) async throws -> String { pullRequest.headCommit diff --git a/Sources/MultishellServices/Support/String+CommitPrefix.swift b/Sources/MultishellServices/Support/String+CommitPrefix.swift new file mode 100644 index 00000000..5f41a272 --- /dev/null +++ b/Sources/MultishellServices/Support/String+CommitPrefix.swift @@ -0,0 +1,15 @@ +extension String { + /// git's own shortest abbreviation; anything shorter names too many commits. + private static let shortestCommitPrefix = 7 + + /// The commit as git abbreviates it. + public var abbreviatedCommit: String { String(prefix(Self.shortestCommitPrefix)) } + + /// Whether this commit hash and `other` name one commit, where a provider or + /// host gives a prefix of it. + public func namesSameCommit(as other: String) -> Bool { + if self == other { return true } + guard Swift.min(count, other.count) >= Self.shortestCommitPrefix else { return false } + return hasPrefix(other) || other.hasPrefix(self) + } +} diff --git a/Sources/MultishellServices/Tools/ServiceToolStatus.swift b/Sources/MultishellServices/Tools/ServiceToolStatus.swift index 10f0ff52..d00d41c1 100644 --- a/Sources/MultishellServices/Tools/ServiceToolStatus.swift +++ b/Sources/MultishellServices/Tools/ServiceToolStatus.swift @@ -5,6 +5,7 @@ public enum ServiceToolStatus: Hashable, Sendable { case ready(version: String, account: String?) /// It answered in a way this build cannot read, said as it said it. case unreadable(String) - /// Older than the commands this build runs, by the version it gave. - case unsupportedVersion(String) + /// Older than the commands this build runs, by the version it gave and the + /// first that has them. + case unsupportedVersion(String, minimum: String) } diff --git a/Tests/MultishellAppCoreTests/AppModel+PullRequestHandoffItems.swift b/Tests/MultishellAppCoreTests/AppModel+PullRequestHandoffItems.swift new file mode 100644 index 00000000..dbfb06be --- /dev/null +++ b/Tests/MultishellAppCoreTests/AppModel+PullRequestHandoffItems.swift @@ -0,0 +1,19 @@ +import MultishellCore +import MultishellServices + +@testable import MultishellAppCore + +extension AppModel { + /// The shown pull request's failing checks, then its unresolved threads, as the + /// PR page lists them. + func pullRequestHandoffItems( + of pullRequest: PullRequest, + in worktree: Worktree, + ) -> [PullRequestHandoffItem] { + PullRequestHandoffItem.items( + checks: mergeReadiness(of: pullRequest, in: worktree).checks, + headCommit: pullRequest.headCommit, + threads: unresolvedThreads(of: pullRequest, in: worktree), + ) + } +} diff --git a/Tests/MultishellAppCoreTests/CIHandoffItem+Items.swift b/Tests/MultishellAppCoreTests/CIHandoffItem+Items.swift new file mode 100644 index 00000000..0c5735de --- /dev/null +++ b/Tests/MultishellAppCoreTests/CIHandoffItem+Items.swift @@ -0,0 +1,14 @@ +import MultishellServices + +@testable import MultishellAppCore + +extension CIHandoffItem { + static func items(of run: CIRun, workflows: [CIWorkflow], report: CIFailureReport?) -> [Self] { + items( + of: run, + workflows: workflows, + report: report, + unplaced: report?.unplaced(among: workflows) ?? [], + ) + } +} diff --git a/Tests/MultishellAppCoreTests/FakePullRequestHost.swift b/Tests/MultishellAppCoreTests/FakePullRequestHost.swift index fbae8d86..008c9b48 100644 --- a/Tests/MultishellAppCoreTests/FakePullRequestHost.swift +++ b/Tests/MultishellAppCoreTests/FakePullRequestHost.swift @@ -10,6 +10,7 @@ final class FakePullRequestHost: PullRequestHost { private struct State { var answer: Result<[PullRequest], ServiceReadFailure> = .success([]) var checks: [PullRequestCheck] = [] + var checksFailure: ServiceReadFailure? var headCommit: String? var calls: [String] = [] var branchAnswers: [String: Result<[PullRequest], ServiceReadFailure>] = [:] @@ -25,6 +26,10 @@ final class FakePullRequestHost: PullRequestHost { var renamedRepositories: [String: RemoteRepository] = [:] var askedRemoteURLs: [String] = [] var repositoryFailures: [ServiceReadFailure] = [] + var logs: [URL: Result] = [:] + var threads: Result<[PullRequestThread], ServiceReadFailure> = .success([]) + var holdsLogs = false + var holdsThreads = false } private let state = Mutex(State()) @@ -108,6 +113,11 @@ final class FakePullRequestHost: PullRequestHost { state.withLock { $0.checks = checks } } + /// Every check read fails as `failure`, as a logged-out `gh` would. + func failChecks(_ failure: ServiceReadFailure) { + state.withLock { $0.checksFailure = failure } + } + func checks(of pullRequest: PullRequest, in directory: URL) async throws -> [PullRequestCheck] { let holds = state.withLock { state in state.calls.append("checks #\(pullRequest.number)") @@ -116,7 +126,65 @@ final class FakePullRequestHost: PullRequestHost { if holds { for await _ in heldReads.stream {} } - return state.withLock { $0.checks } + return try state.withLock { state in + if let failure = state.checksFailure { throw failure } + return state.checks + } + } + + /// A check whose link has no log set is from another CI, and has none. + func answerLog(of link: URL, _ answer: Result) { + state.withLock { $0.logs[link] = answer } + } + + /// Every log read waits, as a slow `gh` would, until `releaseHeldReads`. + func holdLogs() { + state.withLock { $0.holdsLogs = true } + } + + func readsFailedLog(of check: PullRequestCheck) -> Bool { + state.withLock { state in check.link.flatMap { state.logs[$0] } != nil } + } + + func failedLog( + of check: PullRequestCheck, + keepingLast lineLimit: Int, + in directory: URL, + ) async throws -> FailedCheckLog? { + let holds = state.withLock { state in + state.calls.append("log \(check.name)") + return state.holdsLogs + } + if holds { + for await _ in heldReads.stream {} + } + return try state.withLock { state in + try check.link.flatMap { state.logs[$0] }?.get() + } + .map { FailedCheckLog(text: $0, earlierLineCount: 0) } + } + + func answerThreads(_ answer: Result<[PullRequestThread], ServiceReadFailure>) { + state.withLock { $0.threads = answer } + } + + /// Every thread read waits until `releaseHeldReads`. + func holdThreads() { + state.withLock { $0.holdsThreads = true } + } + + func unresolvedThreads( + of pullRequest: PullRequest, + in directory: URL, + ) async throws -> [PullRequestThread] { + let holds = state.withLock { state in + state.calls.append("threads #\(pullRequest.number)") + return state.holdsThreads + } + if holds { + for await _ in heldReads.stream {} + } + return try state.withLock { try $0.threads.get() } } func headCommit(of pullRequest: PullRequest, in directory: URL) async throws -> String { diff --git a/Tests/MultishellAppCoreTests/Files/Panel/Handoff/HandoffChoicesTests.swift b/Tests/MultishellAppCoreTests/Files/Panel/Handoff/HandoffChoicesTests.swift new file mode 100644 index 00000000..c46ee543 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Files/Panel/Handoff/HandoffChoicesTests.swift @@ -0,0 +1,78 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore + +@Suite +struct HandoffChoicesTests { + private static let lint = HandoffCandidate(.check(name: "lint", link: nil, headCommit: "tip")) + private static let danger = HandoffCandidate( + .check(name: "danger", link: nil, headCommit: "tip"), + startsChecked: false, + ) + + @Test func aFailingRequiredCheckStartsCheckedAndAnOptionalOneUnchecked() { + let choices = HandoffChoices() + + #expect(choices.state(of: Self.lint) == .checked) + #expect(choices.state(of: Self.danger) == .unchecked) + } + + @Test func theStepsBoxIsMixedWhileSomeUnsentItemsAreChecked() { + let choices = HandoffChoices() + + #expect(choices.groupState(of: [Self.lint, Self.danger]) == .mixed) + #expect(choices.groupState(of: [Self.lint]) == .checked) + #expect(choices.groupState(of: [Self.danger]) == .unchecked) + } + + @Test func aClickOnAMixedStepBoxChecksEveryItemAndASecondUnchecksThem() { + var choices = HandoffChoices() + + choices.toggleGroup([Self.lint, Self.danger]) + #expect(choices.groupState(of: [Self.lint, Self.danger]) == .checked) + + choices.toggleGroup([Self.lint, Self.danger]) + #expect(choices.groupState(of: [Self.lint, Self.danger]) == .unchecked) + } + + @Test func aSentItemWearsTheAgentAndLeavesTheStepsBoxToTheUnsentOnes() { + var choices = HandoffChoices() + + choices.markSent([Self.lint.id], to: "Claude Code") + + #expect(choices.state(of: Self.lint) == .sent(agentName: "Claude Code")) + #expect(choices.groupState(of: [Self.lint, Self.danger]) == .unchecked) + #expect(choices.groupState(of: [Self.lint]) == nil) + } + + @Test func aStepToggleLeavesASentItemSent() { + var choices = HandoffChoices() + choices.markSent([Self.lint.id], to: "Claude Code") + + choices.toggleGroup([Self.lint, Self.danger]) + + #expect(choices.state(of: Self.lint) == .sent(agentName: "Claude Code")) + #expect(choices.state(of: Self.danger) == .checked) + } + + @Test func aClickOnTheSentBubbleChecksTheItemToSendAgain() { + var choices = HandoffChoices() + choices.markSent([Self.danger.id], to: "Claude Code") + + choices.unmarkSent(Self.danger.id) + + #expect(choices.state(of: Self.danger) == .checked) + } + + @Test func keepingOnlyWhatIsListedDropsThePicksAndMarksOfItemsGone() { + var choices = HandoffChoices() + choices.markSent([Self.lint.id], to: "Claude Code") + choices.set(Self.danger.id, checked: true) + + choices.keepOnly([Self.danger.id], from: .checks) + + #expect(choices.state(of: Self.lint) == .checked) + #expect(choices.state(of: Self.danger) == .checked) + } +} diff --git a/Tests/MultishellAppCoreTests/Files/Panel/Handoff/HandoffLogTailTests.swift b/Tests/MultishellAppCoreTests/Files/Panel/Handoff/HandoffLogTailTests.swift new file mode 100644 index 00000000..f69cd53e --- /dev/null +++ b/Tests/MultishellAppCoreTests/Files/Panel/Handoff/HandoffLogTailTests.swift @@ -0,0 +1,20 @@ +import Testing + +@testable import MultishellAppCore + +@Suite +struct HandoffLogTailTests { + @Test func carriageReturnsAreDroppedWithTheBlankLinesAtTheEnd() { + let tail = HandoffLogTail.lines(of: "error: boom\r\n at App.swift:12\r\n\r\n") + + #expect(tail.lines == ["error: boom", " at App.swift:12"]) + #expect(tail.cutCount == 0) + } + + @Test func aProgressBarsBareCarriageReturnsStayInsideItsOneLine() { + let tail = HandoffLogTail.lines(of: "10%\r50%\r100%\nerror: boom") + + #expect(tail.lines == ["10%\r50%\r100%", "error: boom"]) + #expect(tail.cutCount == 0) + } +} diff --git a/Tests/MultishellAppCoreTests/GitHarness+ServiceHandoff.swift b/Tests/MultishellAppCoreTests/GitHarness+ServiceHandoff.swift new file mode 100644 index 00000000..65120024 --- /dev/null +++ b/Tests/MultishellAppCoreTests/GitHarness+ServiceHandoff.swift @@ -0,0 +1,82 @@ +import Foundation +import TestScratch +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore +@testable import MultishellServices + +extension GitHarness { + static let failingCheckLink = URL(string: "https://github.com/me/demo/actions/runs/7/job/9")! + + static let failedRunWorkflows = [ + CIWorkflow( + name: "build", + status: .failed, + jobs: [ + CIJob(id: "11", name: "lint", status: .passed), + CIJob(id: "12", name: "test-macos", status: .failed), + ], + ) + ] + + /// A PR page Send for `worktree` is reading its checks' logs. + func readsLogs(of worktree: Worktree) -> Bool { + if case .readingLogs = model.handoff.sendPhases[worktree.id] { true } else { false } + } + + /// `feat` pushed with pull request #9 open, `test` failing on it, one thread + /// unresolved, the PR page read and a Claude Code tab open in it. + func showingAFailingPullRequest() async throws + -> (Worktree, FakePullRequestHost, TerminalSession) + { + let (host, _) = connectServices() + try await addOrigin() + let feat = try await createWorktree(onBranch: "feat") + try await pushToGitHubOrigin(feat) + let tip = try await tip(of: feat) + host.answer(.success([.sample(number: 9, headBranch: "feat", headCommit: tip)])) + host.answerChecks([.sample(name: "test", status: .failed, link: Self.failingCheckLink)]) + host.answerLog(of: Self.failingCheckLink, .success("error: boom")) + host.answerThreads(.success([.sample()])) + await model.refreshBranchScan(of: project) + await model.refreshServices(ofProject: project.id) + model.select(feat) + model.setShowsFilesPanel(true) + model.setFilesPanelMode(.pullRequest) + try await waitUntil { + model.remoteState.checks[feat.id]?.checks != nil + && model.remoteState.threads[feat.id]?.threads != nil + } + return (feat, host, try openClaudeTab(in: feat)) + } + + /// `feat` pushed, its newest run failed in `test-macos` with the fake's + /// report read, and a Claude Code tab open in it. + func showingAFailedRun() async throws -> (Worktree, TerminalSession, FakeCIProvider) { + let (_, provider) = connectServices() + try writeCIConfiguration() + try await addOrigin() + let feat = try await createWorktree(onBranch: "feat") + try await pushToGitHubOrigin(feat) + let tip = try await tip(of: feat) + let run = CIRun.sample(id: "r2", branch: "feat", commit: tip, status: .failed) + provider.answer(recent: [run], workflows: Self.failedRunWorkflows, history: [run]) + await model.refreshBranchScan(of: project) + await model.refreshServices(ofProject: project.id) + model.select(feat) + model.setShowsFilesPanel(true) + model.setFilesPanelMode(.ciRuns) + try await waitUntil { + model.remoteState.failureReports["r2"] != nil + && model.remoteState.ciWorkflows["r2"] != nil + } + return (feat, try openClaudeTab(in: feat), provider) + } + + private func openClaudeTab(in worktree: Worktree) throws -> TerminalSession { + store.openTab(in: worktree.id, title: "claude", agentID: AgentCatalogue.claudeID) + model.reconcileSessions(takingFocus: true) + return try #require(model.workspace.sessions(in: worktree.id).first { $0.agentID != nil }) + } +} diff --git a/Tests/MultishellAppCoreTests/HandoffDrops.swift b/Tests/MultishellAppCoreTests/HandoffDrops.swift new file mode 100644 index 00000000..99f330ca --- /dev/null +++ b/Tests/MultishellAppCoreTests/HandoffDrops.swift @@ -0,0 +1,15 @@ +import Foundation + +/// The files Sends wrote under a drops directory, a folder for each Send. +enum HandoffDrops { + static func files(in drops: URL) -> [URL] { + let manager = FileManager.default + let directories = (try? manager.contentsOfDirectory(atPath: drops.path)) ?? [] + return directories.flatMap { name in + let directory = drops.appendingPathComponent(name, isDirectory: true) + return ((try? manager.contentsOfDirectory(atPath: directory.path)) ?? []).map { file in + directory.appendingPathComponent(file, isDirectory: false) + } + } + } +} diff --git a/Tests/MultishellAppCoreTests/HandoffSendOutcome+SentItemCount.swift b/Tests/MultishellAppCoreTests/HandoffSendOutcome+SentItemCount.swift new file mode 100644 index 00000000..bd619ea0 --- /dev/null +++ b/Tests/MultishellAppCoreTests/HandoffSendOutcome+SentItemCount.swift @@ -0,0 +1,8 @@ +@testable import MultishellAppCore + +extension HandoffSendOutcome { + /// How many items went, `nil` for a Send that sent nothing. + var sentItemCount: Int? { + if case .sent(let itemCount, _) = self { itemCount } else { nil } + } +} diff --git a/Tests/MultishellAppCoreTests/MainActorBox.swift b/Tests/MultishellAppCoreTests/MainActorBox.swift new file mode 100644 index 00000000..b40ebbbf --- /dev/null +++ b/Tests/MultishellAppCoreTests/MainActorBox.swift @@ -0,0 +1,5 @@ +/// What a task on the main actor answered, for a test that cannot await it first. +@MainActor +final class MainActorBox { + var value: Value? +} diff --git a/Tests/MultishellAppCoreTests/MergePath+Sample.swift b/Tests/MultishellAppCoreTests/MergePath+Sample.swift index ff249963..38f96652 100644 --- a/Tests/MultishellAppCoreTests/MergePath+Sample.swift +++ b/Tests/MultishellAppCoreTests/MergePath+Sample.swift @@ -8,6 +8,7 @@ extension MergePath { isMergeTaken: Bool = false, isOutgrown: Bool = false, checksReadProblem: String? = nil, + unresolvedThreadCount: Int = 0, ) -> Self { MergePath( pullRequest, @@ -15,6 +16,7 @@ extension MergePath { isMergeTaken: isMergeTaken, isOutgrown: isOutgrown, checksReadProblem: checksReadProblem, + unresolvedThreadCount: unresolvedThreadCount, ) } } diff --git a/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlHandoffTests.swift b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlHandoffTests.swift new file mode 100644 index 00000000..2eab16c7 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlHandoffTests.swift @@ -0,0 +1,261 @@ +import Foundation +import TestScratch +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore +@testable import MultishellServices + +@MainActor +@Suite +struct AppModelControlHandoffTests { + private static func sendPullRequestFeedback( + to sessionID: UUID? = nil, + includesChecks: Bool = true, + includesThreads: Bool = true, + ) -> ControlRequest { + .sendPullRequestFeedback( + worktree: nil, + to: sessionID, + includesChecks: includesChecks, + includesThreads: includesThreads, + ) + } + + @Test func prSendGivesThePickersAgentEveryCheckedItemAndSaysHowManyWentWhere() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + + let reply = await harness.model.answer(Self.sendPullRequestFeedback()) + + let fields = reply.outputFields + #expect(fields["worktree"] as? String == ControlID.worktree(feat.id)) + #expect(fields["pane"] as? String == agent.id.uuidString) + #expect(fields["agent"] as? String == "Claude Code") + #expect(fields["itemCount"] as? Int == 2) + #expect(harness.engine.pasted.map(\.id) == [agent.id]) + } + + @Test func prSendLeavesTheKeyboardWhereItWas() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + _ = try await harness.showingAFailingPullRequest() + let focusedBefore = harness.engine.focused + + _ = await harness.model.answer(Self.sendPullRequestFeedback()) + + #expect(!harness.engine.pasted.isEmpty) + #expect(harness.engine.focused == focusedBefore) + } + + @Test func prSendWithChecksAloneSendsTheCheckAndLeavesTheThreadChecked() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + + let reply = await harness.model.answer(Self.sendPullRequestFeedback(includesThreads: false)) + + #expect(reply.outputFields["itemCount"] as? Int == 1) + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + let states = harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).map { item in + harness.model.handoffState(of: item.candidate, in: feat.id) + } + #expect(states == [.sent(agentName: "Claude Code"), .checked]) + } + + @Test func prSendWithNothingCheckedIsRefusedAsNothingToHandOff() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + for item in harness.model.pullRequestHandoffItems(of: pullRequest, in: feat) { + harness.model.toggleHandoffItem(item.candidate, in: feat.id) + } + + let reply = await harness.model.answer(Self.sendPullRequestFeedback()) + + #expect(reply == .refused(.nothingToHandOff(.pullRequest, id: ControlID.worktree(feat.id)))) + #expect(harness.engine.pasted.isEmpty) + } + + @Test func prSendWithThreadsAloneWhereOnlyTheCheckIsCheckedIsRefused() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + let thread = try #require( + harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).last + ) + harness.model.toggleHandoffItem(thread.candidate, in: feat.id) + + let reply = await harness.model.answer(Self.sendPullRequestFeedback(includesChecks: false)) + + #expect(reply == .refused(.nothingToHandOff(.pullRequest, id: ControlID.worktree(feat.id)))) + } + + @Test func prSendToAShellPaneIsRefusedAsHavingNoAgentToSendTo() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + harness.store.openTab(in: feat.id, title: "Shell") + harness.model.reconcileSessions(takingFocus: false) + let shell = try #require( + harness.model.workspace.sessions(in: feat.id).first { $0.agentID == nil } + ) + + let reply = await harness.model.answer(Self.sendPullRequestFeedback(to: shell.id)) + + #expect(reply == .refused(.noRecipient(id: ControlID.worktree(feat.id)))) + #expect(harness.model.handoffMiss(of: feat, on: .pullRequest) == nil) + } + + @Test func prSendForAWorktreeWithNoPullRequestIsRefusedAsHavingNoPage() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + _ = try await harness.showingAFailingPullRequest() + let main = try #require(harness.worktree(onBranch: "main")) + let mainID = ControlID.worktree(main.id) + + let reply = await harness.model.answer( + .sendPullRequestFeedback( + worktree: mainID, + to: nil, + includesChecks: true, + includesThreads: true, + ) + ) + + #expect(reply == .refused(.noServicePage(.pullRequest, id: mainID))) + } + + @Test func prSendWhileAnotherSendReadsLogsIsRefusedAsReading() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.holdLogs() + let first = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + + let reply = await harness.model.answer(Self.sendPullRequestFeedback()) + host.releaseHeldReads() + _ = await first.value + + #expect(reply == .refused(.handoffUnderWay(id: ControlID.worktree(feat.id)))) + #expect(harness.engine.pasted.map(\.id) == [agent.id]) + } + + @Test func prSendToAPaneClosedWhileItsLogsWereReadIsRefusedAsNoAgent() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.holdLogs() + let asking = Task { await harness.model.answer(Self.sendPullRequestFeedback()) } + try await waitUntil { harness.readsLogs(of: feat) } + let tab = try #require(harness.model.workspace.tab(owning: agent.id)) + + harness.model.closeTab(tab.id) + host.releaseHeldReads() + let reply = await asking.value + + #expect(reply == .refused(.noRecipient(id: ControlID.worktree(feat.id)))) + #expect(harness.engine.pasted.isEmpty) + } + + @Test func ciSendGivesThePickersAgentTheNewestRunsFailedJob() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + + let reply = await harness.model.answer(.sendCIFailures(worktree: nil, to: nil)) + + let fields = reply.outputFields + #expect(fields["worktree"] as? String == ControlID.worktree(feat.id)) + #expect(fields["pane"] as? String == agent.id.uuidString) + #expect(fields["agent"] as? String == "Claude Code") + #expect(fields["itemCount"] as? Int == 1) + #expect(harness.engine.pasted.map(\.id) == [agent.id]) + } + + @Test func ciSendWithTheFailedJobUncheckedIsRefusedAsNothingToHandOff() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailedRun() + let run = try #require(harness.model.services(of: feat).ciRun) + for item in harness.model.ciHandoffItems(of: run) { + harness.model.toggleHandoffItem(item.candidate, in: feat.id) + } + + let reply = await harness.model.answer(.sendCIFailures(worktree: nil, to: nil)) + + #expect(reply == .refused(.nothingToHandOff(.ciRuns, id: ControlID.worktree(feat.id)))) + #expect(harness.engine.pasted.isEmpty) + } + + @Test func ciSendForAWorktreeWithNoRunIsRefusedAsHavingNoPage() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + _ = try await harness.showingAFailedRun() + let main = try #require(harness.worktree(onBranch: "main")) + let mainID = ControlID.worktree(main.id) + + let reply = await harness.model.answer(.sendCIFailures(worktree: mainID, to: nil)) + + #expect(reply == .refused(.noServicePage(.ciRuns, id: mainID))) + } + + @Test func prSendWhoseItemsWereAllUncheckedDuringTheReadIsRefusedAsNothingToHandOff() async throws + { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, _) = try await harness.showingAFailingPullRequest() + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + let candidates = harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).map( + \.candidate + ) + host.holdLogs() + + let asking = Task { await harness.model.answer(Self.sendPullRequestFeedback()) } + try await waitUntil { harness.readsLogs(of: feat) } + harness.model.toggleHandoffGroup(candidates, in: feat.id) + host.releaseHeldReads() + let reply = await asking.value + + #expect(reply == .refused(.nothingToHandOff(.pullRequest, id: ControlID.worktree(feat.id)))) + #expect(harness.engine.pasted.isEmpty) + } + + @Test func prSendOfThreadsAloneGoesWhileAnotherSendReadsLogs() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.holdLogs() + let first = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + + let reply = await harness.model.answer(Self.sendPullRequestFeedback(includesChecks: false)) + host.releaseHeldReads() + _ = await first.value + + #expect(reply.outputFields["itemCount"] as? Int == 1) + } + + @Test func ciSendWithNothingCheckedAndNoAgentIsRefusedAsNothingToHandOff() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + let run = CIRun.sample(id: "r2", status: .failed) + let candidates = harness.model.ciHandoffItems(of: run).map(\.candidate) + harness.model.toggleHandoffGroup(candidates, in: feat.id) + let tab = try #require(harness.model.workspace.tab(owning: agent.id)) + harness.model.closeTab(tab.id) + + let reply = await harness.model.answer(.sendCIFailures(worktree: nil, to: nil)) + + #expect(reply == .refused(.nothingToHandOff(.ciRuns, id: ControlID.worktree(feat.id)))) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlReviewTests.swift b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlReviewTests.swift index a7bb7e3e..31983be1 100644 --- a/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlReviewTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Control/AppModel+ControlReviewTests.swift @@ -107,7 +107,7 @@ struct AppModelControlReviewTests { ) #expect( await harness.messageSource.ask(.sendReview(worktree: nil, to: shell.id)) - == .refused(.noReviewRecipient(id: worktree)) + == .refused(.noRecipient(id: worktree)) ) } @@ -138,6 +138,29 @@ struct AppModelControlReviewTests { #expect(harness.engine.focused == focusedBefore) } + @Test func aFileThatCannotBeWrittenIsAnsweredByTheWritesAlertNotAsAPaneWithNoShell() async throws + { + let (harness, _) = try Self.harnessWithFileRead() + _ = await harness.messageSource.ask( + .addReviewComment(Self.order(1...1, side: .onDisk, text: "One")) + ) + let drops = harness.model.dropsDirectory + try? FileManager.default.removeItem(at: drops) + try FileManager.default.createDirectory( + at: drops.deletingLastPathComponent(), + withIntermediateDirectories: true, + ) + try Data("not a directory".utf8).write(to: drops) + + let reply = await harness.messageSource.ask(.sendReview(worktree: nil, to: nil)) + + guard case .alert(_, let message) = reply?.refusal else { + Issue.record("Expected the write's alert, got \(String(describing: reply))") + return + } + #expect(message.contains("drops")) + } + @Test func clearSentLeavesThePendingAndClearRemovesEverything() async throws { let (harness, _) = try Self.harnessWithFileRead() _ = await harness.messageSource.ask( diff --git a/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+CIHandoffTests.swift b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+CIHandoffTests.swift new file mode 100644 index 00000000..4d083011 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+CIHandoffTests.swift @@ -0,0 +1,174 @@ +import Foundation +import TestScratch +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore +@testable import MultishellServices + +@MainActor +@Suite +struct AppModelCIHandoffTests { + /// As the CI page draws its foot, over the items it built for its rows. + private static func footer(of worktree: Worktree, in harness: GitHarness) -> HandoffFooter? { + guard case .run(let run) = harness.model.ciPage(of: worktree) else { return nil } + return harness.model.ciHandoffFooter( + of: worktree, + over: harness.model.ciWorkflowListing(of: run, sendsFailures: true), + ) + } + + @Test func theNewestRunsFailedJobIsCheckedAndSendIsOffered() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + + let footer = Self.footer(of: feat, in: harness) + + guard case .ready(let picked, _, let canSend) = footer else { + Issue.record("the foot offers Send, not \(String(describing: footer))") + return + } + #expect(picked.id == agent.id) + #expect(canSend) + } + + @Test func sendWritesTheJobAndItsReportThenPastesAMentionAndMarksItSent() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + + let outcome = harness.model.sendCIFailures(of: feat.id, to: agent.id, takingFocus: false) + + #expect(outcome.sentItemCount == 1) + let file = try #require(HandoffDrops.files(in: harness.model.dropsDirectory).first) + let text = try String(contentsOf: file, encoding: .utf8) + #expect(file.lastPathComponent == "ci-feat.md") + #expect(text.contains("## build / test-macos")) + #expect(text.contains(" test-macos failed")) + #expect(harness.engine.pasted.map(\.id) == [agent.id]) + let item = try #require( + harness.model.ciHandoffItems(of: .sample(id: "r2", status: .failed)).first + ) + #expect( + harness.model.handoffState(of: item.candidate, in: feat.id) == .sent(agentName: "Claude Code") + ) + #expect(Self.footer(of: feat, in: harness) == .sent(summary: "1 job sent to Claude Code")) + } + + @Test func aReportReadBeforeItsRunsWorkflowsOffersNothingToSendYet() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + _ = try await harness.showingAFailedRun() + let run = CIRun.sample(id: "r2", status: .failed) + try #require(harness.model.failureReport(of: run) != nil) + + harness.model.remoteState.ciWorkflows[run.id] = nil + + #expect(harness.model.ciHandoffItems(of: run).isEmpty) + } + + @Test func anUncheckedJobIsNotSentAndWithNothingCheckedSendIsOff() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + let item = try #require( + harness.model.ciHandoffItems(of: .sample(id: "r2", status: .failed)).first + ) + + harness.model.toggleHandoffItem(item.candidate, in: feat.id) + let outcome = harness.model.sendCIFailures(of: feat.id, to: agent.id, takingFocus: false) + + #expect(outcome == .nothingChecked) + #expect(harness.engine.pasted.isEmpty) + guard case .ready(_, _, let canSend) = Self.footer(of: feat, in: harness) else { + Issue.record("the foot still offers the picker") + return + } + #expect(!canSend) + } + + @Test func checkingAJobAgainAfterSendTurnsTheFootBackToSend() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + let item = try #require( + harness.model.ciHandoffItems(of: .sample(id: "r2", status: .failed)).first + ) + harness.model.sendCIFailures(of: feat.id, to: agent.id, takingFocus: false) + + harness.model.unmarkHandoffItemSent(item.candidate.id, in: feat.id) + + guard case .ready(_, _, let canSend) = Self.footer(of: feat, in: harness) else { + Issue.record("the foot offers Send again") + return + } + #expect(canSend) + } + + @Test func aNewerRunWithNothingToSendDropsWhatTheLastSendSaid() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, provider) = try await harness.showingAFailedRun() + harness.model.sendCIFailures(of: feat.id, to: agent.id, takingFocus: false) + let tip = try await harness.tip(of: feat) + let passed = CIRun.sample(id: "r3", branch: "feat", commit: tip, status: .passed) + provider.answer(recent: [passed], workflows: [], history: [passed]) + + await harness.model.refreshServices(ofProject: harness.project.id) + harness.model.remoteState.panelReadLog.forget(PanelRead(worktree: feat.id, page: .ciRuns)) + await harness.model.readPanelServicesIfDue(of: feat) + + #expect(harness.model.ciPage(of: feat) == .run(passed)) + #expect(Self.footer(of: feat, in: harness) == nil) + } + + @Test func aSentJobKeepsItsMarkThroughAPullRequestReadWhileItsRunDetailsAreUnloaded() async throws + { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + let item = try #require( + harness.model.ciHandoffItems(of: .sample(id: "r2", status: .failed)).first + ) + harness.model.sendCIFailures(of: feat.id, to: agent.id, takingFocus: false) + harness.model.remoteState.ciWorkflows["r2"] = nil + harness.model.remoteState.failureReports["r2"] = nil + + harness.model.setFilesPanelMode(.pullRequest) + await harness.model.readPanelServices(of: feat.id) + + #expect( + harness.model.handoffState(of: item.candidate, in: feat.id) == .sent(agentName: "Claude Code") + ) + } + + @Test func aSentRunOutputKeepsItsMarkWhileTheReportIsUnread() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, agent, _) = try await harness.showingAFailedRun() + let lintOnly = [ + CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "11", name: "lint", status: .failed)], + ) + ] + harness.model.remoteState.ciWorkflows["r2"] = CIRunDetail( + value: lintOnly, + runStatus: .failed, + runWasFinished: true, + ) + let run = CIRun.sample(id: "r2", status: .failed) + let output = try #require(harness.model.ciHandoffItems(of: run).first { $0.job == nil }) + harness.model.sendCIFailures(of: feat.id, to: agent.id, takingFocus: false) + harness.model.remoteState.failureReports["r2"] = nil + + harness.model.pruneHandoffChoices(of: feat, after: .ciRuns) + + #expect( + harness.model.handoffState(of: output.candidate, in: feat.id) + == .sent(agentName: "Claude Code") + ) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+ForgetHandoffStateTests.swift b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+ForgetHandoffStateTests.swift new file mode 100644 index 00000000..41dfbf37 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+ForgetHandoffStateTests.swift @@ -0,0 +1,46 @@ +import Foundation +import Observation +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore + +@MainActor +@Suite +struct AppModelForgetHandoffStateTests { + @Test func forgettingAWorktreeWithNoSendStateRedrawsNothing() { + let harness = Harness() + let wrote = AtomicFlag() + withObservationTracking { + _ = harness.model.handoff.recipientPicks + _ = harness.model.handoff.choices + _ = harness.model.handoff.receipts + _ = harness.model.handoff.misses + _ = harness.model.focusedSessionHistory + } onChange: { + wrote.raise() + } + + harness.model.forgetHandoffState(of: [harness.feature.id]) + + #expect(!wrote.raised) + } + + @Test func aRemovedWorktreeLosesItsPickChoicesReceiptsMissesAndFocusHistory() { + let harness = Harness() + let id = harness.feature.id + harness.model.pickHandoffRecipient(UUID(), in: id) + harness.model.focusedSessionHistory[id] = [UUID()] + harness.model.handoff.choices[id] = HandoffChoices() + harness.model.handoff.receipts[id] = [.ciRuns: "1 job sent to Claude Code"] + harness.model.noteHandoffMiss("Nothing was sent.", on: .pullRequest, in: id) + + harness.model.forgetHandoffState(of: [id]) + + #expect(harness.model.handoff.recipientPicks[id] == nil) + #expect(harness.model.focusedSessionHistory[id] == nil) + #expect(harness.model.handoff.choices[id] == nil) + #expect(harness.model.handoff.receipts[id] == nil) + #expect(harness.model.handoff.misses[id] == nil) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+HandoffChoicesTests.swift b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+HandoffChoicesTests.swift new file mode 100644 index 00000000..506f9ff8 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+HandoffChoicesTests.swift @@ -0,0 +1,44 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore + +@MainActor +@Suite +struct AppModelHandoffChoicesTests { + private static let lint = HandoffCandidate(.check(name: "lint", link: nil, headCommit: "tip")) + private static let danger = HandoffCandidate( + .check(name: "danger", link: nil, headCommit: "tip"), + startsChecked: false, + ) + + @Test func aCollapsedListSaysHowManyOfItsItemsSendCarries() { + let harness = Harness() + + let text = harness.model.handoffToSendText( + of: [Self.lint, Self.danger], + isCollapsed: true, + in: harness.main.id, + ) + + #expect(text == "1 to send") + } + + @Test func anOpenListOrOneWithNothingCheckedSaysNothing() { + let harness = Harness() + + let open = harness.model.handoffToSendText( + of: [Self.lint], + isCollapsed: false, + in: harness.main.id, + ) + let unchecked = harness.model.handoffToSendText( + of: [Self.danger], + isCollapsed: true, + in: harness.main.id, + ) + + #expect(open == nil) + #expect(unchecked == nil) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+HandoffRecipientsTests.swift b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+HandoffRecipientsTests.swift new file mode 100644 index 00000000..d2eefe70 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+HandoffRecipientsTests.swift @@ -0,0 +1,26 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore + +@MainActor +@Suite +struct AppModelHandoffRecipientsTests { + @Test func theAgentFocusedLastIsWhereASendGoesUnlessOneIsPicked() { + let harness = Harness() + harness.model.select(harness.main) + harness.store.openTab(in: harness.main.id, title: "claude", agentID: AgentCatalogue.claudeID) + harness.store.openTab(in: harness.main.id, title: "codex", agentID: AgentCatalogue.codexID) + harness.model.reconcileSessions(takingFocus: true) + let agents = harness.model.workspace.sessions(in: harness.main.id).filter { $0.agentID != nil } + let claude = agents[0].id + let codex = agents[1].id + + harness.model.reconciler.terminalHost(harness.engine, didFocus: codex) + harness.model.reconciler.terminalHost(harness.engine, didFocus: claude) + #expect(harness.model.handoffRecipient(in: harness.main.id)?.id == claude) + + harness.model.pickHandoffRecipient(codex, in: harness.main.id) + #expect(harness.model.handoffRecipient(in: harness.main.id)?.id == codex) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+PullRequestHandoffTests.swift b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+PullRequestHandoffTests.swift new file mode 100644 index 00000000..cae1f948 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Model/Handoff/AppModel+PullRequestHandoffTests.swift @@ -0,0 +1,600 @@ +import Foundation +import TestScratch +import Testing + +@testable import MultishellAppCore +@testable import MultishellCore +@testable import MultishellServices + +@MainActor +@Suite +struct AppModelPullRequestHandoffTests { + /// As the PR page draws its foot, along the path it drew. + private static func footer(of worktree: Worktree, in harness: GitHarness) -> HandoffFooter? { + guard let pullRequest = harness.model.services(of: worktree).shownPullRequest else { + return nil + } + return harness.model.pullRequestHandoffFooter( + of: worktree, + along: harness.model.mergePath(of: pullRequest, in: worktree), + on: pullRequest, + threads: harness.model.unresolvedThreads(of: pullRequest, in: worktree), + ) + } + + private static func handoffText(in drops: URL) throws -> (name: String, text: String) { + let file = try #require(HandoffDrops.files(in: drops).first) + return (file.lastPathComponent, try String(contentsOf: file, encoding: .utf8)) + } + + @Test func theOpenPullRequestsUnresolvedThreadsAreReadWithItsChecks() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + + #expect(harness.model.unresolvedThreads(of: pullRequest, in: feat).map(\.id) == ["t1"]) + #expect(harness.model.mergePath(of: pullRequest, in: feat).threadsStep == .comments) + } + + @Test func sendReadsTheFailingChecksLogThenWritesItAndTheThreadAndMarksBothSent() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome.sentItemCount == 2) + #expect(host.calls.contains("log test")) + let file = try Self.handoffText(in: harness.model.dropsDirectory) + #expect(file.name == "pr-9-feat.md") + #expect(file.text.contains("## CI / test")) + #expect(file.text.contains(" error: boom")) + #expect(file.text.contains("## Sources/App.swift:12")) + #expect(harness.engine.pasted.map(\.id) == [agent.id]) + #expect( + Self.footer(of: feat, in: harness) + == .sent(summary: "2 items sent to Claude Code") + ) + } + + @Test func aPaneClosedWhileTheLogsWereReadGetsNothingAndTheFootSaysSo() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.holdLogs() + + let sending = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + #expect(Self.footer(of: feat, in: harness) == .reading("Reading 1 log")) + let tab = try #require(harness.model.workspace.tab(owning: agent.id)) + harness.model.closeTab(tab.id) + host.releaseHeldReads() + let outcome = await sending.value + + #expect(outcome == .noRecipient) + #expect(harness.engine.pasted.isEmpty) + #expect( + harness.model.handoffMiss(of: feat, on: .pullRequest) + == "Claude Code was gone by the time the logs were read. Nothing was sent." + ) + } + + @Test func aSendCancelledWhileItsLogsReadPastesNothingAndMarksNothingSent() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.holdLogs() + + let sending = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + sending.cancel() + host.releaseHeldReads() + let outcome = await sending.value + + #expect(outcome == .cancelled) + #expect(harness.engine.pasted.isEmpty) + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + let check = try #require( + harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).first + ) + #expect(harness.model.handoffState(of: check.candidate, in: feat.id) == .checked) + } + + @Test func returningToAWorktreeBeforeTheIntervalReadsItsThreadsAgain() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + let main = try #require(harness.worktree(onBranch: "main")) + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + + harness.model.select(main) + await harness.model.readPanelServicesIfDue(of: main) + harness.model.select(feat) + await harness.model.readPanelServicesIfDue(of: feat) + + #expect(harness.model.unresolvedThreads(of: pullRequest, in: feat).map(\.id) == ["t1"]) + } + + @Test func anItemUncheckedWhileTheLogsReadIsNotSent() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + let thread = try #require( + harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).last?.candidate + ) + host.holdLogs() + + let sending = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + harness.model.toggleHandoffItem(thread, in: feat.id) + host.releaseHeldReads() + _ = await sending.value + + let file = try Self.handoffText(in: harness.model.dropsDirectory) + #expect(!file.text.contains("Sources/App.swift:12")) + #expect(harness.model.handoffState(of: thread, in: feat.id) == .unchecked) + } + + @Test func aRemovedWorktreeKeepsNoThreadText() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + + harness.model.forgetWorktrees([feat.id]) + + #expect(harness.model.remoteState.threads[feat.id] == nil) + } + + @Test func aThreadReadLandingAfterThePanelMovedOnKeepsNoText() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, _) = try await harness.showingAFailingPullRequest() + let main = try #require(harness.worktree(onBranch: "main")) + harness.model.remoteState.panelReadLog.forget(PanelRead(worktree: feat.id, page: .pullRequest)) + let threadReadsBefore = host.calls.count { $0 == "threads #9" } + host.holdThreads() + + let reading = Task { await harness.model.readPanelServices(of: feat.id) } + try await waitUntil { host.calls.count { $0 == "threads #9" } > threadReadsBefore } + harness.model.select(main) + harness.model.remoteState.threads[feat.id] = nil + host.releaseHeldReads() + _ = await reading.value + + #expect(harness.model.remoteState.threads[feat.id] == nil) + } + + @Test func aMergedPullRequestCarriesNoneOfItsCachedThreadsToSend() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, _) = try await harness.showingAFailingPullRequest() + let tip = try await harness.tip(of: feat) + host.answer( + .success([.sample(number: 9, state: .merged, headBranch: "feat", headCommit: tip)]) + ) + + await harness.model.refreshServices(ofProject: harness.project.id) + + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + try #require(pullRequest.state == .merged) + let threads = harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).filter { item in + if case .thread = item { true } else { false } + } + #expect(threads.isEmpty) + } + + @Test func aThreadReReadWhileTheLogsReadIsStillSent() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.holdLogs() + + let sending = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + host.answerThreads(.success([.sample(isOutdated: true)])) + await harness.model.readPanelServices(of: feat.id) + host.releaseHeldReads() + let outcome = await sending.value + + #expect(outcome.sentItemCount == 2) + } + + @Test func selectingAWorktreeOnAnotherPageDropsTheLastOnesThreadText() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + let main = try #require(harness.worktree(onBranch: "main")) + harness.model.setFilesPanelMode(.files) + + harness.model.select(main) + harness.model.schedulePanelServicesRead(of: main.id) + try await waitUntil { harness.model.remoteState.threads[feat.id] == nil } + + #expect(harness.model.remoteState.threads[feat.id] == nil) + } + + @Test func aSendThePaneTookNoPasteOfSaysSoOverTheFoot() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + harness.engine.liveSessionIDs.remove(agent.id) + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome == .notPasted(to: agent.id)) + #expect( + harness.model.handoffMiss(of: feat, on: .pullRequest) + == "Nothing was sent to Claude Code: its pane took no paste." + ) + } + + @Test func aSendForAWorktreeOffThePanelReadsItsThreadsRatherThanDroppingThem() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + harness.model.select(try #require(harness.worktree(onBranch: "main"))) + harness.model.remoteState.threads[feat.id] = nil + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome.sentItemCount == 2) + let file = try Self.handoffText(in: harness.model.dropsDirectory) + #expect(file.text.contains("## Sources/App.swift:12")) + } + + @Test func aPageWhoseThreadsCouldNotBeReadStillSendsItsCheckedCheck() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.answerThreads(.failure(.failed("SSO required"))) + harness.model.remoteState.threads[feat.id] = PullRequestThreads( + pullRequestNumber: 9, + threads: nil, + failure: .failed("SSO required"), + ) + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome.sentItemCount == 1) + } + + @Test func checksReadWhileThreadsFailStillLetGoOfAnOldHeadsPicks() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, _) = try await harness.showingAFailingPullRequest() + let oldHead = HandoffCandidate(.check(name: "CI / test", link: nil, headCommit: "old")) + harness.model.toggleHandoffItem(oldHead, in: feat.id) + harness.model.remoteState.threads[feat.id] = PullRequestThreads( + pullRequestNumber: 9, + threads: nil, + failure: .failed("SSO required"), + ) + + harness.model.pruneHandoffChoices(of: feat, after: .pullRequest) + + #expect(harness.model.handoffState(of: oldHead, in: feat.id) == .checked) + } + + @Test func aSecondSendWhileTheFirstReadsItsThreadsIsRefusedAsReading() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.model.select(try #require(harness.worktree(onBranch: "main"))) + harness.model.remoteState.threads[feat.id] = nil + let threadReadsBefore = host.calls.count { $0 == "threads #9" } + host.holdThreads() + + let first = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { host.calls.count { $0 == "threads #9" } > threadReadsBefore } + let secondOutcome = MainActorBox() + Task { + secondOutcome.value = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + } + try await waitUntil { secondOutcome.value != nil } + let beforeTheReadEnded = secondOutcome.value + host.releaseHeldReads() + _ = await first.value + + #expect(beforeTheReadEnded == .alreadySending) + } + + @Test func threadsAloneOnAPageWhoseThreadReadFailedSayWhy() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + harness.model.remoteState.threads[feat.id] = PullRequestThreads( + pullRequestNumber: 9, + threads: nil, + failure: .failed("SSO required"), + ) + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + includesChecks: false, + ) + + guard case .threadsNotRead = outcome else { + Issue.record("refused as the threads not read, not \(outcome)") + return + } + } + + @Test func aSendToAPaneClosedSinceThePickerDrewSaysSoOverTheFoot() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + let tab = try #require(harness.model.workspace.tab(owning: agent.id)) + harness.model.closeTab(tab.id) + + _ = await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + + #expect( + harness.model.handoffMiss(of: feat, on: .pullRequest) + == "The pane picked has closed. Pick another." + ) + } + + @Test func aFileThatCannotBeWrittenIsSaidByItsAlertAloneNotTwice() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + let drops = harness.model.dropsDirectory + try? FileManager.default.removeItem(at: drops) + try Data("not a directory".utf8).write(to: drops) + + _ = await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + + #expect(harness.model.presentedError != nil) + #expect(harness.model.handoffMiss(of: feat, on: .pullRequest) == nil) + } + + @Test func theFootCountsOnlyTheLogsTheHostCanRead() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + host.answerChecks([ + .sample(name: "test", status: .failed, link: GitHarness.failingCheckLink), + .sample( + name: "circle", + workflow: nil, + status: .failed, + link: URL(string: "https://circleci.com/x"), + ), + ]) + harness.model.remoteState.panelReadLog.forget(PanelRead(worktree: feat.id, page: .pullRequest)) + await harness.model.readPanelServices(of: feat.id) + host.holdLogs() + + let sending = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { harness.readsLogs(of: feat) } + let phase = harness.model.handoff.sendPhases[feat.id] + host.releaseHeldReads() + _ = await sending.value + + #expect(phase == .readingLogs(count: 1)) + } + + @Test func theFootSaysASendIsUnderWayBeforeItsLogsAreRead() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.model.select(try #require(harness.worktree(onBranch: "main"))) + harness.model.remoteState.threads[feat.id] = nil + let threadReadsBefore = host.calls.count { $0 == "threads #9" } + host.holdThreads() + + let sending = Task { + await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + } + try await waitUntil { host.calls.count { $0 == "threads #9" } > threadReadsBefore } + let footer = Self.footer(of: feat, in: harness) + host.releaseHeldReads() + _ = await sending.value + + guard case .reading = footer else { + Issue.record("the foot says the Send is under way, not \(String(describing: footer))") + return + } + } + + @Test func aPageSendBeforeItsFirstThreadReadSendsNoThreadItHasNotShown() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + harness.model.remoteState.threads[feat.id] = nil + + harness.model.select(feat) + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome.sentItemCount == 1) + } + + @Test func aSendForThePanelsWorktreeOnAnotherPageReadsItsThreadsRatherThanDroppingThem() + async throws + { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + harness.model.setFilesPanelMode(.files) + harness.model.select(feat) + harness.model.remoteState.threads[feat.id] = nil + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome.sentItemCount == 2) + } + + @Test func aSendForThePanelsWorktreeOnAnotherPageReadsItsThreadsAfreshNotAsLastShown() + async throws + { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.model.setFilesPanelMode(.files) + harness.model.select(feat) + host.answerThreads(.success([.sample(id: "t9", path: "Sources/New.swift")])) + + _ = await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + + let file = try Self.handoffText(in: harness.model.dropsDirectory) + #expect(file.text.contains("## Sources/New.swift:12")) + #expect(!file.text.contains("## Sources/App.swift:12")) + } + + @Test func aSendOffThePullRequestPageReadsItsChecksAfreshNotAsLastShown() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.model.setFilesPanelMode(.files) + harness.model.select(feat) + host.answerChecks([.sample(name: "test", status: .passed, link: GitHarness.failingCheckLink)]) + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + ) + + #expect(outcome.sentItemCount == 1) + } + + @Test func aSendWhileTheAppIsInTheBackgroundReadsAfreshAsThePagePausedItsReads() + async throws + { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.platform.isActive = false + host.answerThreads(.success([.sample(id: "t9", path: "Sources/New.swift")])) + + _ = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + includesChecks: false, + ) + + let file = try Self.handoffText(in: harness.model.dropsDirectory) + #expect(file.text.contains("## Sources/New.swift:12")) + } + + @Test func checksReadOffThePageAfterAPushAreCaptionedWithTheHeadTheyRanOn() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.model.setFilesPanelMode(.files) + harness.model.select(feat) + host.answerHeadCommit("0123456789abcdef0123456789abcdef01234567") + + _ = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + includesThreads: false, + ) + + let file = try Self.handoffText(in: harness.model.dropsDirectory) + #expect(file.text.contains("This ran on 0123456")) + } + + @Test func checksAloneOnAPageWhoseChecksReadFailedSayWhy() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + harness.model.remoteState.checks[feat.id] = PullRequestChecks( + pullRequestNumber: pullRequest.number, + headCommit: pullRequest.headCommit, + checks: nil, + failure: .failed("SSO required"), + ) + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + includesThreads: false, + ) + + #expect(outcome == .checksNotRead(reason: "SSO required")) + } + + @Test func checksAloneOffThePullRequestPageWhoseReadFailsSayWhy() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, agent) = try await harness.showingAFailingPullRequest() + harness.model.setFilesPanelMode(.files) + harness.model.select(feat) + host.failChecks(.failed("SSO required")) + + let outcome = await harness.model.sendPullRequestFeedback( + of: feat.id, + to: agent.id, + takingFocus: false, + includesThreads: false, + ) + + #expect(outcome == .checksNotRead(reason: "SSO required")) + #expect(harness.engine.pasted.isEmpty) + } + + @Test func aSendThatFindsNothingCheckedClearsTheLastMissNote() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, _, agent) = try await harness.showingAFailingPullRequest() + harness.model.noteHandoffMiss("an old note", on: .pullRequest, in: feat.id) + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + let candidates = harness.model.pullRequestHandoffItems(of: pullRequest, in: feat).map( + \.candidate + ) + harness.model.toggleHandoffGroup(candidates, in: feat.id) + + _ = await harness.model.sendPullRequestFeedback(of: feat.id, to: agent.id, takingFocus: false) + + #expect(harness.model.handoffMiss(of: feat, on: .pullRequest) == nil) + } +} diff --git a/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewCommentsTests.swift b/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewCommentsTests.swift index f0072544..cbfb38fc 100644 --- a/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewCommentsTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewCommentsTests.swift @@ -162,9 +162,7 @@ struct AppModelReviewCommentsTests { let wrote = AtomicFlag() withObservationTracking { _ = harness.model.selectedReviewComments - _ = harness.model.reviewRecipientPicks _ = harness.model.reviewSendReceipts - _ = harness.model.focusedSessionHistory } onChange: { wrote.raise() } diff --git a/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewPageTests.swift b/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewPageTests.swift index 9967c87b..70cc87dc 100644 --- a/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewPageTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewPageTests.swift @@ -55,11 +55,11 @@ struct AppModelReviewPageTests { harness.model.sendReviewToPickedAgent(of: harness.main) - guard case .sent(let receipt) = harness.model.reviewFooter(of: harness.main) else { + guard case .sent(let summary) = harness.model.reviewFooter(of: harness.main) else { Issue.record("the footer says what was sent") return } - #expect(receipt.summary == "1 comment sent to Claude Code") + #expect(summary == "1 comment sent to Claude Code") } @Test func aRemovedLinesCommentHasNoScopeNoteWhereBranchFallsBackToModified() throws { diff --git a/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewSendTests.swift b/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewSendTests.swift index e95128d8..96e7b61a 100644 --- a/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewSendTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Review/AppModel+ReviewSendTests.swift @@ -34,17 +34,6 @@ struct AppModelReviewSendTests { } /// Spelled from `drops` as given, a listing naming the temporary directory's `/private` target. - private static func handoffFiles(in drops: URL) -> [URL] { - let manager = FileManager.default - let directories = (try? manager.contentsOfDirectory(atPath: drops.path)) ?? [] - return directories.flatMap { name in - let directory = drops.appendingPathComponent(name, isDirectory: true) - return ((try? manager.contentsOfDirectory(atPath: directory.path)) ?? []).map { file in - directory.appendingPathComponent(file, isDirectory: false) - } - } - } - @Test func claudeCodeIsHandedAMentionOfTheReviewFileWithItsSpacesEscaped() throws { let (harness, agents) = Self.harness(withAgents: [AgentCatalogue.claudeID]) let drops = harness.drops @@ -53,7 +42,7 @@ struct AppModelReviewSendTests { let sent = harness.model.sendReviewToPickedAgent(of: harness.main) #expect(sent) - let file = try #require(Self.handoffFiles(in: drops).first) + let file = try #require(HandoffDrops.files(in: drops).first) let escaped = file.path.replacingOccurrences(of: " ", with: "\\ ") #expect(harness.engine.pasted.map(\.id) == [agents[0].id]) #expect(harness.engine.pasted.map(\.text) == ["@\(escaped) "]) @@ -66,7 +55,7 @@ struct AppModelReviewSendTests { harness.model.sendReviewToPickedAgent(of: harness.main) - let file = try #require(Self.handoffFiles(in: harness.model.dropsDirectory).first) + let file = try #require(HandoffDrops.files(in: harness.model.dropsDirectory).first) let quoted = AnyShellQuoting.quote(file.path) #expect(harness.engine.pasted.map(\.text) == ["Address the review comments in \(quoted) "]) } @@ -94,7 +83,7 @@ struct AppModelReviewSendTests { #expect(!sent) #expect(harness.model.reviewComments(in: harness.main.id).allSatisfy { $0.isPending }) - #expect(Self.handoffFiles(in: harness.model.dropsDirectory).isEmpty) + #expect(HandoffDrops.files(in: harness.model.dropsDirectory).isEmpty) } @Test func sendGoesToTheAgentThePickerShowedOrNowhereOnceItsPaneCloses() throws { @@ -102,7 +91,7 @@ struct AppModelReviewSendTests { AgentCatalogue.claudeID, AgentCatalogue.codexID, ]) harness.model.addReviewComment(Self.comment(), in: harness.main.id) - harness.model.pickReviewRecipient(agents[0].id, in: harness.main.id) + harness.model.pickHandoffRecipient(agents[0].id, in: harness.main.id) guard case .ready(let picked, _, _) = harness.model.reviewFooter(of: harness.main) else { Issue.record("the footer offers the agent") return @@ -133,25 +122,10 @@ struct AppModelReviewSendTests { let (harness, _) = Harness.withOnePane() harness.model.addReviewComment(Self.comment(), in: harness.main.id) - #expect(harness.model.reviewRecipients(in: harness.main.id).isEmpty) + #expect(harness.model.handoffRecipients(in: harness.main.id).isEmpty) #expect(harness.model.reviewFooter(of: harness.main) == .noRecipient("No agent in main")) } - @Test func theAgentFocusedLastIsWhereAReviewGoesUnlessOneIsPicked() { - let (harness, agents) = Self.harness(withAgents: [ - AgentCatalogue.claudeID, AgentCatalogue.codexID, - ]) - let claude = agents[0].id - let codex = agents[1].id - - harness.model.reconciler.terminalHost(harness.engine, didFocus: codex) - harness.model.reconciler.terminalHost(harness.engine, didFocus: claude) - #expect(harness.model.reviewRecipient(in: harness.main.id)?.id == claude) - - harness.model.pickReviewRecipient(codex, in: harness.main.id) - #expect(harness.model.reviewRecipient(in: harness.main.id)?.id == codex) - } - @Test func addingACommentClearsWhatTheLastSendSaid() { let (harness, _) = Self.harness(withAgents: [AgentCatalogue.claudeID]) harness.model.addReviewComment(Self.comment(), in: harness.main.id) @@ -182,7 +156,7 @@ struct AppModelReviewSendTests { @Test func anAgentStartedFromACustomCommandIsSentASentenceAroundThePath() throws { let (harness, agents) = Self.harness(withAgents: [AgentCatalogue.customID]) harness.model.addReviewComment(Self.comment(), in: harness.main.id) - let recipient = try #require(harness.model.reviewRecipient(in: harness.main.id)) + let recipient = try #require(harness.model.handoffRecipient(in: harness.main.id)) let sent = harness.model.sendReviewToPickedAgent(of: harness.main) diff --git a/Tests/MultishellAppCoreTests/Model/Services/AppModel+PanelServiceReadsTests.swift b/Tests/MultishellAppCoreTests/Model/Services/AppModel+PanelServiceReadsTests.swift index 23e4fc7a..6fd040df 100644 --- a/Tests/MultishellAppCoreTests/Model/Services/AppModel+PanelServiceReadsTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Services/AppModel+PanelServiceReadsTests.swift @@ -570,6 +570,10 @@ struct AppModelPanelServiceReadsTests { headCommit: tip, checks: [], ) + harness.model.remoteState.threads[feat.id] = PullRequestThreads( + pullRequestNumber: 9, + threads: [], + ) harness.store.setFilesPanelMode(.pullRequest) let read = PanelRead(worktree: feat.id, page: .pullRequest) _ = harness.model.remoteState.panelReadLog.begin(read, at: .now - .seconds(90)) diff --git a/Tests/MultishellAppCoreTests/Model/Services/AppModel+ServicePagesTests.swift b/Tests/MultishellAppCoreTests/Model/Services/AppModel+ServicePagesTests.swift index d50e0d74..65d114c6 100644 --- a/Tests/MultishellAppCoreTests/Model/Services/AppModel+ServicePagesTests.swift +++ b/Tests/MultishellAppCoreTests/Model/Services/AppModel+ServicePagesTests.swift @@ -31,6 +31,27 @@ struct AppModelServicePagesTests { ) } + @Test func aMergedPullRequestSaysNothingOfAThreadReadThatFailedBeforeItSettled() async throws { + let harness = try await GitHarness() + defer { harness.tearDown() } + let (feat, host, _) = try await harness.showingAFailingPullRequest() + harness.model.remoteState.threads[feat.id] = PullRequestThreads( + pullRequestNumber: 9, + threads: nil, + failure: .failed("SSO required"), + ) + let tip = try await harness.tip(of: feat) + host.answer( + .success([.sample(number: 9, state: .merged, headBranch: "feat", headCommit: tip)]) + ) + + await harness.model.refreshServices(ofProject: harness.project.id) + + let pullRequest = try #require(harness.model.services(of: feat).shownPullRequest) + try #require(pullRequest.state == .merged) + #expect(harness.model.threadsReadProblem(of: pullRequest, in: feat) == nil) + } + @Test func checksNotYetReadHoldTheMergeBack() async throws { let harness = try await GitHarness() defer { harness.tearDown() } diff --git a/Tests/MultishellAppCoreTests/PullRequestThread+Sample.swift b/Tests/MultishellAppCoreTests/PullRequestThread+Sample.swift new file mode 100644 index 00000000..5218698e --- /dev/null +++ b/Tests/MultishellAppCoreTests/PullRequestThread+Sample.swift @@ -0,0 +1,32 @@ +import Foundation + +@testable import MultishellServices + +extension PullRequestThread { + static func sample( + id: String = "t1", + path: String = "Sources/App.swift", + line: Int? = 12, + originalLine: Int? = 10, + isOutdated: Bool = false, + comments: [String] = ["Guard it."], + hunk: String = "@@ -1,2 +1,2 @@\n-let a\n+let b", + ) -> Self { + PullRequestThread( + id: id, + path: path, + line: line, + originalLine: originalLine, + isOutdated: isOutdated, + diffHunk: hunk, + comments: comments.enumerated().map { index, body in + PullRequestThreadComment( + id: "\(id)-c\(index)", + author: "jt", + body: body, + url: URL(string: "https://github.com/me/demo/pull/44#discussion_r\(index)"), + ) + }, + ) + } +} diff --git a/Tests/MultishellAppCoreTests/Services/CI/CIHandoffItemTests.swift b/Tests/MultishellAppCoreTests/Services/CI/CIHandoffItemTests.swift new file mode 100644 index 00000000..14ff3491 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Services/CI/CIHandoffItemTests.swift @@ -0,0 +1,148 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellServices + +@Suite +struct CIHandoffItemTests { + private static let workflows = [ + CIWorkflow( + name: "build", + status: .failed, + jobs: [ + CIJob(id: "11", name: "lint", status: .passed), + CIJob(id: "12", name: "test-macos", status: .failed), + ], + ), + CIWorkflow( + name: "docs", + status: .failed, + jobs: [CIJob(id: nil, name: "markdown-lint", status: .failed)], + ), + ] + + @Test func eachFailedJobIsAnItemWithItsPartOfTheReport() { + let run = CIRun.sample(id: "r1", status: .failed) + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: "build", job: "test-macos", text: "Expectation failed") + ]) + + let items = CIHandoffItem.items(of: run, workflows: Self.workflows, report: report) + + #expect(items.map(\.job?.name) == ["test-macos", "markdown-lint"]) + #expect(items.map(\.excerpt) == ["Expectation failed", nil]) + #expect( + items.first?.candidate.id + == .ciJob(runID: "r1", position: CIJobPosition(workflow: 0, job: 1), jobID: "12") + ) + } + + @Test func reportTextNamingNoListedJobIsARunOutputItemAfterTheJobs() { + let run = CIRun.sample(id: "r1", status: .failed) + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: nil, job: nil, text: "Config does not parse") + ]) + + let items = CIHandoffItem.items(of: run, workflows: [], report: report) + + #expect(items.map(\.heading) == ["Run output"]) + #expect(items.first?.excerpt == "Config does not parse") + } + + @Test func aJobFailedWhileItsRunStillGoesAwaitsItsReport() { + let going = CIRun.sample(id: "r1", status: .failed, isFinished: false) + let ended = CIRun.sample(id: "r1", status: .failed, isFinished: true) + + let whileGoing = CIHandoffItem.items(of: going, workflows: Self.workflows, report: nil) + let afterEnding = CIHandoffItem.items(of: ended, workflows: Self.workflows, report: nil) + + #expect(whileGoing.map(\.awaitsReport) == [true, true]) + #expect(afterEnding.map(\.awaitsReport) == [false, false]) + } + + @Test func twoSameNamedJobsOfSameNamedWorkflowsWithNoIDsAreTwoItems() { + let run = CIRun.sample(id: "r1", status: .failed) + let workflow = CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: nil, name: "test", status: .failed)], + ) + + let items = CIHandoffItem.items(of: run, workflows: [workflow, workflow], report: nil) + + #expect(Set(items.map(\.candidate.id)).count == 2) + } + + @Test func aJobTheReportNamesThoughItsStatusIsNotFailedCanBeSent() { + let run = CIRun.sample(id: "r1", status: .failed) + let workflow = CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "12", name: "test", status: .unknown)], + ) + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: "build", job: "test", text: "boom") + ]) + + let items = CIHandoffItem.items(of: run, workflows: [workflow], report: report) + + #expect(items.map(\.excerpt) == ["boom"]) + } + + @Test func newRunOutputFromARerunOfTheSameRunIsANewItem() { + let run = CIRun.sample(id: "r1", status: .failed) + func output(_ text: String) -> CIHandoffItem? { + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: nil, job: nil, text: text) + ]) + return CIHandoffItem.items(of: run, workflows: [], report: report).first + } + + #expect(output("bad config")?.candidate.id != output("still bad")?.candidate.id) + } + + @Test func aPassingJobSharingAFailedOnesNamesIsNoItem() { + let run = CIRun.sample(id: "r1", status: .failed) + let failed = CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "1", name: "test", status: .failed)], + ) + let rerun = CIWorkflow( + name: "build", + status: .passed, + jobs: [CIJob(id: "2", name: "test", status: .passed)], + ) + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: "build", job: "test", text: "boom") + ]) + + let items = CIHandoffItem.items(of: run, workflows: [failed, rerun], report: report) + + #expect(items.map(\.job?.id) == ["1"]) + } + + @Test func aRunThatPassedHasNothingToSend() { + let run = CIRun.sample(id: "r1", status: .passed) + let workflow = CIWorkflow( + name: "build", + status: .passed, + jobs: [CIJob(id: "1", name: "flaky", status: .failed)], + ) + + #expect(CIHandoffItem.items(of: run, workflows: [workflow], report: nil).isEmpty) + } + + @Test func aCancelledRunsFailedJobCanBeSent() { + let run = CIRun.sample(id: "r1", status: .cancelled) + let workflow = CIWorkflow( + name: "build", + status: .cancelled, + jobs: [CIJob(id: "1", name: "test", status: .failed)], + ) + + let items = CIHandoffItem.items(of: run, workflows: [workflow], report: nil) + + #expect(items.map(\.job?.id) == ["1"]) + } +} diff --git a/Tests/MultishellAppCoreTests/Services/CI/CIHandoffTests.swift b/Tests/MultishellAppCoreTests/Services/CI/CIHandoffTests.swift new file mode 100644 index 00000000..924d1a66 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Services/CI/CIHandoffTests.swift @@ -0,0 +1,110 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellServices + +@Suite +struct CIHandoffTests { + private static func item(excerpt: String?, isRunFinished: Bool = true) -> CIHandoffItem { + let run = CIRun.sample(id: "r1", status: .failed, isFinished: isRunFinished) + let report = excerpt.map { text in + CIFailureReport(excerpts: [CIFailureExcerpt(workflow: "build", job: "test", text: text)]) + } + let workflow = CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "12", name: "test", status: .failed)], + ) + return CIHandoffItem.items(of: run, workflows: [workflow], report: report)[0] + } + + @Test func aJobIsHeadedByItsWorkflowAndQuotesItsReport() { + let run = CIRun.sample(id: "r1", commit: "abc1234def", status: .failed) + + let entries = CIHandoff.entries( + of: [Self.item(excerpt: "line one\nline two")], + run: run, + provider: "CircleCI", + localTip: "abc1234def", + ) + + #expect(entries.map(\.heading) == ["build / test"]) + #expect(entries.first?.quote == ["line one", "line two"]) + #expect(entries.first?.caveat == nil) + #expect(entries.first?.text == "Failed on CircleCI, job 12.") + } + + @Test func aWorktreeOnAnotherCommitIsToldWhichCommitTheRunRanOn() { + let run = CIRun.sample(id: "r1", commit: "abc1234def", status: .failed) + + let entries = CIHandoff.entries( + of: [Self.item(excerpt: "failed")], + run: run, + provider: "CircleCI", + localTip: "fff9999aaa", + ) + + #expect(entries.first?.caveat?.contains("abc1234") == true) + } + + @Test func aLongReportKeepsItsLastEightyLinesAndSaysHowManyWentBefore() { + let report = (1...100).map { "line \($0)" }.joined(separator: "\n") + let run = CIRun.sample(id: "r1", status: .failed) + + let entry = CIHandoff.entries( + of: [Self.item(excerpt: report)], + run: run, + provider: "CircleCI", + localTip: nil, + )[0] + + #expect(entry.quote.count == 80) + #expect(entry.quote.first == "line 21") + #expect(entry.caveat == "20 earlier lines cut.") + } + + @Test func aJobWithItsReportUnreadSaysSo() { + let run = CIRun.sample(id: "r1", status: .failed, isFinished: false) + + let entry = CIHandoff.entries( + of: [Self.item(excerpt: nil, isRunFinished: false)], + run: run, + provider: "CircleCI", + localTip: nil, + )[0] + + #expect(entry.quote.isEmpty) + #expect(entry.caveat == "Its report was not read yet: the run was still going.") + } + + @Test func aFinishedRunsJobItsReadReportLeavesOutIsSaidToBeLeftOut() { + let run = CIRun.sample(id: "r1", status: .failed, isFinished: true) + let workflow = CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "12", name: "test", status: .failed)], + ) + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: "build", job: "lint", text: "lint failed") + ]) + let item = CIHandoffItem.items(of: run, workflows: [workflow], report: report)[0] + + let entry = CIHandoff.entries(of: [item], run: run, provider: "CircleCI", localTip: nil)[0] + + #expect(entry.caveat == "The run's report says nothing of this job.") + } + + @Test func aFinishedRunsJobWithItsReportUnreadSaysSoRatherThanThatItIsSilent() { + let run = CIRun.sample(id: "r1", status: .failed, isFinished: true) + let workflow = CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "12", name: "test", status: .failed)], + ) + let item = CIHandoffItem.items(of: run, workflows: [workflow], report: nil)[0] + + let entry = CIHandoff.entries(of: [item], run: run, provider: "CircleCI", localTip: nil)[0] + + #expect(entry.caveat == "Its report was not read.") + } +} diff --git a/Tests/MultishellAppCoreTests/Services/CI/CIWorkflowListingTests.swift b/Tests/MultishellAppCoreTests/Services/CI/CIWorkflowListingTests.swift new file mode 100644 index 00000000..8bc0f6a5 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Services/CI/CIWorkflowListingTests.swift @@ -0,0 +1,86 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellServices + +@Suite +struct CIWorkflowListingTests { + private static let run = CIRun.sample(id: "r1", status: .failed) + + private static func listing( + _ workflows: [CIWorkflow], + report: CIFailureReport?, + sending: Bool, + ) -> CIWorkflowListing { + CIWorkflowListing(run: run, workflows: workflows, report: report, sendsFailures: sending) + } + + @Test func aJobIsFoundByItsPlaceThoughTwoWorkflowsShareAName() { + let workflows = [ + CIWorkflow( + name: "build", + status: .passed, + jobs: [CIJob(id: "1", name: "test", status: .passed)], + ), + CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "2", name: "test", status: .failed)], + ), + ] + + let listing = Self.listing(workflows, report: nil, sending: true) + + #expect(listing.item(at: CIJobPosition(workflow: 0, job: 0)) == nil) + #expect(listing.item(at: CIJobPosition(workflow: 1, job: 0))?.job?.id == "2") + #expect(listing.showsHandoffSlot) + } + + @Test func aRunWhoseOnlyItemIsRunOutputKeepsNoSlotOnItsJobRows() { + let workflows = [ + CIWorkflow( + name: "build", + status: .passed, + jobs: [CIJob(id: "1", name: "lint", status: .passed)], + ) + ] + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: nil, job: nil, text: "bad config") + ]) + + let listing = Self.listing(workflows, report: report, sending: true) + + #expect(!listing.showsHandoffSlot) + #expect(listing.runOutput?.excerpt == "bad config") + #expect(listing.unplacedExcerpts == ["bad config"]) + } + + @Test func anEarlierRunReadsItsReportForEachJobAndSendsNothing() { + let workflows = [ + CIWorkflow( + name: "build", + status: .failed, + jobs: [CIJob(id: "1", name: "test", status: .failed)], + ) + ] + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: "build", job: "test", text: "boom") + ]) + + let listing = Self.listing(workflows, report: report, sending: false) + + #expect(listing.excerpt(ofJobAt: CIJobPosition(workflow: 0, job: 0)) == "boom") + #expect(!listing.showsHandoffSlot) + } + + @Test func theNewestRunShowsEachUnplacedExcerptInABoxOfItsOwn() { + let report = CIFailureReport(excerpts: [ + CIFailureExcerpt(workflow: nil, job: nil, text: "first"), + CIFailureExcerpt(workflow: nil, job: nil, text: "second"), + ]) + + let listing = Self.listing([], report: report, sending: true) + + #expect(listing.unplacedExcerpts == ["first", "second"]) + } +} diff --git a/Tests/MultishellAppCoreTests/Services/Merge/MergePathStepItemsTests.swift b/Tests/MultishellAppCoreTests/Services/Merge/MergePathStepItemsTests.swift new file mode 100644 index 00000000..45cd6a50 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Services/Merge/MergePathStepItemsTests.swift @@ -0,0 +1,43 @@ +import Testing + +@testable import MultishellAppCore +@testable import MultishellServices + +@Suite +struct MergePathStepItemsTests { + private static let path = MergePath.sample( + .sample(review: .changesRequested), + checks: [.sample(name: "lint"), .sample(name: "test", status: .failed)], + unresolvedThreadCount: 1, + ) + + private static func items(of kind: MergePath.Step.Kind) throws -> MergePathStepItems { + let step = try #require(path.steps.first { $0.kind == kind }) + return MergePathStepItems(of: step, in: path, headCommit: "tip", threads: [.sample()]) + } + + @Test func theChecksStepCarriesItsFailingChecksAlone() throws { + let items = try Self.items(of: .checks) + + #expect(items.checkCandidates.keys.map(\.name) == ["test"]) + #expect(items.threads.isEmpty) + #expect(items.showsCheckSlot) + #expect(items.collapsibleList == .checks) + } + + @Test func theStepHoldingTheThreadsCarriesThemAndNoChecks() throws { + let items = try Self.items(of: .review) + + #expect(items.threads.map(\.id) == ["t1"]) + #expect(items.candidates == [items.candidate(of: .sample())].compactMap(\.self)) + #expect(!items.showsCheckSlot) + #expect(items.collapsibleList == .threads) + } + + @Test func anyOtherStepCarriesNothing() throws { + let items = try Self.items(of: .conflicts) + + #expect(items.candidates.isEmpty) + #expect(items.collapsibleList == nil) + } +} diff --git a/Tests/MultishellAppCoreTests/Services/Merge/MergePathTests.swift b/Tests/MultishellAppCoreTests/Services/Merge/MergePathTests.swift index 8cc52426..d3503a1a 100644 --- a/Tests/MultishellAppCoreTests/Services/Merge/MergePathTests.swift +++ b/Tests/MultishellAppCoreTests/Services/Merge/MergePathTests.swift @@ -127,4 +127,38 @@ struct MergePathTests { MergePath.sample(.sample(state: .merged), checks: []).end == .merged(isOutgrown: false) ) } + + @Test func threadsWithNoReviewStepGetAStepOfTheirOwnThatHoldsNoMergeBack() { + let path = MergePath.sample( + .sample(review: .notRequired), + checks: [.sample(status: .failed)], + unresolvedThreadCount: 2, + ) + + #expect(path.steps.map(\.kind) == [.conflicts, .checks, .comments]) + #expect(path.threadsStep == .comments) + #expect(path.end == .waits(.steps(1))) + } + + @Test func threadsListUnderTheReviewStepWhereThereIsOne() { + let path = MergePath.sample( + .sample(review: .changesRequested), + checks: [.sample(status: .passed)], + unresolvedThreadCount: 2, + ) + + #expect(!path.steps.contains { $0.kind == .comments }) + #expect(path.threadsStep == .review) + } + + @Test func aSettledPullRequestListsNoThreads() { + let path = MergePath.sample( + .sample(state: .merged, review: .approved), + checks: [.sample(status: .passed)], + unresolvedThreadCount: 2, + ) + + #expect(path.threadsStep == nil) + #expect(!path.steps.contains { $0.kind == .comments }) + } } diff --git a/Tests/MultishellAppCoreTests/Services/PullRequests/PullRequestHandoffItemTests.swift b/Tests/MultishellAppCoreTests/Services/PullRequests/PullRequestHandoffItemTests.swift new file mode 100644 index 00000000..b4c4d4fd --- /dev/null +++ b/Tests/MultishellAppCoreTests/Services/PullRequests/PullRequestHandoffItemTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing + +@testable import MultishellAppCore +@testable import MultishellServices + +@Suite +struct PullRequestHandoffItemTests { + @Test func onlyFailingChecksAreItemsAndAnOptionalOneStartsUnchecked() { + let checks: [PullRequestCheck] = [ + .sample(name: "lint", status: .passed), + .sample(name: "test", status: .failed, link: URL(string: "https://ci/test")), + .sample(name: "danger", workflow: nil, status: .failed, isRequired: false), + ] + + let items = PullRequestHandoffItem.items(checks: checks, headCommit: "tip", threads: []) + + #expect( + items.map(\.candidate.id) == [ + .check(name: "CI / test", link: URL(string: "https://ci/test"), headCommit: "tip"), + .check(name: "danger", link: nil, headCommit: "tip"), + ] + ) + #expect(items.map(\.candidate.startsChecked) == [true, false]) + } + + @Test func aNewCommentOnAThreadMakesItANewItem() { + let before = PullRequestHandoffItem.thread(.sample(comments: ["Guard it."])).candidate + let after = PullRequestHandoffItem.thread(.sample(comments: ["Guard it.", "Still?"])).candidate + + #expect(before.id != after.id) + } + + @Test func twoFailingChecksSharingALinkAreTwoItems() { + let link = URL(string: "https://app.netlify.com/deploys/1") + let checks: [PullRequestCheck] = [ + .sample(name: "deploy-preview", workflow: nil, status: .failed, link: link), + .sample(name: "header-rules", workflow: nil, status: .failed, link: link), + ] + + let items = PullRequestHandoffItem.items(checks: checks, headCommit: "tip", threads: []) + + #expect(Set(items.map(\.candidate.id)).count == 2) + } + + @Test func aCheckWhoseLinkSurvivesAPushIsANewItemAtTheNewHead() { + let check = PullRequestCheck.sample( + name: "codecov/patch", + workflow: nil, + status: .failed, + link: URL(string: "https://codecov.io/gh/me/demo"), + ) + + let before = PullRequestHandoffItem.check(check, headCommit: "aaa").candidate + let after = PullRequestHandoffItem.check(check, headCommit: "bbb").candidate + + #expect(before.id != after.id) + } +} diff --git a/Tests/MultishellAppCoreTests/Services/PullRequests/PullRequestHandoffTests.swift b/Tests/MultishellAppCoreTests/Services/PullRequests/PullRequestHandoffTests.swift new file mode 100644 index 00000000..8093d841 --- /dev/null +++ b/Tests/MultishellAppCoreTests/Services/PullRequests/PullRequestHandoffTests.swift @@ -0,0 +1,120 @@ +import Foundation +import Testing + +@testable import MultishellAppCore +@testable import MultishellServices + +@Suite +struct PullRequestHandoffTests { + private static let link = URL(string: "https://github.com/me/demo/actions/runs/7/job/9")! + + private static func checkItem() -> PullRequestHandoffItem { + .check(.sample(name: "test", status: .failed, link: link), headCommit: "abc1234def") + } + + @Test func aCheckQuotesItsLogsTailAndLinksItsPage() { + let item = Self.checkItem() + + let entry = PullRequestHandoff.entries( + of: [item], + logs: [item.candidate.id: .read(FailedCheckLog(text: "error: boom", earlierLineCount: 0))], + localTip: "abc1234def", + )[0] + + #expect(entry.heading == "CI / test") + #expect(entry.quote == ["error: boom"]) + #expect(entry.caveat == nil) + #expect(entry.text == "Failed. Its page: \(Self.link.absoluteString)") + } + + @Test func aLogThatFailedToReadIsSentWithTheToolsWords() { + let item = Self.checkItem() + + let entry = PullRequestHandoff.entries( + of: [item], + logs: [item.candidate.id: .failed("HTTP 404")], + localTip: nil, + )[0] + + #expect(entry.quote.isEmpty) + #expect(entry.caveat == "Its log could not be read: HTTP 404") + } + + @Test func aWorktreeOnAnotherCommitIsToldWhichCommitTheCheckRanOn() { + let item = Self.checkItem() + + let entry = PullRequestHandoff.entries(of: [item], logs: [:], localTip: "fff0000")[0] + + #expect(entry.caveat?.contains("abc1234") == true) + } + + @Test func aThreadIsHeadedByItsPlaceAndQuotesTheEndOfItsHunk() { + let thread = PullRequestThread.sample(comments: ["Guard it.", "Agreed."]) + + let entry = PullRequestHandoff.entries(of: [.thread(thread)], logs: [:], localTip: nil)[0] + + #expect(entry.heading == "Sources/App.swift:12") + #expect(entry.quote == ["@@ -1,2 +1,2 @@", "-let a", "+let b"]) + #expect(entry.text.hasPrefix("jt: Guard it.\n\njt: Agreed.")) + } + + @Test func anOutdatedThreadIsLabelledByTheLineItWasWrittenOnAndSaysSo() { + let thread = PullRequestThread.sample(line: nil, originalLine: 10, isOutdated: true) + + let entry = PullRequestHandoff.entries(of: [.thread(thread)], logs: [:], localTip: nil)[0] + + #expect(entry.heading == "Sources/App.swift:10") + #expect(entry.caveat == "Outdated: the lines it was written on have changed since.") + } + + @Test func aWorktreeOnAnotherCommitIsToldSoWithoutClaimingItIsAhead() { + let item = Self.checkItem() + + let entry = PullRequestHandoff.entries(of: [item], logs: [:], localTip: "fff0000aaa")[0] + + #expect(entry.caveat == "This ran on abc1234, not the worktree's current commit.") + } + + @Test func aThreadOnACRLFFileQuotesItsHunkWithoutCarriageReturns() { + let thread = PullRequestThread.sample(hunk: "@@ -1 +1 @@\r\n-let a\r\n+let b") + + let entry = PullRequestHandoff.entries(of: [.thread(thread)], logs: [:], localTip: nil)[0] + + #expect(entry.quote == ["@@ -1 +1 @@", "-let a", "+let b"]) + } + + @Test func aLogThatPrintedNothingSaysSo() { + let item = Self.checkItem() + + let entry = PullRequestHandoff.entries( + of: [item], + logs: [item.candidate.id: .read(FailedCheckLog(text: "", earlierLineCount: 0))], + localTip: nil, + )[0] + + #expect(entry.caveat == "Its log printed nothing.") + } + + @Test func aThreadWithNoHunkQuotesNothing() { + let thread = PullRequestThread.sample(hunk: "") + + let entry = PullRequestHandoff.entries(of: [.thread(thread)], logs: [:], localTip: nil)[0] + + #expect(entry.quote.isEmpty) + } + + @Test func aLongLogSaysHowManyLinesCameBeforeItsTailInTheWholeLog() { + let output = (1...12_000).map { "test\tRun\t2026-11-19T01:02:03.4Z line \($0)" } + .joined(separator: "\n") + let log = GitHubJobLog.log(from: output, keepingLast: HandoffLogTail.linesToRead) + let item = Self.checkItem() + + let entry = PullRequestHandoff.entries( + of: [item], + logs: [item.candidate.id: .read(log)], + localTip: nil, + )[0] + + #expect(entry.caveat == "11920 earlier lines cut.") + } +} diff --git a/Tests/MultishellAppUITests/Files/Panel/Review/ReviewSendFooterTests.swift b/Tests/MultishellAppUITests/Files/Panel/Handoff/HandoffSendFooterTests.swift similarity index 85% rename from Tests/MultishellAppUITests/Files/Panel/Review/ReviewSendFooterTests.swift rename to Tests/MultishellAppUITests/Files/Panel/Handoff/HandoffSendFooterTests.swift index 3ac330c8..f76e7f45 100644 --- a/Tests/MultishellAppUITests/Files/Panel/Review/ReviewSendFooterTests.swift +++ b/Tests/MultishellAppUITests/Files/Panel/Handoff/HandoffSendFooterTests.swift @@ -7,20 +7,26 @@ import Testing @testable import MultishellCore @Suite @MainActor -struct ReviewSendFooterTests { +struct HandoffSendFooterTests { private static func footer( in harness: ModelHarness, fontSize: Double = 13, - ) throws -> ReviewSendFooter { + ) throws -> HandoffSendFooter { let worktree = harness.addPrimaryWorktree() harness.model.select(worktree) harness.model.setUIFontSize(fontSize) harness.store.openTab(in: worktree.id, title: "claude", agentID: AgentCatalogue.claudeID) harness.model.liveSessionIDs = Set(harness.model.workspace.sessions(in: worktree.id).map(\.id)) - let offersTheAgent = - if case .ready = harness.model.reviewFooter(of: worktree) { true } else { false } + let footer = harness.model.reviewFooter(of: worktree) + let offersTheAgent = if case .ready = footer { true } else { false } try #require(offersTheAgent) - return ReviewSendFooter(model: harness.model, worktree: worktree, theme: .multishellDark) + return HandoffSendFooter( + footer: footer, + metrics: harness.model.metrics, + theme: .multishellDark, + pick: { _ in }, + send: { _ in }, + ) } private static func height(ofFooterAtWidth width: CGFloat) throws -> CGFloat { diff --git a/Tests/MultishellCLITests/Control/ControlRefusal+WordingTests.swift b/Tests/MultishellCLITests/Control/ControlRefusal+WordingTests.swift index 1f98964c..a3060dcc 100644 --- a/Tests/MultishellCLITests/Control/ControlRefusal+WordingTests.swift +++ b/Tests/MultishellCLITests/Control/ControlRefusal+WordingTests.swift @@ -26,6 +26,23 @@ struct ControlRefusalWordingTests { ) } + @Test func nothingToSendCoversItemsSentAlreadyAndOnlyTheCIPageSaysToShowItself() { + let pullRequest = ControlRefusal.nothingToHandOff(.pullRequest, id: "w-89abcdef").wording + let ciRuns = ControlRefusal.nothingToHandOff(.ciRuns, id: "w-89abcdef").wording + + #expect(pullRequest.contains("not sent already")) + #expect(!pullRequest.contains("only while shown")) + #expect(ciRuns.contains("not sent already")) + #expect(ciRuns.hasSuffix("`multishell ui show ci w-89abcdef`")) + } + + @Test func aSecondSendWhileTheFirstIsUnderWaySaysSoWithoutNamingLogs() { + let wording = ControlRefusal.handoffUnderWay(id: "w-89abcdef").wording + + #expect(wording.contains("under way")) + #expect(!wording.contains("logs")) + } + @Test func aReviewCommentRefusedSaysWhetherTheTabOrTheLinesAreMissing() { #expect( ControlRefusal.noReviewTab(path: "a.swift").wording diff --git a/Tests/MultishellCLITests/Control/Helper+ControlTests.swift b/Tests/MultishellCLITests/Control/Helper+ControlTests.swift index 76027661..7947f269 100644 --- a/Tests/MultishellCLITests/Control/Helper+ControlTests.swift +++ b/Tests/MultishellCLITests/Control/Helper+ControlTests.swift @@ -256,6 +256,47 @@ struct HelperControlTests { .sendReview(worktree: nil, to: UUID(uuidString: "00000000-0000-0000-0000-000000000001")), ), (["review", "clear", "--sent"], .clearReviewComments(worktree: nil, sentOnly: true)), + ( + ["pr", "send"], + .sendPullRequestFeedback( + worktree: nil, + to: nil, + includesChecks: true, + includesThreads: true, + ), + ), + ( + ["pr", "send", "--checks", "--worktree", "w-89abcdef"], + .sendPullRequestFeedback( + worktree: "w-89abcdef", + to: nil, + includesChecks: true, + includesThreads: false, + ), + ), + ( + ["pr", "send", "--threads", "--to", id.uuidString], + .sendPullRequestFeedback( + worktree: nil, + to: id, + includesChecks: false, + includesThreads: true, + ), + ), + ( + ["pr", "send", "--threads", "--checks"], + .sendPullRequestFeedback( + worktree: nil, + to: nil, + includesChecks: true, + includesThreads: true, + ), + ), + (["ci", "send"], .sendCIFailures(worktree: nil, to: nil)), + ( + ["ci", "send", "--to", id.uuidString, "--worktree", "w-89abcdef"], + .sendCIFailures(worktree: "w-89abcdef", to: id), + ), ( ["review", "clear", "--worktree", "w-89abcdef"], .clearReviewComments(worktree: "w-89abcdef", sentOnly: false), @@ -377,6 +418,14 @@ struct HelperControlTests { ["review", "add", "a.swift", "1"], ["review", "send", "--to", "not-an-id"], ["review", "list", "--worktree", "main"], + ["pr", "send", "--to", "not-an-id"], + ["pr", "send", "--worktree", "main"], + ["pr", "send", "extra"], + ["pr", "list"], + ["pr"], + ["ci", "send", "--checks"], + ["ci", "send", "--to", "not-an-id"], + ["ci", "list"], ["tabs", "open", "--"], ["tabs", "open", "--agent", "claude", "--", "make"], ["tabs", "move", UUID().uuidString], diff --git a/Tests/MultishellServicesTests/CI/CircleCI/CircleCIToolReportTests.swift b/Tests/MultishellServicesTests/CI/CircleCI/CircleCIToolReportTests.swift index 32014277..0b7fa5e4 100644 --- a/Tests/MultishellServicesTests/CI/CircleCI/CircleCIToolReportTests.swift +++ b/Tests/MultishellServicesTests/CI/CircleCI/CircleCIToolReportTests.swift @@ -18,7 +18,7 @@ struct CircleCIToolReportTests { @Test func theCLIBeforeOneHasNoRunCommandsAndIsTooOld() { #expect( CircleCIToolReport.status(versionOutput: "0.1.31425+7ba21d2\n", authMe: .sample()) - == .unsupportedVersion("0.1.31425+7ba21d2") + == .unsupportedVersion("0.1.31425+7ba21d2", minimum: "1") ) } diff --git a/Tests/MultishellServicesTests/SCM/GitHub/GitHubFixtures.swift b/Tests/MultishellServicesTests/SCM/GitHub/GitHubFixtures.swift index 55e5ed82..0b440d09 100644 --- a/Tests/MultishellServicesTests/SCM/GitHub/GitHubFixtures.swift +++ b/Tests/MultishellServicesTests/SCM/GitHub/GitHubFixtures.swift @@ -54,4 +54,21 @@ enum GitHubFixtures { "updatedAt":"2026-10-20T01:00:00Z","url":"https://github.com/KieranP/multishell/pull/\(number)"} """ } + + /// One page of review threads: `id` unresolved, and one resolved beside it. + static func reviewThreads(id: String, hasNextPage: Bool) -> String { + let cursor = hasNextPage ? #""c1""# : "null" + return """ + {"data":{"repository":{"pullRequest":{"reviewThreads":{\ + "pageInfo":{"hasNextPage":\(hasNextPage),"endCursor":\(cursor)},"nodes":[\ + {"id":"\(id)","isResolved":false,"isOutdated":false,"path":"Sources/App.swift",\ + "line":12,"originalLine":10,\ + "firstComment":{"nodes":[{"diffHunk":"@@ -1,2 +1,2 @@\\n-let a\\n+let b"}]},\ + "comments":{"nodes":[{"id":"\(id)-c","author":{"login":"jt"},"body":"Guard it.",\ + "url":"https://github.com/me/demo/pull/44#discussion_r1"}]}},\ + {"id":"\(id)-done","isResolved":true,"isOutdated":false,"path":"README.md",\ + "line":null,"originalLine":null,"firstComment":{"nodes":[{"diffHunk":""}]},\ + "comments":{"nodes":[{"id":"x","author":null,"body":"Fixed","url":null}]}}]}}}}} + """ + } } diff --git a/Tests/MultishellServicesTests/SCM/GitHub/GitHubHostTests.swift b/Tests/MultishellServicesTests/SCM/GitHub/GitHubHostTests.swift index f6d21747..745c6a95 100644 --- a/Tests/MultishellServicesTests/SCM/GitHub/GitHubHostTests.swift +++ b/Tests/MultishellServicesTests/SCM/GitHub/GitHubHostTests.swift @@ -320,4 +320,69 @@ struct GitHubHostTests { #expect(tool.runLog.drain().finishedRuns.map(\.command) == ["gh pr list"]) } + @Test func aFailedChecksLogIsReadFromItsJobsLogsEndpointWhichAnswersWhileItsRunGoes() async throws + { + let tool = try FakeTool( + named: "gh", + #"printf '2026-11-19T01:02:03.4567890Z error: boom\n'"#, + ) + defer { tool.tearDown() } + let check = PullRequestCheck( + name: "test", + workflow: "CI", + status: .failed, + isRequired: true, + link: URL(string: "https://github.com/me/demo/actions/runs/7/job/135205394571"), + ) + + let log = try await host(for: tool).failedLog(of: check, keepingLast: 160, in: tool.directory) + + #expect(log?.text == "error: boom\n") + #expect( + tool.calls.first?.arguments + == "api --hostname github.com --allow-escape-sequences repos/me/demo/actions/jobs/135205394571/logs" + ) + } + + @Test func aCheckLinkingOutsideActionsHasNoLogAndAsksNothing() async throws { + let tool = try FakeTool(named: "gh", "exit 0") + defer { tool.tearDown() } + let check = PullRequestCheck( + name: "ci/circleci: build", + workflow: nil, + status: .failed, + isRequired: true, + link: URL(string: "https://circleci.com/gh/me/demo/12"), + ) + + let log = try await host(for: tool).failedLog(of: check, keepingLast: 160, in: tool.directory) + + #expect(log == nil) + #expect(tool.calls.isEmpty) + } + + @Test func unresolvedThreadsAreReadPageByPageUntilGitHubSaysThereAreNoMore() async throws { + let tool = try FakeTool( + named: "gh", + """ + case "$*" in + *after=c1*) cat <<'JSON' + \(GitHubFixtures.reviewThreads(id: "t2", hasNextPage: false)) + JSON + ;; + *) cat <<'JSON' + \(GitHubFixtures.reviewThreads(id: "t1", hasNextPage: true)) + JSON + ;; + esac + """, + ) + defer { tool.tearDown() } + let onGitHub = Self.pullRequest(at: URL(string: "https://github.com/me/demo/pull/44")!) + + let threads = try await host(for: tool).unresolvedThreads(of: onGitHub, in: tool.directory) + + #expect(threads.map(\.id) == ["t1", "t2"]) + #expect(tool.calls.count == 2) + } } diff --git a/Tests/MultishellServicesTests/SCM/GitHub/GitHubJobAddressTests.swift b/Tests/MultishellServicesTests/SCM/GitHub/GitHubJobAddressTests.swift new file mode 100644 index 00000000..fe6ef79b --- /dev/null +++ b/Tests/MultishellServicesTests/SCM/GitHub/GitHubJobAddressTests.swift @@ -0,0 +1,32 @@ +import Foundation +import Testing + +@testable import MultishellServices + +@Suite +struct GitHubJobAddressTests { + @Test func anActionsJobLinkNamesItsHostRepositoryAndJob() throws { + let link = try #require( + URL(string: "https://git.example.com/me/demo/actions/runs/44418623259/job/135205394571") + ) + + let address = try #require(GitHubJobAddress(link)) + + #expect(address.host == "git.example.com") + #expect(address.logsEndpoint == "repos/me/demo/actions/jobs/135205394571/logs") + } + + @Test func aLinkOutsideActionsNamesNoJob() throws { + let circle = try #require(URL(string: "https://app.circleci.com/pipelines/gh/me/demo/12")) + let run = try #require(URL(string: "https://github.com/me/demo/actions/runs/7")) + + #expect(GitHubJobAddress(circle) == nil) + #expect(GitHubJobAddress(run) == nil) + } + + @Test func aJobSegmentInOtherScriptsDigitsNamesNoJob() throws { + let link = try #require(URL(string: "https://github.com/me/demo/actions/runs/1/job/%C2%BD")) + + #expect(GitHubJobAddress(link) == nil) + } +} diff --git a/Tests/MultishellServicesTests/SCM/GitHub/GitHubJobLogTests.swift b/Tests/MultishellServicesTests/SCM/GitHub/GitHubJobLogTests.swift new file mode 100644 index 00000000..fcd3852e --- /dev/null +++ b/Tests/MultishellServicesTests/SCM/GitHub/GitHubJobLogTests.swift @@ -0,0 +1,91 @@ +import Testing + +@testable import MultishellServices + +@Suite +struct GitHubJobLogTests { + @Test func eachLineLosesItsTimestampAndItsColour() { + let output = + "2026-11-19T01:02:03.4567890Z \u{1b}[31merror:\u{1b}[0m boom\n" + + "2026-11-19T01:02:04.0000000Z at App.swift:12" + + #expect( + GitHubJobLog.log(from: output, keepingLast: 160).text == "error: boom\n at App.swift:12" + ) + } + + @Test func aLineWithoutATimestampIsKeptAsItIs() { + #expect(GitHubJobLog.log(from: "plain\tline", keepingLast: 160).text == "plain\tline") + } + + @Test func aStepsFirstLineLosesItsByteOrderMarkAndTimestamp() { + let output = "\u{FEFF}2026-11-19T01:02:03.4567890Z ##[group]Run tests" + + #expect(GitHubJobLog.log(from: output, keepingLast: 160).text == "Run tests") + } + + @Test func otherControlCodesAndGroupMarkersAreStrippedToo() { + let output = + "2026-11-19T01:02:03.4Z ##[group]Run tests\n" + + "2026-11-19T01:02:03.5Z \u{1b}[Kbuilding\u{1b}[?25l\n" + + "2026-11-19T01:02:03.6Z ##[endgroup]" + + #expect(GitHubJobLog.log(from: output, keepingLast: 160).text == "Run tests\nbuilding") + } + + @Test func onlyTheLastLinesAskedForAreCleanedAndTheRestCounted() { + let output = (1...5).map { "2026-11-19T01:02:03.4Z line \($0)" }.joined(separator: "\n") + + let log = GitHubJobLog.log(from: output, keepingLast: 2) + + #expect(log.text == "line 4\nline 5") + #expect(log.earlierLineCount == 3) + } + + @Test func carriageReturnsInsideALineDoNotSkewTheEarlierCount() { + let plain = (1...10).map { "2026-11-19T01:02:03.4Z line \($0)" } + let progress = (1...3).map { _ in "2026-11-19T01:02:03.4Z 10%\r50%\r100%" } + let output = (plain + progress).joined(separator: "\n") + + let log = GitHubJobLog.log(from: output, keepingLast: 2) + + #expect(log.text == "10%\r50%\r100%\n10%\r50%\r100%") + #expect(log.earlierLineCount == 11) + } + + @Test func anEndGroupMarkerTakesNoLineOfTheTail() { + let output = + "2026-11-19T01:02:03.4Z error: boom\n" + + "2026-11-19T01:02:03.5Z ##[endgroup]" + + #expect(GitHubJobLog.log(from: output, keepingLast: 160).text == "error: boom") + } + + @Test func aFoldEndDroppedFromTheTailIsCountedAmongTheLinesCut() { + let output = + "2026-11-19T01:02:03.1Z one\n" + + "2026-11-19T01:02:03.2Z two\n" + + "2026-11-19T01:02:03.3Z three\n" + + "2026-11-19T01:02:03.4Z ##[endgroup]\n" + + "2026-11-19T01:02:03.5Z four" + + let log = GitHubJobLog.log(from: output, keepingLast: 3) + + #expect(log.text == "three\nfour") + #expect(log.earlierLineCount == 3) + } + + @Test func theRunnersCleanupAfterTheLastErrorLineIsLeftOut() { + let output = + "2026-11-19T01:02:03.1Z ##[error]first\n" + + "2026-11-19T01:02:03.2Z make: *** [lint] Error 2\n" + + "2026-11-19T01:02:03.3Z ##[error]Process completed with exit code 2.\n" + + "2026-11-19T01:02:03.4Z Post job cleanup.\n" + + "2026-11-19T01:02:03.5Z Cleaning up orphan processes" + + let log = GitHubJobLog.log(from: output, keepingLast: 2) + + #expect(log.text == "make: *** [lint] Error 2\n##[error]Process completed with exit code 2.") + #expect(log.earlierLineCount == 1) + } +} diff --git a/Tests/MultishellServicesTests/SCM/GitHub/GitHubReviewThreadRecordTests.swift b/Tests/MultishellServicesTests/SCM/GitHub/GitHubReviewThreadRecordTests.swift new file mode 100644 index 00000000..a73bf9fd --- /dev/null +++ b/Tests/MultishellServicesTests/SCM/GitHub/GitHubReviewThreadRecordTests.swift @@ -0,0 +1,26 @@ +import Foundation +import Testing + +@testable import MultishellServices + +@Suite +struct GitHubReviewThreadRecordTests { + @Test func aPageKeepsOnlyItsUnresolvedThreadsAndTheNextCursor() throws { + let json = Data(GitHubFixtures.reviewThreads(id: "t1", hasNextPage: true).utf8) + + let page = try GitHubReviewThreadRecord.page(from: json) + + #expect(page.threads.map(\.id) == ["t1"]) + #expect(page.next == "c1") + let comment = try #require(page.threads.first?.comments.first) + #expect(comment.author == "jt") + #expect(page.threads.first?.diffHunk == "@@ -1,2 +1,2 @@\n-let a\n+let b") + #expect(page.threads.first?.line == 12) + } + + @Test func theLastPageHasNoNextCursor() throws { + let json = Data(GitHubFixtures.reviewThreads(id: "t2", hasNextPage: false).utf8) + + #expect(try GitHubReviewThreadRecord.page(from: json).next == nil) + } +} diff --git a/Tests/MultishellServicesTests/SCM/GitHub/GitHubToolReportTests.swift b/Tests/MultishellServicesTests/SCM/GitHub/GitHubToolReportTests.swift index 2bcc591a..6139647d 100644 --- a/Tests/MultishellServicesTests/SCM/GitHub/GitHubToolReportTests.swift +++ b/Tests/MultishellServicesTests/SCM/GitHub/GitHubToolReportTests.swift @@ -29,6 +29,54 @@ struct GitHubToolReportTests { ) } + @Test func aGhBeforeTheFirstWhoseApiTakesEscapeSequencesIsTooOld() { + let older = "gh version 2.96.1 (2026-07-20)\n" + + #expect( + GitHubToolReport.status(versionOutput: older, authStatus: .sample()) + == .unsupportedVersion("2.96.1", minimum: "2.97.0") + ) + } + + @Test func aGhTooOldAndLoggedOutSaysLoggedOutSinceNothingReadsWithoutALogin() { + let auth = ProcessOutput.sample( + error: "You are not logged into any GitHub hosts. To log in, run: gh auth login\n", + status: 1, + ) + + #expect( + GitHubToolReport.status(versionOutput: "gh version 2.90.0\n", authStatus: auth) + == .loggedOut + ) + } + + @Test func aGhAtTheFloorOrPastItIsNotTooOld() { + let atFloor = "gh version 2.97.0 (2026-07-31)\n" + + #expect( + GitHubToolReport.status(versionOutput: atFloor, authStatus: .sample()) + == .ready(version: "2.97.0", account: nil) + ) + #expect( + GitHubToolReport.status(versionOutput: version, authStatus: .sample()) + == .ready(version: "2.103.2", account: nil) + ) + } + + @Test func aVersionWithNoPatchNumberReadsAsItsZeroPatch() { + #expect( + GitHubToolReport.status(versionOutput: "gh version 2.97\n", authStatus: .sample()) + == .ready(version: "2.97", account: nil) + ) + } + + @Test func aGhBuiltFromSourceWithNoVersionNumberIsNotCalledTooOld() { + #expect( + GitHubToolReport.status(versionOutput: "gh version DEV\n", authStatus: .sample()) + == .ready(version: "DEV", account: nil) + ) + } + @Test func aGhWithNoLoginIsLoggedOut() { let auth = ProcessOutput.sample( error: "You are not logged into any GitHub hosts. To log in, run: gh auth login\n", diff --git a/Tests/MultishellServicesTests/StandIn/ServiceStandInTests.swift b/Tests/MultishellServicesTests/StandIn/ServiceStandInTests.swift index 2005d524..648e14ea 100644 --- a/Tests/MultishellServicesTests/StandIn/ServiceStandInTests.swift +++ b/Tests/MultishellServicesTests/StandIn/ServiceStandInTests.swift @@ -43,6 +43,76 @@ struct ServiceStandInTests { #expect(checks.first?.isRequired == true) } + @Test func theHostAnswersAPullRequestsThreadsAndAFailedChecksLogFromTheStandIn() async throws { + let json = """ + {"pullRequests": [{"number": 7, "title": "a", "state": "open", "headBranch": "a", + "headCommit": "1", "headRepository": "me/demo", + "checks": [{"name": "test", "status": "failed", "log": "error: boom"}, + {"name": "lint", "status": "failed"}], + "threads": [{"id": "t1", "path": "a.swift", + "comments": [{"id": "c1", "body": "Why?"}]}]}]} + """ + let host = try ServiceStandIn(json: json).pullRequestHost + let pullRequest = try #require(try await host.pullRequests(in: Self.here).first) + let checks = try await host.checks(of: pullRequest, in: Self.here) + let test = try #require(checks.first { $0.name == "test" }) + let lint = try #require(checks.first { $0.name == "lint" }) + + let threads = try await host.unresolvedThreads(of: pullRequest, in: Self.here) + let testLog = try await host.failedLog(of: test, keepingLast: 160, in: Self.here) + let lintLog = try await host.failedLog(of: lint, keepingLast: 160, in: Self.here) + + #expect(threads.map(\.id) == ["t1"]) + #expect(threads.first?.line == nil && threads.first?.isOutdated == false) + #expect(threads.first?.comments.first?.author == nil) + #expect(threads.first?.diffHunk == "") + #expect(testLog?.text == "error: boom") + #expect(lintLog == nil) + } + + @Test func aPullRequestGivingNoThreadsHasNone() async throws { + let host = try ServiceStandIn(json: Self.json).pullRequestHost + let pullRequest = try #require(try await host.pullRequests(in: Self.here).first) + + #expect(try await host.unresolvedThreads(of: pullRequest, in: Self.here).isEmpty) + } + + @Test func aThreadWithNoCommentIsRefusedNamingWhere() { + let json = """ + {"pullRequests": [{"number": 7, "title": "a", "state": "open", "headBranch": "a", + "headCommit": "1", "headRepository": "me/demo", + "threads": [{"id": "t1", "path": "a.swift", "comments": [{"id": "c1", "body": "x"}]}, + {"id": "t2", "path": "a.swift", "comments": []}]}]} + """ + + let error = #expect(throws: ServiceStandInUnreadable.self) { try ServiceStandIn(json: json) } + + #expect( + error?.reason.hasPrefix("at pullRequests.0.threads.1.comments: ") == true, + "\(String(describing: error))", + ) + } + + @Test func aKeyNoThreadOrCommentTakesIsRefusedNamingWhere() { + for (field, path) in [ + (#""resolved": true, "comments": [{"id": "c", "body": "x"}]"#, "threads.0.resolved"), + (#""comments": [{"id": "c", "body": "x", "login": "me"}]"#, "threads.0.comments.0.login"), + ] { + let json = """ + {"pullRequests": [{"number": 7, "title": "a", "state": "open", "headBranch": "a", + "headCommit": "1", "headRepository": "me/demo", + "threads": [{"id": "t", "path": "a.swift", \(field)}]}]} + """ + + let error = #expect(throws: ServiceStandInUnreadable.self) { try ServiceStandIn(json: json) } + + #expect( + error?.reason.hasPrefix("at pullRequests.0.\(path): ") == true, + "\(String(describing: error))", + ) + } + } + @Test func anOwnerAndNameStandForTheHeadRepositorysURL() async throws { let json = """ {"pullRequests": [{"number": 1, "title": "t", "state": "draft", "headBranch": "b", @@ -279,7 +349,11 @@ struct ServiceStandInTests { "isReadyToMerge": false, "headBranch": "a", "headCommit": "1", "headRepository": "me/demo", "baseBranch": "main", "updatedAt": "2026-10-29T10:00:00Z", "checks": [{"name": "build", "workflow": "ci", "status": "passed", "isRequired": true, - "link": "https://x/c"}]}], + "link": "https://x/c", "log": "ok"}], + "threads": [{"id": "t", "path": "a.swift", "line": 3, "originalLine": 2, + "isOutdated": true, "diffHunk": "@@ -1 +1 @@", + "comments": [{"id": "c", "author": "me", "body": "Why?", + "url": "https://x/c1"}]}]}], "ciRuns": [{"id": "r", "branch": "a", "commit": "1", "subject": "s", "status": "failed", "isFinished": true, "createdAt": "2026-10-29T10:00:00Z", "repository": "me/demo", "workflows": [{"name": "ci", "status": "failed", @@ -290,6 +364,8 @@ struct ServiceStandInTests { let pullRequest = try #require(standIn.pullRequests.first) let check = try #require(standIn.checks[ServiceStandIn.key(of: pullRequest)]?.first) + let thread = try #require(standIn.threads[ServiceStandIn.key(of: pullRequest)]?.first) + let comment = try #require(thread.comments.first) let run = try #require(standIn.runs.first) let job = try #require(standIn.workflows["r"]?.first?.jobs.first) @@ -300,6 +376,10 @@ struct ServiceStandInTests { #expect( check.workflow == "ci" && check.isRequired && check.link?.absoluteString == "https://x/c" ) + #expect(standIn.logs[check] == "ok") + #expect(thread.path == "a.swift" && thread.line == 3 && thread.originalLine == 2) + #expect(thread.isOutdated && comment.author == "me" && comment.body == "Why?") + #expect(thread.diffHunk == "@@ -1 +1 @@" && comment.url?.absoluteString == "https://x/c1") #expect(run.subject == "s" && run.isFinished && run.createdAt != nil) #expect(run.repository?.isSame(as: RemoteRepository(owner: "me", name: "demo")) == true) #expect(job.id == "j" && job.status == .failed)