Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Install an agent from Settings, on this computer or on a server.** In Settings › Providers a provider that is not installed has an Install button that runs its official installer on the scope's machine; a project on a server with no agent installed offers the same from its empty screen.
- **A chat waiting on the sessions it asked says which ones, and lets you stop it.** Over the message box, Waiting on names each session still owing an answer, one that needs you first with what it needs, a click opening it; Stop ends the turn. Only on Claude Code.
- **An agent is told when a merged pull request conflicts with what it is working on.** When the pull request of another session's checkout merges, the agents in the repository's other checkouts whose work conflicts with it get a note naming the files, at their next edit or command. An idle session is not woken for it; not in Cursor CLI's chat.
- **Read a check's log without leaving lich.** On a pull request's Checks tab, click a finished GitHub Actions or GitLab job: its steps open beside the list of checks, with the failed one unfolded at its first error. The log can be searched and copied; a running job and other services' checks still open in the browser.

### Changed

- **The Pulls screen is redrawn, and its list is sorted by what each pull request needs.** Open ones are grouped into Ready to merge, Needs work, In review and Drafts, in place of the All, Ready, Drafts and Failing filters and the Approved state. Inside a pull request, its facts stand beside the description, and Copy link and Copy Markdown are in the `⋯` menu.
- **Long conversations no longer slow the window down.** Scrolling, typing and watching an answer come in cost about the
same in a chat of thousands of messages as in a new one, and several agents working at once take about a third of the
processor they took. Answers also come in more smoothly, about thirty updates a second instead of twenty.
Expand Down
28 changes: 28 additions & 0 deletions api/checklog.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,31 @@ type StepLog struct {
Lines []string `json:"lines"`
Cut int `json:"cut,omitempty"`
}

// ProjectJobLog reads the whole log of one finished job of a pull request, the
// check of a CheckItem with HasLog.
var ProjectJobLog = define[JobLogOptions, JobLog]("project.JobLog")

// JobLogOptions names the job by its check's URL, read with the account of the
// checkout at Path.
type JobLogOptions struct {
Path string `json:"path"`
URL string `json:"url"`
}

// JobLog is a job's log by step, in the order they ran, a skipped one left
// out. A GitLab job's is one step with no name.
type JobLog struct {
Steps []JobStep `json:"steps"`
}

// JobStep is one step of a job and what it printed, without timestamps or
// terminal escapes; the runner's own markers ("##[error]", "##[group]") stay.
// State is passed or failed, "" for a step with no name.
type JobStep struct {
Name string `json:"name"`
State string `json:"state"`
StartedAt string `json:"startedAt"`
CompletedAt string `json:"completedAt"`
Lines []string `json:"lines"`
}
3 changes: 3 additions & 0 deletions api/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,9 @@ type CheckItem struct {
// Required is GitHub's own answer to "does this check gate the merge", the
// same verdict its checks list labels Required.
Required bool `json:"required"`
// HasLog is a finished job whose log ProjectJobLog reads; any other check
// is read at URL alone.
HasLog bool `json:"hasLog"`
}

// ReviewComment is one line comment of a review being submitted. Line is the
Expand Down
19 changes: 19 additions & 0 deletions api/testdata/contract.golden
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ project.GitWriteMessage(GitWriteMessageOptions) GitWrittenMessage
project.GlobalCommitIdentity(None) CommitIdentity
project.Home(None) *OpenedProject
project.Issue(NumberOptions) Issue
project.JobLog(JobLogOptions) JobLog
project.LinkPullRequest(LinkPullRequestOptions) None
project.ListBranches(PathOptions) Branches
project.ListCheckouts(PathOptions) []Worktree
Expand Down Expand Up @@ -1430,6 +1431,15 @@ Issue {
url string
}

JobLogOptions {
path string
url string
}

JobLog {
steps []JobStep
}

LinkPullRequestOptions {
session string
path string
Expand Down Expand Up @@ -3241,6 +3251,14 @@ GitCommit {
head,omitempty bool
}

JobStep {
name string
state string
startedAt string
completedAt string
lines []string
}

ChecksRollup {
passed int
failed int
Expand Down Expand Up @@ -3299,6 +3317,7 @@ CheckItem {
startedAt string
completedAt string
required bool
hasLog bool
}

PRCommit {
Expand Down
10 changes: 10 additions & 0 deletions docs/ceilings.md
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,16 @@ work when nobody knows it and that the call site never shows. The mechanism and
without comparing them — noreply forms, vanity domains and org aliases make a string comparison a
false-positive farm. The Commits tab of the Pulls screen lists each commit's author and compares it with
nothing either, so a branch built under the wrong identity says so nowhere in lich.
- **A check's log opens in the window only once its job is over, and only for GitHub Actions and GitLab jobs**
(`internal/project/joblog.go`): neither forge serves a running job's log whole, and another service's check is
a link. Such a check opens its page in the browser. GitHub's log is one text with no step in it, so it is cut
at the steps' own start times, which are whole seconds: a line printed in the second a step changed can stand
under its neighbour. A GitLab trace names its sections only by the runner's own words for them, so it opens as
one log with no steps.
- **Ready to merge on the Pulls list is what a list row says** (`needOf`, `native/cmd/lich-native/pulls_logic.go`):
no draft, no failing or running check, and no review asked for or refused. A row does not carry whether the
branch conflicts with its base, and a GitLab row carries no checks, so one that cannot merge can stand there;
opening it says so.
- **A checkout is GitLab only when its remote says so, and glab is the judge of a self-hosted one**
(`internal/project/forge.go` `forgeOf`): the remote is origin, else the first one git lists. github.com is
GitHub, gitlab.com is GitLab, and any other host is GitLab only when `glab config get token --host <host>`
Expand Down
2 changes: 2 additions & 0 deletions internal/project/forge.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ type forge interface {
// wtPath; accountDir names whose account the call runs as.
checkoutPullRequest(accountDir, wtPath string, number int) error
checkLog(dir string, lines int) (api.CheckLog, error)
// jobLog is the whole log of the job whose page a check's URL names.
jobLog(path, page string) (api.JobLog, error)
}

// Forge answers which forge opts.Path's remote points at.
Expand Down
14 changes: 11 additions & 3 deletions internal/project/gitlabchecks.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ func jobChecks(jobs []glabJob) (ChecksRollup, []CheckItem) {
r.Pending++
}
items = append(items, CheckItem{Name: j.Name, State: state, Description: j.Stage, URL: j.WebURL,
StartedAt: j.StartedAt, CompletedAt: j.FinishedAt, Required: !j.AllowFailure})
StartedAt: j.StartedAt, CompletedAt: j.FinishedAt, Required: !j.AllowFailure,
HasLog: state != checkPending && j.StartedAt != "" && gitlabJobPage.MatchString(j.WebURL)})
}
sort.SliceStable(items, func(i, k int) bool { return checkOrder[items[i].State] < checkOrder[items[k].State] })
return r, items
Expand Down Expand Up @@ -155,6 +156,14 @@ var (
traceSection = regexp.MustCompile(`section_(start|end):\d+:([^\[\r\s]+)(?:\[[^\]]*\])?\r?(?:\x1b\[0K)?`)
)

// traceLine is a trace's line as the job printed it, and whether it carried a
// section marker of the runner's.
func traceLine(line string) (text string, marked bool) {
line = traceStamp.ReplaceAllString(line, "")
text = traceSection.ReplaceAllString(line, "")
return strings.TrimRight(terminalCode.ReplaceAllString(text, ""), "\r"), text != line
}

// traceSteps keeps the tail of the job's script section, or of the whole trace
// when it has none (a job that failed setting up).
func traceSteps(raw []byte, lines int) []api.StepLog {
Expand All @@ -173,8 +182,7 @@ func traceSteps(raw []byte, lines int) []api.StepLog {
sawScript = sawScript || inScript
}
}
line = traceSection.ReplaceAllString(line, "")
line = strings.TrimRight(terminalCode.ReplaceAllString(line, ""), "\r")
line, _ = traceLine(line)
if line == "" && markers != nil {
continue
}
Expand Down
167 changes: 167 additions & 0 deletions internal/project/joblog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
package project

import (
"context"
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
"time"

"github.com/lichdotdev/lich/api"
)

var (
// githubJobPage and gitlabJobPage take the repository and the job from a
// check's URL. Only these characters reach the endpoint built from them.
githubJobPage = regexp.MustCompile(`^https://[^/]+/([\w.-]+/[\w.-]+)/actions/runs/\d+/job/(\d+)`)
gitlabJobPage = regexp.MustCompile(`^https?://[^/]+/([\w./-]+)/-/jobs/(\d+)`)
)

// stepOpeners are what the runner's first line of a step reads: a step of the
// workflow, an action's cleanup, and the job's own end.
var stepOpeners = []string{stepMarker, "Post job cleanup.", "Cleaning up orphan processes"}

// JobLog reads the whole log of one finished job, the check at opts.URL.
func (s *Service) JobLog(_ context.Context, opts api.JobLogOptions) (api.JobLog, error) {
return s.forgeOf(opts.Path).jobLog(opts.Path, opts.URL)
}

type githubJobStep struct {
Name string `json:"name"`
Conclusion string `json:"conclusion"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
}

func (g githubForge) jobLog(path, page string) (api.JobLog, error) {
m := githubJobPage.FindStringSubmatch(page)
if m == nil {
return api.JobLog{}, fmt.Errorf("%q is not a GitHub Actions job", page)
}
endpoint := "repos/" + m[1] + "/actions/jobs/" + m[2]
out, err := g.s.gh(prReadTimeout, path, "api", endpoint)
if err != nil {
return api.JobLog{}, err
}
var job struct {
Steps []githubJobStep `json:"steps"`
}
if err := json.Unmarshal(out, &job); err != nil {
return api.JobLog{}, errUnreadableAnswer(err)
}
raw, err := g.rawJobLog(path, endpoint+"/logs")
if err != nil {
return api.JobLog{}, err
}
return api.JobLog{Steps: splitJobLog(raw, job.Steps)}, nil
}

// rawJobLog downloads a job's log from the API, which serves it as soon as the
// job ends, where `gh run view --log` waits for its whole run. gh 2.102 refuses
// a response holding terminal escapes unless told to let it through, and an
// older gh does not know that flag; the escapes are dropped in splitJobLog.
func (g githubForge) rawJobLog(path, endpoint string) ([]byte, error) {
out, err := g.s.gh(checkLogTimeout, path, "api", "--allow-escape-sequences", endpoint)
if err != nil && strings.Contains(err.Error(), "unknown flag") {
return g.s.gh(checkLogTimeout, path, "api", endpoint)
}
return out, err
}

// splitJobLog hands each line of a job's log to the step that wrote it. The log
// names no step, and a step's start is told to the second, so a line opens the
// next step when it is later than that second, or in it and reads as an opening.
func splitJobLog(raw []byte, steps []githubJobStep) []api.JobStep {
var out []api.JobStep
var starts []time.Time
for _, st := range steps {
if st.Conclusion == "skipped" {
continue
}
out = append(out, api.JobStep{Name: st.Name, State: stepState(st.Conclusion),
StartedAt: st.StartedAt.Format(time.RFC3339), CompletedAt: st.CompletedAt.Format(time.RFC3339)})
starts = append(starts, st.StartedAt)
}
if len(out) == 0 {
out, starts = []api.JobStep{{}}, []time.Time{{}}
}
at := 0
for line := range strings.SplitSeq(strings.TrimRight(string(raw), "\n"), "\n") {
stamp, text := splitStamp(line)
for at+1 < len(out) && opensStep(stamp, text, starts[at+1]) {
at++
}
if text != "##[endgroup]" {
out[at].Lines = append(out[at].Lines, text)
}
}
return out
}

func opensStep(stamp time.Time, text string, start time.Time) bool {
if stamp.IsZero() {
return false
}
second := stamp.Truncate(time.Second)
if second.After(start) {
return true
}
if second.Before(start) {
return false
}
for _, opener := range stepOpeners {
if strings.HasPrefix(text, opener) {
return true
}
}
return false
}

// splitStamp reads a raw log line into its time, zero for a line that carries
// none, and its text.
func splitStamp(line string) (time.Time, string) {
line = strings.TrimPrefix(line, "\uFEFF")
stamp, text, _ := strings.Cut(line, " ")
at, err := time.Parse(time.RFC3339Nano, strings.TrimSuffix(stamp, "\r"))
if err != nil {
return time.Time{}, printed(line)
}
return at, printed(text)
}

// printed is a line as a terminal leaves it: no escapes, and of a line a
// progress bar redrew over itself, the last drawing.
func printed(line string) string {
line = strings.TrimRight(terminalCode.ReplaceAllString(line, ""), "\r")
return line[strings.LastIndexByte(line, '\r')+1:]
}

func stepState(conclusion string) string {
if isFailureConclusion(strings.ToUpper(conclusion)) {
return checkFailed
}
return checkPassed
}

// jobLog is the job's trace with no steps: GitLab tells a job's sections apart
// only by the runner's own names for them.
func (g gitlabForge) jobLog(path, page string) (api.JobLog, error) {
m := gitlabJobPage.FindStringSubmatch(page)
if m == nil {
return api.JobLog{}, fmt.Errorf("%q is not a GitLab job", page)
}
raw, err := g.run(checkLogTimeout, path, "api", "projects/"+url.PathEscape(m[1])+"/jobs/"+m[2]+"/trace")
if err != nil {
return api.JobLog{}, err
}
step := api.JobStep{}
for line := range strings.SplitSeq(strings.TrimRight(string(raw), "\n"), "\n") {
text, marked := traceLine(line)
if text != "" || !marked {
step.Lines = append(step.Lines, printed(text))
}
}
return api.JobLog{Steps: []api.JobStep{step}}, nil
}
Loading
Loading