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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 2.0.3

### Added

- A question answered in chat, or by a comment on any of the thread's subjects (the pull request, say), unblocks the thread, so its queue goes out. A blocked thread says what it waits on in `loopway threads`, `--json` and the TUI.

## 2.0.2

### Added
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,11 @@ The bare `loopway` adds thread lines to its output, after the line of the event
```
3f9a1c2e dev open owner/repo#12 2 pending
8c01d7b4 review closed owner/repo#13 1 pending
24edcfc4 dev open owner/repo#14 3 pending blocked: question on owner/repo#14 https://github.com/owner/repo/issues/14#issuecomment-1
```

A thread waiting on an ask says so: `blocked: <kind> on <subject> <url>` for its oldest open ask (`(+N more)` when there are several). `--json` has `blocked: { kind, subject, url }` for it, and nothing for a thread that isn't waiting. The TUI shows the same on the main view's row, and the thread view's Pending section says its updates wait on the answer.

## Sessions

Each open thread with queued updates and no run in flight gets all of them, oldest first, in one run of Claude Code (`claude -p --permission-mode auto --output-format stream-json`) in the directory `loopway` runs in. A new session gets the bot's prompt plus the updates; later batches run with `--resume <session id>`. `--max N` (default 3) caps the runs in flight.
Expand Down Expand Up @@ -133,7 +136,8 @@ A session can also ask a question itself: `ask(subject, question)` posts it (mar
How an ask is answered:

- **A reaction.** After every pass over the known subjects (every 30 s) loopway reads the reactions on its open permission asks. A 👍 or 👎 from your `gh` user, and nobody else, answers. A 👍 resumes the session with `approved: <tool> <input>` and "Retry it.", and the approval is remembered (`session.approved`), so the same call passes next time. A 👎 resumes it with `denied`. If you left both, the 👎 wins. It costs one conditional request per open ask, and a 304 is free.
- **A reply.** A comment from your `gh` user on the question's subject, after the question, answers it. It is queued like any update, and the ask is marked answered.
- **A reply.** A comment from your `gh` user on any open subject of the thread, after the question, answers it, so a reply on the pull request answers a question asked on its issue. It is queued like any update, and the ask is marked answered.
- **A chat message.** Anything you send in the TUI's chat answers the thread's open questions (`answered ... chatted`), since you are talking to the session. The queue it held back goes out on the run after the chat block ends. A permission ask is not answered by chat: it still needs a 👍 or 👎.
- Either way the session leaves `blocked` and its next run gets the answer. A blocked session is not run for other updates meanwhile: they wait in the queue.

Open asks live in the thread's JSON, so a restart keeps waiting on them. The log (`loopway`, `--json`) has `asked` and `answered` lines, and the TUI's thread view lists what the thread is waiting on, with links; `blocked` shows as the session status on the main view.
Expand Down
2 changes: 1 addition & 1 deletion docs/developing.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ When CI passes on a push to `main` and `packages/cli` changed since the last `cl
| `sessions.ts` | Delivers each thread's queue to its session (`--max`, resume, requeue on failure, usage-limit hold), and records what it sends. Also the TUI's chat blocks: messages from the owner go to the session in order, the queue waits, and the end of the block tells the session to report |
| `claude.ts`, `transcript.ts` | The Claude Code harness: `claude -p` args, spawn, how a run ended, and the stream turned into log lines |
| `mcp.ts` | loopway's MCP server (HTTP, one path per thread) with the `comment`, `ask`, `create_issue`, `create_pr` and `permission` tools |
| `asks.ts` | Asks: the allow/deny rule matching, the comments loopway posts to ask, and reading the owner's reactions |
| `asks.ts` | Asks: what a thread is blocked on, the allow/deny rule matching, the comments loopway posts to ask, and reading the owner's reactions |
| `update.ts` | Self-update: the latest `cli-v*` release, installing its `loopway-cli.tgz` with `npm install -g`, re-exec, and the 10-minute watch. `index.ts` wires it: a lookup before anything starts, and `Sessions.drain` while a newer release waits for runs to finish |
| `config.ts`, `state.ts` | `~/.loopway/config.json`'s `github` block and `auto_update`, and `stateDir`, where `state.json` and the threads live |
| `tui.tsx`, `tui-main.tsx`, `tui-thread.tsx` | The [Ink](https://github.com/vadimdemedes/ink) TUI: the root, the main view (threads grouped by state) and the thread view. Reads threads from the in-process store and the session log from disk |
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@loopway/cli",
"version": "2.0.2",
"version": "2.0.3",
"private": true,
"license": "MIT",
"description": "loopway: polls GitHub and prints every new subject and every update to one you know.",
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/asks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ export interface Ask {

export const openAsks = (thread: Thread): Ask[] => (thread.asks ?? []).filter((a) => !a.answeredAt);

/** What a thread's session waits on: its oldest open ask, and how many more there are. */
export function blockedOn(thread: Thread): (Ask & { more: number }) | undefined {
const [first, ...rest] = openAsks(thread);
return first && { ...first, more: rest.length };
}

/** `blocked: question on owner/repo#12 <url>`, with `(+N more)` when it waits on several. */
export const blockedText = (ask: Ask & { more: number }) =>
`blocked: ${ask.kind} on ${ask.subject} ${ask.commentUrl}${ask.more ? ` (+${ask.more} more)` : ""}`;

/** The same call: the same tool with the same input. */
export function callKey(tool: string, input: unknown): string {
// Claude words a Bash call's `description` differently each time it retries; the rest of the input is the call.
Expand Down
21 changes: 15 additions & 6 deletions packages/cli/src/format.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { blockedOn, blockedText } from "./asks.js";
import type { Subject, Update } from "./source.js";
import type { Thread } from "./thread.js";

Expand All @@ -24,7 +25,7 @@ export type ThreadEvent =
| { type: "queued"; subject: string; update: Update; thread: string }
| { type: "ignored"; subject: string; update: Update; thread: string }
| { type: "thread_closed"; thread: Thread }
| { type: "answered"; at: string; thread: string; what: string; how: "approved" | "denied" | "replied" };
| { type: "answered"; at: string; thread: string; what: string; how: "approved" | "denied" | "replied" | "chatted" };

const pad = (n: number) => String(n).padStart(2, "0");

Expand Down Expand Up @@ -147,17 +148,25 @@ export function formatJson(event: LoopwayEvent): string {
}
}

/** One row of `loopway threads`: id, bot, status, subjects, pending count. */
export const formatThread = (t: Thread) =>
`${t.id} ${t.bot.padEnd(8)} ${t.status.padEnd(6)} ${subjectKeys(t)} ${t.queue.length} pending`;
/** One row of `loopway threads`: id, bot, status, subjects, pending count, and what it is blocked on if it is. */
export const formatThread = (t: Thread) => {
const blocked = blockedOn(t);
return (
`${t.id} ${t.bot.padEnd(8)} ${t.status.padEnd(6)} ${subjectKeys(t)} ${t.queue.length} pending` +
(blocked ? ` ${blockedText(blocked)}` : "")
);
};

export const formatThreadJson = (t: Thread) =>
JSON.stringify({
export const formatThreadJson = (t: Thread) => {
const blocked = blockedOn(t);
return JSON.stringify({
id: t.id,
bot: t.bot,
status: t.status,
subjects: t.subjects.map((s) => s.key),
pending: t.queue.length,
...(blocked ? { blocked: { kind: blocked.kind, subject: blocked.subject, url: blocked.commentUrl } } : {}),
createdAt: t.createdAt,
latestAt: t.latestAt,
});
};
16 changes: 14 additions & 2 deletions packages/cli/src/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from "./asks.js";
import type { Bot } from "./bots.js";
import type { RunAgent, RunOutcome } from "./claude.js";
import type { SessionEvent } from "./format.js";
import type { SessionEvent, ThreadEvent } from "./format.js";
import { abortableSleep } from "./poller.js";
import type { IssueOptions, Made, Subject } from "./source.js";
import { markerOf, repoOf, type Pending, type Session, type Thread } from "./thread.js";
Expand Down Expand Up @@ -95,7 +95,7 @@ export interface SessionsOptions {
};
/** Told after a thread created a subject, once it is recorded as sent: the rest of loopway takes it in. */
created: (thread: string, subject: Subject, subscribe: boolean) => Promise<void>;
emit: (event: SessionEvent) => void;
emit: (event: SessionEvent | ThreadEvent) => void;
now?: () => number;
newSessionId?: () => string;
newAskId?: () => string;
Expand Down Expand Up @@ -167,9 +167,21 @@ export class Sessions {
chat.inbox.push(text);
chat.said = true;
this.log(thread, `you> ${text}`);
this.answerQuestions(thread);
this.kick();
}

/** The owner said something in chat: the questions the thread was blocked on are answered. */
private answerQuestions(thread: Thread): void {
const events = this.o.threads.answerByChat(thread);
if (events.length === 0) return;
void this.o.threads.save(thread);
for (const event of events) {
if (event.type === "answered") this.log(thread, `answered by chat: ${event.what}`);
this.o.emit(event);
}
}

/** Ends the chat block. If anything was said, the session is told so, and reports it to the ticket if it should. */
endChat(threadId: string): void {
const chat = this.chats.get(threadId);
Expand Down
24 changes: 22 additions & 2 deletions packages/cli/src/threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,17 +141,37 @@ export class Threads {
events.push({ type: "queued", subject, update, thread: thread.id });
}

/** The owner's comment on a subject after a question was asked there answers it. It is queued like any update. */
/**
* The owner's comment on any open subject of the thread, after a question was asked, answers it: the question may
* have been asked on the issue and the answer given on the pull request. It is queued like any update.
*/
private answerQuestions(thread: Thread, subject: string, update: Update, events: ThreadEvent[]) {
if (update.kind !== "comment" || update.actor.toLowerCase() !== this.o.owner?.toLowerCase()) return;
if (thread.subjects.find((s) => s.key === subject)?.status !== "open") return;
for (const ask of openAsks(thread)) {
if (ask.kind !== "question" || ask.subject !== subject || ask.at >= update.at) continue;
if (ask.kind !== "question" || ask.at >= update.at) continue;
ask.answeredAt = update.at;
events.push({ type: "answered", at: update.at, thread: thread.id, what: askLabel(ask), how: "replied" });
}
this.unblock(thread);
}

/**
* A chat message from the owner answers the thread's open questions: they are talking to the session, so it need not
* wait for a comment. A permission ask still needs its 👍 or 👎. The queue it held back goes out on the next run.
* The caller saves the thread.
*/
answerByChat(thread: Thread): ThreadEvent[] {
const at = new Date(this.now()).toISOString();
const events: ThreadEvent[] = [];
for (const ask of openAsks(thread).filter((a) => a.kind === "question")) {
ask.answeredAt = at;
events.push({ type: "answered", at, thread: thread.id, what: askLabel(ask), how: "chatted" });
}
if (events.length > 0) this.unblock(thread);
return events;
}

/**
* The owner's 👍 or 👎 on a permission ask. A 👍 is remembered, so the same call passes next time. Either way the
* session is told on its queue and is no longer blocked.
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/tui-main.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Box, Text, useInput, useWindowSize } from "ink";
import { blockedOn, blockedText } from "./asks.js";
import { stamp, subjectKeys } from "./format.js";
import type { Thread } from "./thread.js";
import { Footer, Header, HEADER_ROWS } from "./tui-header.js";
Expand Down Expand Up @@ -94,6 +95,7 @@ export function MainView(props: MainViewProps) {
/** bot, session status, pending count, time of the latest message, subjects. Closed threads are dim. */
function Row({ thread, selected }: { thread: Thread; selected: boolean }) {
const closed = thread.status === "closed";
const blocked = blockedOn(thread);
return (
<Text
wrap="truncate-end"
Expand All @@ -106,6 +108,7 @@ function Row({ thread, selected }: { thread: Thread; selected: boolean }) {
<Text color={selected ? theme.cream : sessionColor(thread)}>{sessionText(thread).padEnd(14)}</Text>
{" "}
{thread.queue.length} pending {stamp(thread.latestAt)} {subjectKeys(thread)}
{blocked && <Text color={selected ? theme.cream : theme.land}> {blockedText(blocked)}</Text>}
</Text>
);
}
6 changes: 5 additions & 1 deletion packages/cli/src/tui-thread.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ export function ThreadView({ thread, version, status, log, onBack, onFilter, cha
<Box>
<Stat n={thread.subjects.length} label="subjects" color={theme.cream} />
<Stat n={open.length} label="waiting on you" color={open.length ? theme.land : theme.green} />
<Stat n={thread.queue.length} label="updates queued" color={thread.queue.length ? theme.blue : theme.green} />
<Stat
n={thread.queue.length}
label={open.length && thread.queue.length ? "updates waiting on the answer" : "updates queued"}
color={thread.queue.length ? theme.blue : theme.green}
/>
<Stat n={sent} label="messages sent" color={theme.green} />
</Box>
{thread.subjects.map((s, i) => (
Expand Down
73 changes: 66 additions & 7 deletions packages/cli/test/asks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,16 +334,27 @@ describe("questions", () => {
expect(s.runs[0]?.message).toContain("notes.md");
});

it("only answers a question asked on the subject the owner commented on", async () => {
it("is answered by the owner's comment on any open subject of the thread, such as the pull request", async () => {
const s = await setup();
s.thread.subjects.push({ key: "o/r#13", status: "open" });
s.thread.subjects.push({ key: "o/r#13", status: "open", created: true }, { key: "o/r#14", status: "closed" });
await s.sessions.ask("t1", SUBJECT, question);
await s.threads.handle({
type: "update",
subject: { key: "o/r#13", kind: "issue", title: "t", author: "me", createdAt: "2026-11-10T12:00:00Z" },
update: { id: "c1", kind: "comment", actor: "me", at: "2026-11-10T15:01:00Z" },
});
const comment = (key: string, actor: string, at: string) =>
s.threads.handle({
type: "update",
subject: { key, kind: "pull_request", title: "t", author: "me", createdAt: "2026-11-10T12:00:00Z" },
update: { id: `c-${key}-${actor}-${at}`, kind: "comment", actor, at },
});
// Someone else, the owner before the question, and the owner on a closed subject don't answer it.
await comment("o/r#13", "someone", "2026-11-10T15:01:00Z");
await comment("o/r#13", "me", "2026-11-10T14:00:00Z");
await comment("o/r#14", "me", "2026-11-10T15:01:00Z");
expect(openAsks(s.thread)).toHaveLength(1);
expect(s.thread.session?.status).toBe("blocked");

const events = await comment("o/r#13", "me", "2026-11-10T15:02:00Z");
expect(events).toContainEqual(expect.objectContaining({ type: "answered", how: "replied" }));
expect(openAsks(s.thread)).toEqual([]);
expect(s.thread.session?.status).toBe("idle");
});

it("refuses a question on a subject the bot does not read", async () => {
Expand All @@ -353,6 +364,54 @@ describe("questions", () => {
});
});

describe("a chat message", () => {
const question = "Which file name should I use?";

it("answers the open questions, unblocks the thread, and the next run delivers the whole queue", async () => {
const s = await setup();
await s.sessions.ask("t1", SUBJECT, question);
s.thread.session!.id = "sid";
s.thread.queue.push({ id: "c1", kind: "comment", actor: "alice", at: "2026-11-10T15:01:00Z", subject: SUBJECT });
s.thread.queue.push({ id: "c2", kind: "check_run", actor: "ci", at: "2026-11-10T15:02:00Z", subject: SUBJECT });
s.sessions.kick();
await s.sessions.idle();
expect(s.runs).toHaveLength(0);

s.sessions.chat("t1", "call it notes.md");
await s.sessions.idle();
expect(s.runs).toHaveLength(1);
expect(s.runs[0]!.message).toContain("Chat: call it notes.md");
expect(s.thread.queue).toHaveLength(2);
expect(s.thread.asks).toMatchObject([{ kind: "question", answeredAt: expect.any(String) }]);
expect(s.events).toContainEqual(expect.objectContaining({ type: "answered", how: "chatted" }));
expect(await s.log()).toContain("answered by chat: " + question);
expect(s.thread.session?.status).toBe("idle");

s.sessions.endChat("t1");
await s.sessions.idle();
expect(s.runs).toHaveLength(2);
expect(s.runs[1]!.message).toContain("2 updates since your last turn");
expect(await s.log()).toContain("-> delivered 2 updates");
expect(s.thread.queue).toEqual([]);
});

it("does not answer a permission ask: the thread stays blocked and its queue waits", async () => {
const s = await setup();
await s.sessions.permission("t1", "Bash", CURL);
s.thread.session!.id = "sid";
s.thread.queue.push({ id: "c1", kind: "comment", actor: "alice", at: "2026-11-10T15:01:00Z", subject: SUBJECT });

s.sessions.chat("t1", "hello");
await s.sessions.idle();
s.sessions.endChat("t1");
await s.sessions.idle();
expect(openAsks(s.thread)).toHaveLength(1);
expect(s.thread.session?.status).toBe("blocked");
expect(s.thread.queue).toHaveLength(1);
expect(s.events.some((e) => e.type === "answered")).toBe(false);
});
});

describe("over MCP, with a claude stand-in", () => {
it("answers the permission tool the way Claude Code reads it, and the ask tool with what to do next", async () => {
const s = await setup({ bot: { ...aBot("dev", ["issue"]), allow: ["Bash(ls:*)"] } });
Expand Down
22 changes: 22 additions & 0 deletions packages/cli/test/files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,28 @@ describe("output", () => {
"abc12345 dev open o/r#12 1 pending",
);
expect(JSON.parse(formatThreadJson(thread))).toMatchObject({ id: "abc12345", bot: "dev", pending: 0 });
expect(JSON.parse(formatThreadJson(thread))).not.toHaveProperty("blocked");
const url = "https://github.com/o/r/issues/12#issuecomment-1";
const ask = (id: string, kind: "question" | "permission") => ({
id,
kind,
commentUrl: url,
subject: "o/r#12",
tool: "ask",
input: "which file?",
at: "2026-11-10T14:03:00Z",
});
const blocked = { ...thread, asks: [ask("a1", "question")] };
expect(formatThread(blocked)).toBe(
`abc12345 dev open o/r#12 0 pending blocked: question on o/r#12 ${url}`,
);
expect(JSON.parse(formatThreadJson(blocked)).blocked).toEqual({ kind: "question", subject: "o/r#12", url });
expect(formatThread({ ...blocked, asks: [ask("a1", "permission"), ask("a2", "question")] })).toContain(
`blocked: permission on o/r#12 ${url} (+1 more)`,
);
expect(formatThread({ ...thread, asks: [{ ...ask("a1", "question"), answeredAt: "2026-11-10T14:04:00Z" }] })).toBe(
"abc12345 dev open o/r#12 0 pending",
);
expect(JSON.parse(formatJson({ type: "queued", subject: "o/r#12", update, thread: "abc12345" }))).toMatchObject({
type: "queued",
thread: "abc12345",
Expand Down
Loading
Loading