From 20f39564528e6c824821f9f381cb5fce41b8e66a Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:43:31 +0900 Subject: [PATCH 1/3] =?UTF-8?q?feat(todo):=20=EC=97=90=EC=9D=B4=EC=A0=84?= =?UTF-8?q?=ED=8A=B8=EA=B0=80=20=EC=A7=80=EA=B8=88=20=EC=9E=91=EC=97=85=20?= =?UTF-8?q?=EC=A4=91=EC=9D=B8=20=ED=95=AD=EB=AA=A9=EC=9D=84=20working=20?= =?UTF-8?q?=ED=91=9C=EC=8B=9C=EB=A1=9C=20=EB=B3=B4=EC=97=AC=20=EC=A4=80?= =?UTF-8?q?=EB=8B=A4=20(v2.26.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit todo.mjs working [what] | --off 가 todo.md 옆 todo-working.json(0600)에 심박을 남기고, 180초 안에 갱신된 표시만 '지금 작업 중'으로 앱·웹·TUI에 보인다. 표시 없는 에이전트 차례는 '에이전트 차례'로 바꿨다. 만료는 서버·TUI 타이머가 쓰기 없이 반영한다. --- README.ko.md | 4 ++- README.md | 4 ++- VERSION | 2 +- log/changelog-v2.26.0.md | 20 ++++++++++++ tests/todo-page.test.mjs | 2 +- tests/todo-web.test.mjs | 23 ++++++++++++++ tests/todo.test.mjs | 40 +++++++++++++++++++++++ todo/AGENT.md | 11 ++++--- todo/app/src/client.rs | 11 +++++++ todo/app/src/i18n.rs | 5 ++- todo/app/src/main.rs | 68 +++++++++++++++++++++++++++++++++++----- todo/app/src/theme.rs | 2 ++ todo/core.mjs | 58 ++++++++++++++++++++++++++++++++-- todo/locales/en.mjs | 7 +++-- todo/locales/ko.mjs | 7 +++-- todo/page/app.css | 10 ++++++ todo/page/app.js | 11 ++++--- todo/status.mjs | 11 +++++++ todo/todo.mjs | 13 +++++--- todo/tui.mjs | 13 +++++--- todo/web.mjs | 7 +++-- 21 files changed, 289 insertions(+), 40 deletions(-) create mode 100644 log/changelog-v2.26.0.md diff --git a/README.ko.md b/README.ko.md index 841bb7a..9ab28ce 100644 --- a/README.ko.md +++ b/README.ko.md @@ -172,13 +172,15 @@ node ~/sdlc-kit/todo/todo.mjs take --json # 작업자가 맡은 항목 TUI와 웹 페이지는 영어나 한국어로 표시합니다. `--lang ko`(TUI 또는 `web`)를 주거나 `SDLC_TODO_LANG=ko`를 지정하세요. 플래그가 우선하고, 모르는 값이면 영어, 기본값도 영어입니다. TUI에서는 `L`, 웹 페이지에서는 언어 메뉴로 바꾸며 다시 시작하거나 새로 고칠 때까지 유지됩니다. -상태는 다음에 누가 움직일지 보여 줍니다. 내 차례(범위 승인·계획 승인·답변), 에이전트 진행 중, 답변 전달됨 — 에이전트 수신 전, 시작 전, 막힘 — 조치 필요, 완료이며, 에이전트가 멈추는 행에는 그 사실을 적습니다. +상태는 다음에 누가 움직일지 보여 줍니다. 내 차례(범위 승인·계획 승인·답변), 지금 작업 중(에이전트가 3분 안에 `working`으로 표시한 항목, 몇 분째·무슨 일인지 함께 보임), 에이전트 차례(아직 아무도 잡지 않음), 답변 전달됨 — 에이전트 수신 전, 시작 전, 막힘 — 조치 필요, 완료이며, 에이전트가 멈추는 행에는 그 사실을 적습니다. 항목에는 마크다운 브리프를 붙일 수 있습니다(`brief <절대 경로>` 또는 `add --brief PATH`, ` - brief: <경로>`로 저장). 앱과 페이지는 이를 sdlc 작업 문서처럼(At a glance, Questions for you, 전체 문서는 접음) 보여 주며 승인 버튼은 없습니다. 브리프는 앱이 읽는 하나뿐인 형식인 `todo/brief.md`(Your call, What changes, AI pick, Phase, Background, Why)로 쓰고, 채울 수 없는 줄은 뺍니다. 항목에는 변경이 들어간 저장소도 적을 수 있습니다(`repos aidt-lms-api,aidt-viewer-api`, ` - repos: aidt-lms-api, aidt-viewer-api`로 저장, 이름 없이 실행하면 지움). 앱 카드, 페이지 목록·상세, TUI 목록·상세에 항상 보입니다. 결정에는 한 번에 고르는 답을 붙일 수 있습니다(`choices "진행 | 먼저 고침 | 보류" [--pick N]`, ` - choices: 진행 | 먼저 고침 | 보류`와 ` - pick: N`으로 저장, 최대 6개, 답 없이 실행하면 지움). 열린 항목이면 앱 카드, 페이지 상세(답변 칸 위), TUI(숫자 키)에 답마다 버튼이 생기고, 누르면 그 답 글자 그대로 보통 답변으로 보냅니다. `--pick`으로 고른 답은 맨 앞에 "권장"으로 표시합니다. 같은 티켓 링크를 가진, 내가 볼 열린 항목은 앱과 페이지에서 그 티켓 아래에 모아 보입니다. 에이전트는 권장 답을 미리 채워 둘 수도 있습니다(`suggest "답"`, ` - suggest: 답`으로 저장, 내 답변이나 빈 값이 지움). 앱 카드, 페이지 답변 칸, TUI 답변 줄(`r`)이 그 글자로 시작하므로 그대로 보내면 한 번에 끝납니다. 고친 답은 덮어쓰지 않고, 새 권장 답은 고치지 않은 칸만 바꿉니다. 앱 카드의 '에이전트가 묻고 있어요' 칸에는 요약의 Your call과 AI pick만 보이고(요약에 질문이 없을 때만 대기 문구), What changes는 그 아래 흐린 한 줄로 보입니다. +지금 항목을 작업 중인 에이전트는 `todo.mjs working ["단계"]`(예: `build`, `dev QA`)로 표시하고 적어도 60초마다 다시 부르며, 끝나면 `working --off`로 지웁니다. 표시는 `todo.md`가 아닌 할 일 파일 옆 `todo-working.json`(소유자만 읽기)에 남고, 마지막 갱신 뒤 3분이 지나면 저절로 사라지므로 죽은 작업자의 표시는 남지 않습니다. 모든 화면에 "지금 작업 중 · 12분째 · build"와 깜박이는 초록 점으로 보이고, 아무 에이전트도 표시하지 않은 열린 항목은 "에이전트 차례"로 보입니다. `list --json`과 웹 API에는 `working: {what, since, beat}` 또는 `null`로 실립니다. + 사람이 직접 실행해야 하는 명령(OTP를 묻는 VPN 연결 등)은 에이전트가 `run "명령"`으로 남깁니다(` - run: 명령`, 내 답변·`resume`·`done`·빈 값이 지움). 앱 카드에는 명령과 **터미널에서 열기** 버튼이 보입니다. macOS의 zsh에서는 명령이 입력만 된 채로 Terminal이 열리므로, 확인하고 Enter를 누르면 됩니다. 다른 환경에서는 버튼이 명령을 복사합니다. 페이지와 TUI 상세에도 명령이 보입니다. 단 답은 에이전트가 `next`나 `take`로 읽기 전까지 "답변 전달됨 — 에이전트 수신 전"으로 보이고, sdlc 대기였다면 읽은 뒤 sdlc.sh가 다음 단계로 넘어갈 때까지 다시 내 차례로 돌아옵니다. sdlc 밖에서 사람을 기다리는 작업자(승인, 티켓 답변 등)는 `wait`로 남기고 `resume`으로 지웁니다. 다른 사람(QA·기획)이 먼저 답해야 하면 `others "누구"`로 "다른 사람 회신 대기"를 표시합니다. 이 항목은 확인 필요에서 빠지고 `next`가 건너뛰며(`take`는 exit 15), 내 답글·`wait`·`resume`이 지웁니다. 모든 화면은 서버 하나를 같이 씁니다. 처음 띄운 쪽이 포트와 토큰을 to-do 파일 옆 `todo-web.json`(소유자만 읽기)에 남기고, 뒤에 띄운 화면·앱·`todo.mjs serve`는 그 서버가 응답하는 동안 다시 씁니다. diff --git a/README.md b/README.md index 7840184..fdf98cf 100644 --- a/README.md +++ b/README.md @@ -196,13 +196,15 @@ node ~/sdlc-kit/todo/todo.mjs take --json # one item a worker owns, with The TUI and web page show English or Korean: pass `--lang ko` (TUI or `web`) or set `SDLC_TODO_LANG=ko`; the flag wins, an unknown variable means English, and English is the default. Press `L` in the TUI or use the page's language menu to switch until restart or reload. -Statuses say who acts next: your turn (approve intent, approve plan or answer), agent working, answered — not picked up yet, not started, blocked — fix needed, or done; the row where agents stop says so. +Statuses say who acts next: your turn (approve intent, approve plan or answer), working now (an agent marked it with `working` within the last 3 minutes; it shows how long and on what), agent's turn (nobody is on it yet), answered — not picked up yet, not started, blocked — fix needed, or done; the row where agents stop says so. An item may carry a markdown brief (`brief ` or `add --brief PATH`, stored as ` - brief: `); the app and page show it like an sdlc work document (At a glance, Questions for you, full text folded) without approval. Write it from `todo/brief.md`, the one format the app reads (Your call, What changes, AI pick, Phase, Background, Why); leave out a line you cannot fill. An item may also name the repositories its change touches (`repos aidt-lms-api,aidt-viewer-api`, stored as ` - repos: aidt-lms-api, aidt-viewer-api`; no name clears it). The app card, the page row and detail, and the TUI row and detail always show them. A decision can offer one-click answers (`choices "proceed | fix first | hold" [--pick N]`, stored as ` - choices: proceed | fix first | hold` and ` - pick: N`; up to 6 labels, no labels clears them). On an open item the app card, the page detail (above the reply box) and the TUI (number keys) show one button per label; a click sends that exact label as an ordinary reply, and the picked one comes first, marked Recommended. Open items that need you and share a ticket link sit together under that ticket in the app and page. An agent can also prefill the answer it recommends (`suggest "answer"`, stored as ` - suggest: answer`; a human reply or no text clears it). The app card, the page reply box and the TUI reply line (`r`) start with that text, so sending it as-is takes one press; an edit is never overwritten, and a new suggestion replaces only an unedited one. On the app card the "agent is asking" box shows only the brief's Your call and AI pick (the waiting line only when the brief asks nothing), with What changes as one muted line below it. +An agent working on an item right now marks it with `todo.mjs working ["step"]` (e.g. `build`, `dev QA`), repeats it at least every 60 s, and clears it with `working --off`. The mark lives in `todo-working.json` beside the to-do file (owner-only), never in `todo.md`, and expires 3 minutes after its last refresh, so the mark of a worker that died disappears by itself. Every view shows it as "Working now · 12 min · build" with a pulsing green dot; an open item no agent has marked reads "Agent's turn". `list --json` and the web API carry it as `working: {what, since, beat}` or `null`. + When the human has to run something (a VPN login that asks for an OTP, say), the agent records it with `run "command"` (` - run: command`; a reply, `resume`, `done` or no text clears it). The app card shows the command and an **Open in Terminal** button: on macOS with zsh, Terminal opens with the command typed at the prompt but not run, so you read it and press Enter; elsewhere the button copies it. The page and TUI details show the command. A reply shows "answered — no agent has picked it up yet" until an agent reads it with `next` or `take`; after an sdlc wait the item then waits for you again until sdlc.sh moves on. A worker that waits on you outside sdlc (an approval, a ticket answer) records it with `wait` and drops it with `resume`. When someone else must answer first (QA, a planner), `others "who"` marks it "waiting on someone else": it leaves Needs you, `next` passes it by (`take` exits 15), and a reply, `wait` or `resume` clears it. All surfaces share one server: the first launch writes its port and token to `todo-web.json` beside the to-do file (owner-only), and later launches, the app and `todo.mjs serve` reuse it while it answers. diff --git a/VERSION b/VERSION index d6af7e3..7a25c70 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.25.1 +2.26.0 diff --git a/log/changelog-v2.26.0.md b/log/changelog-v2.26.0.md new file mode 100644 index 0000000..ef1225d --- /dev/null +++ b/log/changelog-v2.26.0.md @@ -0,0 +1,20 @@ +# v2.26.0: The to-do shows which items an agent is working on right now + +## Problem + +Every open item whose next step was an agent's read "Agent working" (`status.agent`), whether or not any agent held it. On 2026-11-12, 26 items read "Agent working" while no agent ran, so the human could not tell real work from a queue. + +## Changes + +- **`todo.mjs working ["what"]`** marks an item as worked on now, or refreshes the mark: `beat` becomes now, `since` stays while the mark is live (else now), and `what` is a one-line label such as `build` or `dev QA` (80 characters at most; omitted keeps the previous one). `working --off` clears it. An unknown id exits 1, a done item exits 1 unless `--off`. It runs no sdlc sync and never writes `todo.md`, so a heartbeat can call it every 60 s. +- **`todo-working.json`** beside `todo.md` (follows `SDLC_TODO`) holds `{ id: { what, since, beat } }` in ISO times, written atomically with mode 0600; expired marks are pruned on each write. A mark is live while its `beat` is younger than 180 s (`core.WORKING_TTL_MS`; `SDLC_TODO_WORKING_TTL` in seconds overrides it for tests). An expired mark is ignored everywhere, so the mark of a worker that died disappears by itself. Two writers at the same moment can lose one update; the next beat restores it. +- **New status `working`** (`statusOf` → `{ actor: 'agent', kind: 'working' }`): "Working now" / "지금 작업 중", shown with elapsed minutes and the label, e.g. "지금 작업 중 · 12분째 · build". Blocked, waiting for you and waiting on someone else still win over a live mark: a turn that is yours or someone else's is never hidden by a heartbeat. The header counts are unchanged (it is still an agent's turn). +- **"Agent working" is now "Agent's turn"** / "에이전트 차례": an open item an agent should take next but nobody has marked. +- **Item JSON** (`list --json`, `next`/`take --json`, `/api/items`, `/events`) carries `working: { what, since, beat }` or `null` (null when the item is done or the mark expired). +- **Every surface tells it apart:** the app gives it its own green tint, a halo around the row dot and a pulsing dot in its pill, repainting once a second only while an item is working; the web page shows a green pill with a CSS-pulsing dot and a green row bar; the TUI marks it `◉` in bold green with a "Working now · 12 min · build" line under the row (legend updated). +- **Expiry without a write:** the server and the TUI watch `todo-working.json` and also arm a timer for the oldest live mark's expiry (`core.watchWorking`), so a mark nobody refreshes leaves every view within the TTL (plus 50 ms), with no file change. +- **Agents:** `todo/AGENT.md` asks to run `working ""` at least every 60 s while working an item and `working --off` when they stop; README and CLI help describe the command. + +## After updating + +Rebuild the app: run `todo/app/install-macos.sh` again (macOS), or `cargo build --release` in `todo/app`. Restart a running to-do server (`serve`) so it watches the new file. diff --git a/tests/todo-page.test.mjs b/tests/todo-page.test.mjs index 22f693b..1bf1e42 100644 --- a/tests/todo-page.test.mjs +++ b/tests/todo-page.test.mjs @@ -485,7 +485,7 @@ test('language: the page follows the server language, switches at runtime and ke assert.match(texts('aaaaaa'), /Approve plan/); assert.match(line('aaaaaa'), /Agents stop here until you decide/); assert.match(line('aaaaaa'), /Approve…/); - assert.match(texts('bbbbbb'), /Agent working/); + assert.match(texts('bbbbbb'), /Agent's turn/); assert.match(texts('bbbbbb'), /Queued behind your decision/); assert.equal(p.nodes.get('detail-fields').children[0].textContent, 'Status', 'open Details re-renders'); assert.equal(p.nodes.get('live-text').textContent, 'Connecting'); diff --git a/tests/todo-web.test.mjs b/tests/todo-web.test.mjs index 65608fe..4a1275b 100644 --- a/tests/todo-web.test.mjs +++ b/tests/todo-web.test.mjs @@ -237,6 +237,29 @@ function eventStream(ctx, t) { }; } +test('working: SSE shows a marker at once and drops it when its heartbeat expires, with no further write', async t => { + const ttl = process.env.SDLC_TODO_WORKING_TTL; + process.env.SDLC_TODO_WORKING_TTL = '1'; + t.after(() => { if (ttl === undefined) delete process.env.SDLC_TODO_WORKING_TTL; else process.env.SDLC_TODO_WORKING_TTL = ttl; }); + const ctx = await web(t); + const { id } = await core.add(ctx.file, 'Build it'); + const waitFor = eventStream(ctx, t); + await waitFor(value => value.items?.some(item => item.id === id)); + const marked = waitFor(value => value.items?.some(item => item.id === id && item.working?.what === 'build')); + await core.working(ctx.file, id, 'build'); + assert.deepEqual((await marked).items.find(item => item.id === id).turn, { actor: 'agent', kind: 'working' }); + const before = readFileSync(core.workingPath(ctx.file), 'utf8'); + // Frames are matched in order: the first one after the mark that no longer carries it. + let seen = false; + const expired = await waitFor(value => { + const item = value.items?.find(other => other.id === id); + if (item?.working) seen = true; + return seen && item?.working === null; + }, 3000); + assert.deepEqual(expired.items.find(item => item.id === id).turn, { actor: 'agent', kind: 'new' }); + assert.equal(readFileSync(core.workingPath(ctx.file), 'utf8'), before, 'expiry needs no write'); +}); + test('S3: SSE observes an external core write within one second without reloading', async t => { const ctx = await web(t); await core.add(ctx.file, 'Initial'); diff --git a/tests/todo.test.mjs b/tests/todo.test.mjs index a1a4415..4920c38 100644 --- a/tests/todo.test.mjs +++ b/tests/todo.test.mjs @@ -265,6 +265,46 @@ test('choices: CLI stores one-click answers and a pick, adds one event per chang assert.deepEqual([listed[0].choices, listed[0].pick], [[], null]); }); +test('working: CLI marks, refreshes and clears an item beside todo.md; statusOf shows it unless a human turn wins; it expires', async t => { + const { root, file } = scratch(t); + const a = await core.add(file, 'A20-1 build'); + const b = await core.add(file, 'B'); + const todo = readFileSync(file, 'utf8'); + checkCode(await cli(file, ['working', a.id, 'build']), 0); + const where = join(root, 'todo-working.json'); + assert.equal(core.workingPath(file), where); + if (process.platform !== 'win32') assert.equal(statSync(where).mode & 0o777, 0o600, 'only the owner reads the markers'); + const first = JSON.parse(readFileSync(where, 'utf8'))[a.id]; + assert.equal(first.what, 'build'); + assert.equal(readFileSync(file, 'utf8'), todo, 'todo.md is not written'); + let listed = JSON.parse(checkCode(await cli(file, ['list', '--json']), 0).stdout); + assert.deepEqual(listed.find(item => item.id === a.id).working, first); + assert.equal(listed.find(item => item.id === b.id).working, null); + await new Promise(resolveWait => setTimeout(resolveWait, 20)); + checkCode(await cli(file, ['working', a.id]), 0); + const second = JSON.parse(readFileSync(where, 'utf8'))[a.id]; + assert.deepEqual([second.what, second.since], ['build', first.since], 'a refresh keeps the label and the start'); + assert.ok(second.beat > first.beat, 'a refresh moves the heartbeat'); + const [item] = core.withWorking(core.load(file).items, file); + assert.deepEqual(statusOf(item), { actor: 'agent', kind: 'working' }); + assert.equal(statusOf({ ...item, status: 'waiting' }).actor, 'you', 'a human turn wins over a heartbeat'); + assert.equal(statusOf({ ...item, done: true }).kind, 'done'); + checkCode(await cli(file, ['working', 'nope', 'x']), 1); + checkCode(await cli(file, ['working', a.id, 'x', '--off']), 2); + checkCode(await cli(file, ['working', a.id, '--off']), 0); + assert.deepEqual(JSON.parse(readFileSync(where, 'utf8')), {}); + // A marker whose heartbeat is older than the TTL is ignored everywhere and pruned on the next write. + writeFileSync(where, JSON.stringify({ [a.id]: { what: 'old', since: '2026-01-01T00:00:00.000Z', beat: '2026-01-01T00:00:00.000Z' } })); + assert.equal(core.withWorking(core.load(file).items, file)[0].working, null); + checkCode(await cli(file, ['working', b.id, 'QA']), 0); + const marks = JSON.parse(readFileSync(where, 'utf8')); + assert.deepEqual(Object.keys(marks), [b.id]); + assert.notEqual(marks[b.id].since, '2026-01-01T00:00:00.000Z'); + await new Promise(resolveWait => setTimeout(resolveWait, 100)); + listed = JSON.parse(checkCode(await cli(file, ['list', '--json'], { env: { SDLC_TODO_WORKING_TTL: '0.05' } }), 0).stdout); + assert.equal(listed.find(item => item.id === b.id).working, null, 'an expired heartbeat is no marker'); +}); + test('others: an agent waiting on someone else outranks an sdlc NEEDS-HUMAN; its own wait and a reply still win', t => { const { file } = scratch(t); const status = text => { writeFileSync(file, text); return core.load(file).items[0].status; }; diff --git a/todo/AGENT.md b/todo/AGENT.md index a1426db..bbc9d24 100644 --- a/todo/AGENT.md +++ b/todo/AGENT.md @@ -7,10 +7,10 @@ Prefix the commands below with `node /todo/todo.mjs` unless they name `sdlc ## Select -Run `node /todo/todo.mjs next --json` and capture its exit code. +Run `next --json`; use its exit code. - `0`: work the returned item. -- `10`: stop and tell the human what the item waits for; let them decide in the TUI, web page or chat. +- `10`: stop and tell the human what the item waits for; they decide in the app or chat. - `20`: stop and report the returned error text. - `30`: stop; nothing remains to do. @@ -25,6 +25,7 @@ Use the returned `id` for mutations; a shared slug is ambiguous. Read `replies` from `next --json` and fold the human's answers into the artifact. Treat an answer as input, never approval; a changed artifact needs approval again. +While working an item, run `working ""` at least every 60 s; `working --off` when you stop. If the item has a project, `cd` there. In that project, if `.sdlc/` is absent, run `bash /sdlc.sh init` and configure it per SKILL.md. If no project is set and the work needs a repository, run `wait "which project?"` and stop. @@ -59,9 +60,9 @@ Leave web approvals to the human; only sdlc.sh records gate approval. ## Schedule the host -Let the host run the model proactively; the kit never runs a model. -Use one worker per list; there is no multi-agent lease. +The host runs the model, never the kit. +Use one worker per list. - Claude Code: `/loop 15m follow /todo/AGENT.md`. - cron/launchd: schedule `claude -p "follow /todo/AGENT.md"` or `codex exec "follow /todo/AGENT.md"`. -- Paseo: schedule an agent with the prompt `follow /todo/AGENT.md`. +- Paseo: schedule the prompt `follow /todo/AGENT.md`. diff --git a/todo/app/src/client.rs b/todo/app/src/client.rs index 410cd9e..66f7f98 100644 --- a/todo/app/src/client.rs +++ b/todo/app/src/client.rs @@ -39,6 +39,14 @@ pub struct Sdlc { pub action: String, } +/// An agent's live `working` marker: what it does, since when and its last heartbeat (ISO times). +#[derive(Clone, Default, Deserialize)] +pub struct Working { + #[serde(default)] + pub what: String, + pub since: String, +} + #[derive(Clone, Default, Deserialize)] pub struct Item { pub id: String, @@ -72,6 +80,9 @@ pub struct Item { /// Kept at the top of every tab (a setting switched with its choices); never counted as needing you. #[serde(default)] pub pin: bool, + /// Set while an agent works on it right now; the server drops it once the heartbeat expires. + #[serde(default)] + pub working: Option, pub version: String, pub turn: Turn, } diff --git a/todo/app/src/i18n.rs b/todo/app/src/i18n.rs index bb6cd7f..b8dc22a 100644 --- a/todo/app/src/i18n.rs +++ b/todo/app/src/i18n.rs @@ -27,7 +27,10 @@ pub fn t(lang: Lang, key: &str) -> &'static str { "status.approve-intent" => ("Approve scope", "범위 승인 필요"), "status.approve-plan" => ("Approve plan", "계획 승인 필요"), "status.answer" => ("Needs your answer", "답변 필요"), - "status.agent" => ("Agent working", "에이전트 진행 중"), + "status.agent" => ("Agent's turn", "에이전트 차례"), + "status.working" => ("Working now", "지금 작업 중"), + "working.minutes" => (" min", "분째"), + "working.justNow" => ("just started", "방금 시작"), "status.handoff" => ("Answered — not picked up yet", "답변 전달됨 — 에이전트 수신 전"), "status.new" => ("Not started", "시작 전"), "status.blocked" => ("Blocked — needs action", "막힘 — 조치 필요"), diff --git a/todo/app/src/main.rs b/todo/app/src/main.rs index 0fac39a..7d4722c 100644 --- a/todo/app/src/main.rs +++ b/todo/app/src/main.rs @@ -103,7 +103,35 @@ fn settle(focus: Option<&str>, at: usize, queue: &[&str]) -> Option { Some(focus.and_then(|id| queue.iter().position(|q| *q == id)).unwrap_or(at.min(queue.len() - 1))) } -fn status_label(lang: Lang, item: &Item) -> &'static str { +/// The tint of an item: its actor's, or its own while an agent works on it right now. +fn tint(item: &Item) -> &str { if item.turn.kind == "working" { "working" } else { &item.turn.actor } } + +/// Seconds since the Unix epoch of an ISO time such as `2026-11-12T03:04:05.678Z` (UTC, as the server writes it). +fn iso_seconds(iso: &str) -> Option { + let number = |range: std::ops::Range| iso.get(range)?.parse::().ok(); + let (y, m, d) = (number(0..4)?, number(5..7)?, number(8..10)?); + let (h, min, s) = (number(11..13)?, number(14..16)?, number(17..19)?); + // Days from the civil date (Howard Hinnant's algorithm). + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; + let days = era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468; + Some(days * 86400 + h * 3600 + min * 60 + s) +} + +/// "Working now · 12 min · build": how long an agent has worked on it and on what. +fn working_label(lang: Lang, since: &str, what: &str, now: i64) -> String { + let minutes = iso_seconds(since).map(|since| (now - since) / 60).unwrap_or(0); + let elapsed = if minutes >= 1 { format!("{minutes}{}", t(lang, "working.minutes")) } else { t(lang, "working.justNow").to_string() }; + [t(lang, "status.working"), &elapsed, what].iter().filter(|part| !part.is_empty()).copied().collect::>().join(" · ") +} + +fn status_label(lang: Lang, item: &Item) -> String { + if let ("working", Some(working)) = (item.turn.kind.as_str(), &item.working) { + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); + return working_label(lang, &working.since, &working.what, now); + } match item.turn.kind.as_str() { "approve-intent" => t(lang, "status.approve-intent"), "approve-plan" => t(lang, "status.approve-plan"), @@ -114,7 +142,7 @@ fn status_label(lang: Lang, item: &Item) -> &'static str { "others" => t(lang, "status.others"), "done" => t(lang, "status.done"), _ => t(lang, "status.new"), - } + }.to_string() } fn open_url(url: &str) { @@ -284,9 +312,20 @@ fn build_tray(lang: Lang) -> Result { fn pill(ui: &mut egui::Ui, text: &str, actor: &str, dark: bool) { let (fg, bg) = theme::tone(actor, dark); egui::Frame::new().fill(bg).corner_radius(CornerRadius::same(255)).inner_margin(Margin::symmetric(9, 3)) - .show(ui, |ui| ui.label(RichText::new(text).color(fg).size(11.5).strong())); + .show(ui, |ui| ui.horizontal(|ui| { + // Work in progress right now carries a pulsing dot, so it never reads as only an agent's turn. + if actor == "working" { + ui.spacing_mut().item_spacing.x = 5.0; + let (rect, _) = ui.allocate_exact_size(egui::vec2(7.0, 7.0), Sense::hover()); + ui.painter().circle_filled(rect.center(), 3.5, fg.gamma_multiply(pulse(ui))); + } + ui.label(RichText::new(text).color(fg).size(11.5).strong()); + })); } +/// The working dot's strength: full and faint by turns, a beat a second (the app repaints once a second while any item works). +fn pulse(ui: &egui::Ui) -> f32 { if (ui.input(|i| i.time) as i64) % 2 == 0 { 1.0 } else { 0.35 } } + fn primary(ui: &mut egui::Ui, p: &theme::Palette, text: &str, enabled: bool) -> egui::Response { ui.add_enabled(enabled, egui::Button::new(RichText::new(text).color(p.on_accent).strong()) .fill(p.accent).stroke(Stroke::NONE).corner_radius(CornerRadius::same(8)).min_size(egui::vec2(0.0, 30.0))) @@ -324,6 +363,8 @@ impl eframe::App for App { let attention = model.items.iter().filter(|i| needs_you(i)).count(); self.update_tray(attention); if toast.is_some() { ctx.request_repaint_after(Duration::from_millis(500)); } + // The working dots pulse and their minutes count up; nothing repaints on a timer while no agent works. + if model.items.iter().any(|i| !i.done && i.turn.kind == "working") { ctx.request_repaint_after(Duration::from_secs(1)); } // The keyboard zoom (Cmd/Ctrl with + and -) is kept like the settings card's. let zoom = ctx.zoom_factor().clamp(prefs::ZOOM.0, prefs::ZOOM.1); // The keys have no limit of their own; hold the real zoom to the range the saved one keeps. @@ -559,7 +600,7 @@ impl App { egui::CollapsingHeader::new(RichText::new(title).color(p.muted).size(12.5)).id_salt("queue").show(ui, |ui| { for (i, other) in queue.iter().enumerate().filter(|(i, _)| *i != at) { let color = theme::tone(if must_decide(other) { &other.turn.actor } else { "" }, dark).0; - if line(ui, p, color, other, status_label(lang, other)) { go = i; } + if line(ui, p, color, other, &status_label(lang, other)) { go = i; } } }); } @@ -573,11 +614,11 @@ impl App { let mut clicked = false; theme::row(p).show(ui, |ui| { ui.set_width(ui.available_width()); - clicked = line(ui, p, theme::tone(&item.turn.actor, dark).0, item, status_label(lang, item)); + clicked = line(ui, p, theme::tone(tint(item), dark).0, item, &status_label(lang, item)); if self.open.contains(&item.id) && !needs_you(item) { ui.add_space(2.0); ui.horizontal_wrapped(|ui| { - pill(ui, status_label(lang, item), &item.turn.actor, dark); + pill(ui, &status_label(lang, item), tint(item), dark); ui.label(RichText::new(meta_of(item)).color(p.muted).size(12.0)); }); self.details(ui, ctx, p, item, busy, artifact, Part::Both); @@ -887,7 +928,7 @@ fn heading(ui: &mut egui::Ui, p: &theme::Palette, dark: bool, lang: Lang, item: ui.with_layout(Layout::right_to_left(Align::Center), |ui| match item.turn.kind.as_str() { "answer" if must_decide(item) => pill(ui, t(lang, "decide.yours"), "you", dark), "answer" => pill(ui, t(lang, "decide.suggested"), "", dark), - _ => pill(ui, status_label(lang, item), &item.turn.actor, dark), + _ => pill(ui, &status_label(lang, item), tint(item), dark), }); }); ui.add(egui::Label::new(RichText::new(&item.title).size(19.0).strong().line_height(Some(27.0))).wrap()); @@ -910,6 +951,7 @@ fn line(ui: &mut egui::Ui, p: &theme::Palette, color: Color32, item: &Item, hint let row = ui.horizontal(|ui| { let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover()); ui.painter().circle_filled(rect.center(), 4.0, color); + if item.turn.kind == "working" { ui.painter().circle_stroke(rect.center(), 6.0, Stroke::new(1.5, color.gamma_multiply(pulse(ui) - 0.3))); } ui.add(egui::Label::new(RichText::new(&item.title).color(p.text).size(13.5)).truncate().selectable(false)); }).response; // The whole width answers the click, not only the text. @@ -1116,6 +1158,18 @@ mod tests { assert_eq!(untag("Today the key opens every file (AS-IS): too wide.".into()), "Today the key opens every file (AS-IS): too wide."); } + #[test] + fn working_shows_minutes_and_what_from_the_iso_start() { + assert_eq!(iso_seconds("1970-01-02T00:00:01.000Z"), Some(86401)); + assert_eq!(iso_seconds("2026-11-12T03:04:05.678Z"), Some(1794452645)); + let since = "2026-11-12T03:00:00.000Z"; + let start = iso_seconds(since).unwrap(); + assert_eq!(working_label(Lang::Ko, since, "build", start + 12 * 60 + 30), "지금 작업 중 · 12분째 · build"); + assert_eq!(working_label(Lang::En, since, "", start + 20), "Working now · just started"); + assert_eq!(tint(&item("w", "agent", "working")), "working"); + assert_eq!(tint(&item("a", "agent", "agent")), "agent"); + } + #[test] fn focus_follows_the_decision_then_takes_the_next_one() { assert_eq!(settle(None, 0, &[]), None); diff --git a/todo/app/src/theme.rs b/todo/app/src/theme.rs index 31d6ef1..ef953bc 100644 --- a/todo/app/src/theme.rs +++ b/todo/app/src/theme.rs @@ -30,6 +30,8 @@ pub fn tone(actor: &str, dark: bool) -> (Color32, Color32) { let (fg, bg_light, bg_dark) = match actor { "you" => (0xd97706, 0xfef3c7, 0x3a2a0c), "agent" => (0x2f6fed, 0xdde8ff, 0x16233f), + // An agent working on it right now, apart from an agent's turn nobody holds. + "working" => (0x0a7a52, 0xe3f6ee, 0x123227), "blocked" => (0xdc2626, 0xfee2e2, 0x3d1616), _ => (0x6b7280, 0xececf0, 0x26262b), }; diff --git a/todo/core.mjs b/todo/core.mjs index 9999c56..7c2ccb8 100644 --- a/todo/core.mjs +++ b/todo/core.mjs @@ -214,10 +214,11 @@ function normalize(model) { identify(model); } const lockLost = Symbol('lock ownership lost'); -async function atomicWrite(file, text, owns = () => true) { +async function atomicWrite(file, text, owns = () => true, mode) { const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomUUID()}.tmp`); try { - fs.writeFileSync(temp, text, 'utf8'); + fs.writeFileSync(temp, text, { encoding: 'utf8', mode }); + if (mode !== undefined) fs.chmodSync(temp, mode); for (let attempt = 0; ; attempt++) { try { if (!owns()) throw lockLost; fs.renameSync(temp, file); break; } catch (error) { if (!['EPERM', 'EBUSY'].includes(error.code) || attempt >= 5) throw error; await pause(20 * (attempt + 1)); } @@ -612,3 +613,56 @@ export function watch(file, onChange) { fs.watchFile(file, { interval: 250 }, listener); return () => fs.unwatchFile(file, listener); } + +// Which items an agent works on right now: todo-working.json beside todo.md, { id: { what, since, beat } } in ISO +// times. A heartbeat refreshes `beat` every minute; writing todo.md that often would fill its history, contend +// for its lock and reload every view. A marker counts only while its beat is younger than the TTL, so the +// marker of a worker that died vanishes by itself. +export const WORKING_TTL_MS = 180000; +export const workingPath = (file = todoPath()) => path.join(path.dirname(file), 'todo-working.json'); +// SDLC_TODO_WORKING_TTL (seconds) shortens the TTL, for tests. +export const workingTtl = () => Number(process.env.SDLC_TODO_WORKING_TTL) > 0 ? Number(process.env.SDLC_TODO_WORKING_TTL) * 1000 : WORKING_TTL_MS; +const liveMark = (mark, now, ttl) => !!mark && typeof mark === 'object' && typeof mark.since === 'string' && + typeof mark.beat === 'string' && now - Date.parse(mark.beat) < ttl; +// Live markers only; a missing or unreadable file is no marker. +export function readWorking(file = todoPath(), now = Date.now()) { + let marks; + try { marks = JSON.parse(fs.readFileSync(workingPath(file), 'utf8')); } catch { return {}; } + if (!marks || typeof marks !== 'object' || Array.isArray(marks)) return {}; + const ttl = workingTtl(); + return Object.fromEntries(Object.entries(marks).filter(([, mark]) => liveMark(mark, now, ttl)) + .map(([id, mark]) => [id, { what: typeof mark.what === 'string' ? mark.what : '', since: mark.since, beat: mark.beat }])); +} +// Items as every view shows them: `working` is the live marker of an open item, else null. +export function withWorking(items, file = todoPath(), now = Date.now()) { + const live = readWorking(file, now); + return items.map(item => ({ ...item, working: !item.done && live[item.id] || null })); +} +// Mark or refresh (`what` undefined keeps the label), or clear with off. No sync and no todo.md write: a heartbeat +// calls it every minute. Two writers at once can lose one update; the next beat restores it. +export async function working(file, id, what, { off = false, now = new Date() } = {}) { + const item = findItem(load(file), id); + if (item.done && !off) fail(`item is done: ${id}`, 1); + const label = what === undefined ? undefined : line(what); + if (label?.length > 80) fail('working text must be 80 characters or fewer'); + const marks = readWorking(file, now.getTime()), previous = marks[item.id]; + if (off) delete marks[item.id]; + else marks[item.id] = { what: label ?? previous?.what ?? '', since: previous?.since ?? now.toISOString(), beat: now.toISOString() }; + await atomicWrite(workingPath(file), `${JSON.stringify(marks)}\n`, () => true, 0o600); + return marks[item.id] || null; +} +// Calls onChange when a marker is written and when the oldest live one expires, so a marker nobody refreshes +// leaves every view within the TTL without any write. +export function watchWorking(file, onChange) { + let timer; + const arm = () => { + clearTimeout(timer); + const beats = Object.values(readWorking(file)).map(mark => Date.parse(mark.beat)); + if (!beats.length) return; + timer = setTimeout(() => { onChange(); arm(); }, Math.max(0, Math.min(...beats) + workingTtl() - Date.now()) + 50); + timer.unref?.(); + }; + const stop = watch(workingPath(file), () => { onChange(); arm(); }); + arm(); + return () => { clearTimeout(timer); stop(); }; +} diff --git a/todo/locales/en.mjs b/todo/locales/en.mjs index 597ac0d..c10a72d 100644 --- a/todo/locales/en.mjs +++ b/todo/locales/en.mjs @@ -13,7 +13,10 @@ export default { 'status.approve-intent': 'Approve intent', 'status.approve-plan': 'Approve plan', 'status.answer': 'Answer needed', - 'status.agent': 'Agent working', + 'status.agent': "Agent's turn", + 'status.working': 'Working now', + 'working.minutes': '{count} min', + 'working.justNow': 'just started', 'status.handoff': 'Answered — no agent has picked it up yet', 'status.new': 'Not started', 'status.blocked': 'Blocked — fix needed', @@ -186,7 +189,7 @@ export default { 'tui.help.back': 'Back / cancel', 'tui.help.input': 'Input: ← → Home End Backspace · Ctrl+U clear', 'tui.help.submit': 'Enter submits · empty input cancels', - 'tui.help.legend': '● your turn · ◐ agent working · ◌ answered, not picked up · ○ not started · ✕ blocked · ✓ done', + 'tui.help.legend': '● your turn · ◉ working now · ◐ agent’s turn · ◌ answered, not picked up · ○ not started · ✕ blocked · ✓ done', 'tui.help.stop': 'Agents work Open items top-down and stop at the first ● or ✕.', 'tui.help.decide': 'Replies record your words; approve in the browser (w).', 'tui.help.scroll': 'Details/help: ↑ ↓ j k / PgUp PgDn scroll · g G', diff --git a/todo/locales/ko.mjs b/todo/locales/ko.mjs index d8b5193..f66d47e 100644 --- a/todo/locales/ko.mjs +++ b/todo/locales/ko.mjs @@ -12,7 +12,10 @@ export default { 'status.approve-intent': '범위 승인 필요', 'status.approve-plan': '계획 승인 필요', 'status.answer': '답변 필요', - 'status.agent': '에이전트 진행 중', + 'status.agent': '에이전트 차례', + 'status.working': '지금 작업 중', + 'working.minutes': '{count}분째', + 'working.justNow': '방금 시작', 'status.handoff': '답변 전달됨 — 에이전트 수신 전', 'status.new': '시작 전', 'status.blocked': '막힘 — 조치 필요', @@ -183,7 +186,7 @@ export default { 'tui.help.back': '뒤로 / 취소', 'tui.help.input': '입력: ← → Home End Backspace · Ctrl+U 지우기', 'tui.help.submit': 'Enter로 확인 · 빈 입력은 취소', - 'tui.help.legend': '● 내 차례 · ◐ 에이전트 진행 중 · ◌ 답변 전달됨(수신 전) · ○ 시작 전 · ✕ 막힘 · ✓ 완료', + 'tui.help.legend': '● 내 차례 · ◉ 지금 작업 중 · ◐ 에이전트 차례 · ◌ 답변 전달됨(수신 전) · ○ 시작 전 · ✕ 막힘 · ✓ 완료', 'tui.help.stop': '에이전트는 열린 항목을 위에서부터 처리하고 첫 ● 또는 ✕에서 멈춥니다.', 'tui.help.decide': '답변은 내 말을 기록할 뿐이며, 승인은 브라우저(w)에서 합니다.', 'tui.help.scroll': '자세히/도움말: ↑ ↓ j k / PgUp PgDn 스크롤 · g G', diff --git a/todo/page/app.css b/todo/page/app.css index efeaed9..4e2fe30 100644 --- a/todo/page/app.css +++ b/todo/page/app.css @@ -16,6 +16,8 @@ --busy-bg: #e6f0fb; --ok: #1e6b34; --ok-bg: #e6f4ea; + --live: #0a7a52; + --live-bg: #e3f6ee; --open-bg: #f2f2f7; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Apple SD Gothic Neo", system-ui, sans-serif; font-size: 100%; @@ -40,6 +42,8 @@ --busy-bg: #1a2838; --ok: #7fd796; --ok-bg: #1b3022; + --live: #6ee7b7; + --live-bg: #123227; --open-bg: #2c2c2e; } } @@ -162,6 +166,12 @@ a.chip { display: inline-block; min-height: 44px; min-width: 44px; line-height: .badge.ok { color: var(--ok); background: var(--ok-bg); } .badge.open { color: var(--muted); background: var(--open-bg); } .badge.blocked { background: var(--bad-bg); } +/* An agent works on it now: green, with a dot that pulses so it never reads as only an agent's turn. */ +.badge.working { color: var(--live); background: var(--live-bg); gap: 0.4rem; } +.badge.working::before { content: ""; width: 0.5rem; height: 0.5rem; border-radius: 50%; background: var(--live); animation: working 1.4s ease-in-out infinite; } +@keyframes working { 50% { opacity: 0.25; transform: scale(0.7); } } +.row[data-tone="working"] { box-shadow: inset 3px 0 0 var(--live); } +.row[data-tone="working"] .check::before { border-color: var(--live); } .row[data-tone="wait"] { box-shadow: inset 3px 0 0 var(--accent); } .row[data-tone="blocked"] { box-shadow: inset 3px 0 0 var(--bad); } .row[data-tone="busy"] { box-shadow: inset 3px 0 0 var(--busy); } diff --git a/todo/page/app.js b/todo/page/app.js index 8431a95..6d3f5ff 100644 --- a/todo/page/app.js +++ b/todo/page/app.js @@ -1,6 +1,6 @@ // To-do page. Rows are patched by id so drafts, focus and scroll survive live updates. import { defaultLanguage, isLanguage, languages, locales, phaseLabel, translator } from './i18n.mjs'; -import { countsOf, queueOf, statusOf, ticketGroups } from './status.mjs'; +import { countsOf, queueOf, statusLabel, statusOf, ticketGroups } from './status.mjs'; const $ = id => document.getElementById(id); const el = (tag, className, text) => { const node = document.createElement(tag); @@ -108,10 +108,11 @@ function whatWaits(item) { const status = statusOf(item); return item.waiting || (status.gate ? t(`next.${status.kind}`) : item.sdlc?.action || t(`next.${status.kind}`)); } -// Colour tone of a status pill, row bar and check ring: amber you, blue agent, grey not started or not picked up. +// Colour tone of a status pill, row bar and check ring: amber you, blue agent's turn, green with a pulsing dot +// while an agent works on it now, grey not started or not picked up. const tones = { you: 'wait', agent: 'busy', others: 'open', blocked: 'blocked', done: 'ok' }; -const toneOf = status => ['new', 'handoff'].includes(status.kind) ? 'open' : tones[status.actor]; -const pill = item => { const status = statusOf(item); return chip(t(`status.${status.kind}`), `badge ${toneOf(status)}`); }; +const toneOf = status => status.kind === 'working' ? 'working' : ['new', 'handoff'].includes(status.kind) ? 'open' : tones[status.actor]; +const pill = item => { const status = statusOf(item); return chip(statusLabel(t, item), `badge ${toneOf(status)}`); }; function doneAt(item) { const last = [...item.events].reverse().find(e => /^(done|DONE)\b/.test(e.what)); return last ? last.at : ''; @@ -221,7 +222,7 @@ function updateRow(li, item) { li.dataset.tone = toneOf(status); const queued = queue.queued.has(item.id) ? queue.stop.status === 'blocked' ? 'row.queuedFix' : 'row.queued' : ''; // Rebuild the small info line only when it changed, so a focused link keeps focus. - const sig = JSON.stringify([lang, status.kind, queued, item.project, item.repos, item.link, item.sdlc?.phase, item.error, item.sdlc?.action, item.others, item.done]); + const sig = JSON.stringify([lang, statusLabel(t, item), queued, item.project, item.repos, item.link, item.sdlc?.phase, item.error, item.sdlc?.action, item.others, item.done]); if (sig === r.sig) return; r.sig = sig; const parts = []; diff --git a/todo/status.mjs b/todo/status.mjs index 23e2a1e..3c12530 100644 --- a/todo/status.mjs +++ b/todo/status.mjs @@ -7,10 +7,21 @@ export function statusOf(item) { if (item.status === 'waiting') { const gate = gateOf(item); return { actor: 'you', kind: gate ? `approve-${gate}` : 'answer', gate }; } // Someone else (a planner, QA) answers first; it is neither your turn nor an agent's. if (item.status === 'others') return { actor: 'others', kind: 'others' }; + // An agent marked it with `working` and still beats. Blocked, waiting and others win above: a turn that is + // yours or someone else's is not hidden by a heartbeat. Loaders attach only live markers (core.withWorking). + if (item.working) return { actor: 'agent', kind: 'working' }; // A reply stays unread until an agent takes it with next or take; nobody is working on it yet. if (item.unread) return { actor: 'agent', kind: 'handoff' }; return { actor: 'agent', kind: item.sdlc ? 'agent' : 'new' }; } +// The status words, with how long an agent has been working and on what: "Working now · 12 min · build". +export function statusLabel(t, item, now = Date.now()) { + const { kind } = statusOf(item), label = t(`status.${kind}`); + if (kind !== 'working') return label; + const minutes = Math.floor((now - Date.parse(item.working.since)) / 60000); + const elapsed = minutes >= 1 ? t('working.minutes', { count: minutes }) : t('working.justNow'); + return [label, elapsed, item.working.what].filter(Boolean).join(' · '); +} // Agents work Open items top-down and stop at the first one that is your turn or blocked. export function queueOf(items) { const open = items.filter(item => !item.done); diff --git a/todo/todo.mjs b/todo/todo.mjs index 3aa98e6..4559cf3 100644 --- a/todo/todo.mjs +++ b/todo/todo.mjs @@ -20,6 +20,7 @@ const usage = `Usage: node ${path.join(kit, 'todo', 'todo.mjs')} pin [on|off] (keep at the top of every app tab, e.g. a setting switched with choices; not counted as needing you) run ["command"] (a command the human runs; the app opens a terminal with it typed, not run; a reply or no text clears it) suggest ["answer"] (the one-line reply you recommend, pre-filled in the human's reply field; a reply or no text clears it) + working ["what"] | working --off (an agent works on it now: call on start, again at least every 60 s, --off when done; a mark not refreshed for 3 min expires) done ["result"] | web [--port N] [--open] [--lang L] | serve [--lang L] | help No command: the app (--ui tui,web,app picks any of them; --no-web for the TUI alone, --lang L). Without a built app it opens the TUI with its web link; build it with: cargo build --release --manifest-path ${path.join(kit, 'todo', 'app', 'Cargo.toml')} @@ -29,7 +30,7 @@ const bad = message => { throw Object.assign(new Error(`${message}\n${usage}`), const schemas = { add: { project: true, link: true, slug: true, by: true, brief: true }, next: { json: false }, take: { json: false }, list: { json: false }, sync: {}, - start: { slug: true, phase: true }, phase: {}, wait: {}, others: {}, resume: {}, answer: {}, note: {}, brief: {}, repos: {}, choices: { pick: true }, suggest: {}, run: {}, pin: {}, done: {}, + start: { slug: true, phase: true }, phase: {}, wait: {}, others: {}, resume: {}, answer: {}, note: {}, brief: {}, repos: {}, choices: { pick: true }, suggest: {}, run: {}, pin: {}, working: { off: false }, done: {}, web: { port: true, open: false, lang: true }, serve: { lang: true }, help: {}, '': { 'no-web': false, lang: true, ui: true } }; function argumentsFor(argv) { @@ -48,10 +49,10 @@ function argumentsFor(argv) { } return { command, flags, args }; } -function summary(item) { +function summary(item, live = core.readWorking(file)) { return { id: item.id, title: item.title, project: item.project, link: item.link, slug: item.sdlc?.slug || null, phase: item.sdlc?.phase || null, state: item.sdlc?.state || null, - action: item.sdlc?.action || '', waiting: item.waiting, asked: core.asked(item), others: item.others || '', brief: item.brief || '', repos: item.repos || [], choices: item.choices || [], pick: item.pick ?? null, suggest: item.suggest || '', run: item.run || '', pin: !!item.pin, replies: item.replies || core.replies(item), unread: item.unread || 0, fix: !!item.fixRequested, status: item.status }; + action: item.sdlc?.action || '', waiting: item.waiting, asked: core.asked(item), others: item.others || '', brief: item.brief || '', repos: item.repos || [], choices: item.choices || [], pick: item.pick ?? null, suggest: item.suggest || '', run: item.run || '', pin: !!item.pin, replies: item.replies || core.replies(item), unread: item.unread || 0, fix: !!item.fixRequested, status: item.status, working: !item.done && live[item.id] || null }; } const uiNames = ['tui', 'web', 'app']; const appPath = () => process.env.SDLC_TODO_APP || path.join(kit, 'todo', 'app', 'target', 'release', process.platform === 'win32' ? 'sdlc-todo.exe' : 'sdlc-todo'); @@ -143,7 +144,8 @@ async function main() { case 'list': { arity(0); const model = await core.sync(file, { kit }); - if (flags.json) console.log(JSON.stringify(model.items.map(summary))); + const live = core.readWorking(file); + if (flags.json) console.log(JSON.stringify(model.items.map(item => summary(item, live)))); else for (const item of model.items) console.log(`${item.id} [${item.status}] ${item.title}`); return; } @@ -171,6 +173,9 @@ async function main() { case 'suggest': arity(1, 2); await core.suggest(file, args[0], args[1] || ''); return; case 'run': arity(1, 2); await core.run(file, args[0], args[1] || ''); return; case 'pin': arity(1, 2); await core.pin(file, args[0], args[1] || 'on'); return; + case 'working': + arity(1, flags.off ? 1 : 2); + await core.working(file, args[0], args[1], { off: !!flags.off }); return; case 'resume': arity(1, 2); await core.resume(file, ...args); return; } } diff --git a/todo/tui.mjs b/todo/tui.mjs index fc35dfc..c3d5644 100644 --- a/todo/tui.mjs +++ b/todo/tui.mjs @@ -2,7 +2,7 @@ import { emitKeypressEvents } from 'node:readline'; import { spawn } from 'node:child_process'; import * as core from './core.mjs'; import { defaultLanguage, locales, nextLanguage, phaseLabel, translator } from './i18n.mjs'; -import { countsOf, queueOf, statusOf } from './status.mjs'; +import { countsOf, queueOf, statusLabel, statusOf } from './status.mjs'; const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' }); const chars = text => [...segmenter.segment(String(text))].map(part => part.segment); @@ -53,10 +53,11 @@ const textOf = state => translator(state.lang || defaultLanguage); // What the human is asked to do: the explicit wait, else the sdlc action, else the generic step. const waitText = (item, t) => item.waiting || item.sdlc?.action || t(`next.${statusOf(item).kind}`); const doneTime = item => [...(item.events || [])].reverse().find(e => /^(done|DONE)(?:$| —)/.test(e.what))?.at || ''; -const looks = { done: ['✓', '2;33'], blocked: ['✕', '31'], you: ['●', '33'], agent: ['◐', '36'], others: ['◇', '2'], handoff: ['◌', '36'], new: ['○', ''] }; +// An agent working right now gets its own bold green mark; an agent's turn with nobody on it stays ◐. +const looks = { done: ['✓', '2;33'], blocked: ['✕', '31'], you: ['●', '33'], agent: ['◐', '36'], others: ['◇', '2'], handoff: ['◌', '36'], new: ['○', ''], working: ['◉', '1;32'] }; function status(item, t) { const { actor, kind } = statusOf(item); - return [...looks[['new', 'handoff'].includes(kind) ? kind : actor], t(`status.${kind}`)]; + return [...looks[['new', 'handoff', 'working'].includes(kind) ? kind : actor], statusLabel(t, item)]; } const webText = (state, t) => state.webUrl || (state.webError ? t('tui.webOffBecause', { reason: state.webError }) : t('tui.webOff')); function detailLines(item, t) { @@ -126,6 +127,7 @@ export function render(state, { width = 80, height = 24, color = false } = {}) { let row = paint(`${active ? '›' : ' '} `, active ? '33' : '') + paint(`${glyph} ${title}`, current.done ? '2;33;9' : code); if (showMeta) row += ' '.repeat(Math.max(2, width - widthOf(prefix + title) - widthOf(meta))) + paint(meta, '2'); rows.push(row); + if (statusOf(current).kind === 'working') rows.push(paint(clip(` ${label}`, width), code)); if (current === stop) rows.push(paint(clip(` ${t(`stop.${statusOf(current).actor}`)}`, width), code)); if (waiting(current)) rows.push(paint(clip(` ${waitText(current, t)} · ${t('tui.decideInBrowser')}`, width), '2')); if (choicesOf(current).length) rows.push(paint(clip(` ${choiceText(current, t)}`, width), '2')); @@ -262,7 +264,7 @@ export async function runTui({ file, kit, web, lang = defaultLanguage }) { if (!input.isTTY || !output.isTTY || !input.setRawMode) throw new Error('A terminal is required for the TUI'); const readItems = () => { const model = core.load(file); - return model.items.map(item => ({ ...item, version: core.itemVersion(item, model) })); + return core.withWorking(model.items, file).map((item, i) => ({ ...item, version: core.itemVersion(model.items[i], model) })); }; let state = { items: readItems(), file, selected: 0, view: 'list', lang }; const t = (key, vars) => textOf(state)(key, vars); @@ -407,7 +409,8 @@ export async function runTui({ file, kit, web, lang = defaultLanguage }) { if (stopped) { if (failure) throw failure; return; } state.items = readItems(); ready = true; emitKeypressEvents(input); input.on('keypress', keypress); input.resume(); - stopWatch = core.watch(file, refresh); draw(); + const stopFile = core.watch(file, refresh), stopWorking = core.watchWorking(file, refresh); + stopWatch = () => { stopFile(); stopWorking(); }; draw(); if (typeof web === 'string') { state.webUrl = web; draw(); } else if (web) webStart = import('./web.mjs').then(({ startWeb }) => startWeb({ file, kit, port: 0, open: false, lang, onUrl: url => { state.webUrl = url; draw(); } })) diff --git a/todo/web.mjs b/todo/web.mjs index 0165d7c..5414f44 100644 --- a/todo/web.mjs +++ b/todo/web.mjs @@ -146,7 +146,8 @@ export async function startWeb({ file = core.todoPath(), kit = defaultKit, port const clients = new Set(); const payload = () => { const model = core.load(file); - return { items: model.items.map(item => ({ ...item, version: core.itemVersion(item, model), turn: statusOf(item) })), file, lang }; + // The version hashes the item as loaded; the working marker is not part of it. + return { items: core.withWorking(model.items, file).map((item, i) => ({ ...item, version: core.itemVersion(model.items[i], model), turn: statusOf(item) })), file, lang }; }; const sendEvent = (res, value, event = '') => res.write(`${event ? `event: ${event}\n` : ''}data: ${JSON.stringify(value)}\n\n`); const broadcast = () => { @@ -260,13 +261,13 @@ export async function startWeb({ file = core.todoPath(), kit = defaultKit, port }); actualPort = server.address().port; // Watching only loads the file: sync writes it, so syncing in the watcher would loop. - const stopWatch = core.watch(file, broadcast); + const stopWatch = core.watch(file, broadcast), stopWorking = core.watchWorking(file, broadcast); const keepalive = setInterval(() => { for (const res of clients) res.write(': keepalive\n\n'); }, 15000); keepalive.unref(); let closing; const close = () => { if (!closing) { - stopWatch(); + stopWatch(); stopWorking(); clearInterval(keepalive); if (session && readSession(session)?.token === token) fs.rmSync(session, { force: true }); for (const res of clients) res.end(); From 933de7a93abe69ad043318e6b292a3274e077de0 Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:03:35 +0900 Subject: [PATCH 2/3] =?UTF-8?q?fix(todo):=20working=20=ED=91=9C=EC=8B=9C?= =?UTF-8?q?=EA=B0=80=20id=20=EB=B3=80=EA=B2=BD=EC=9D=84=20=EB=94=B0?= =?UTF-8?q?=EB=9D=BC=EA=B0=80=EA=B3=A0=20=EB=AF=B8=EB=9E=98=20=EC=8B=AC?= =?UTF-8?q?=EB=B0=95=C2=B7=EA=B8=B4=20=ED=83=80=EC=9D=B4=EB=A8=B8=C2=B7?= =?UTF-8?q?=EC=83=81=EC=84=B8=20=EC=9E=AC=EA=B5=AC=EC=84=B1=EC=9D=84=20?= =?UTF-8?q?=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit start --slug나 제목 변경으로 id가 바뀌면 mutate가 살아 있는 표시를 새 id로 옮긴다(외부 core.update 호출 포함). 5초 넘게 앞선 beat는 살아 있지 않고, 만료 타이머는 2^31-1ms로 묶는다. 웹 상세는 beat만 바뀌면 다시 만들지 않고 상태 글자만 갱신한다. --- tests/todo.test.mjs | 30 ++++++++++++++++++++++++++++++ todo/core.mjs | 22 ++++++++++++++++++++-- todo/page/app.js | 10 ++++++---- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/tests/todo.test.mjs b/tests/todo.test.mjs index 4920c38..bc2b038 100644 --- a/tests/todo.test.mjs +++ b/tests/todo.test.mjs @@ -305,6 +305,36 @@ test('working: CLI marks, refreshes and clears an item beside todo.md; statusOf assert.equal(listed.find(item => item.id === b.id).working, null, 'an expired heartbeat is no marker'); }); +test('working: a marker follows its item when start --slug or a retitle changes the id; a future beat is not live', async t => { + const { root, file } = scratch(t); + const where = join(root, 'todo-working.json'); + const old = checkCode(await cli(file, ['add', 'Build it']), 0).stdout.trim(); + checkCode(await cli(file, ['working', old, 'build']), 0); + const mark = JSON.parse(readFileSync(where, 'utf8'))[old]; + checkCode(await cli(file, ['start', old, '--slug', 'foo-bar']), 0); + let [item] = JSON.parse(checkCode(await cli(file, ['list', '--json']), 0).stdout); + assert.notEqual(item.id, old, 'a slug changes the id'); + assert.deepEqual(item.working, mark, 'the marker moved with the item'); + assert.deepEqual(Object.keys(JSON.parse(readFileSync(where, 'utf8'))), [item.id], 'no orphan under the old id'); + checkCode(await cli(file, ['working', 'foo-bar']), 0); + const refreshed = JSON.parse(readFileSync(where, 'utf8'))[item.id]; + assert.deepEqual([refreshed.what, refreshed.since], ['build', mark.since], 'the slug refreshes the same marker'); + // An outside caller of core.update (the factory retitles this way) is covered too. + const plain = await core.add(file, 'Plain title'); + await core.working(file, plain.id, 'QA'); + await core.update(file, plain.id, current => { current.title = 'Renamed title'; }); + const renamed = core.load(file).items.find(other => other.title === 'Renamed title'); + assert.equal(core.withWorking([renamed], file)[0].working?.what, 'QA'); + assert.equal(core.readWorking(file)[plain.id], undefined); + // A beat far in the future (a wrong clock, a hand edit) never expires, so it does not count. + const future = new Date(Date.now() + 60000).toISOString(); + writeFileSync(where, JSON.stringify({ [item.id]: { what: 'x', since: future, beat: future } })); + assert.equal(core.withWorking(core.load(file).items, file).find(other => other.id === item.id).working, null); + const soon = new Date(Date.now() + 2000).toISOString(); + writeFileSync(where, JSON.stringify({ [item.id]: { what: 'x', since: soon, beat: soon } })); + assert.equal(core.readWorking(file)[item.id]?.what, 'x', 'a few seconds of clock skew still counts'); +}); + test('others: an agent waiting on someone else outranks an sdlc NEEDS-HUMAN; its own wait and a reply still win', t => { const { file } = scratch(t); const status = text => { writeFileSync(file, text); return core.load(file).items[0].status; }; diff --git a/todo/core.mjs b/todo/core.mjs index 7c2ccb8..dfef9b5 100644 --- a/todo/core.mjs +++ b/todo/core.mjs @@ -331,6 +331,7 @@ export async function mutate(file, fn, onSaved) { if (!owns()) throw lockLost; const model = load(file); normalize(model); + const before = new Map(model.items.map(item => [item, item.id])); const result = await fn(model); if (heartbeatError) throw heartbeatError; return await committing(lock, owner, async () => { @@ -345,6 +346,7 @@ export async function mutate(file, fn, onSaved) { model.items = model.items.filter(item => !overflow.includes(item)); } await atomicWrite(file, serialize(model), owns); + await followIds(file, before, model); // Observe the persisted postimage before releasing the original mutation lock. onSaved?.(model, result); return result; @@ -622,8 +624,9 @@ export const WORKING_TTL_MS = 180000; export const workingPath = (file = todoPath()) => path.join(path.dirname(file), 'todo-working.json'); // SDLC_TODO_WORKING_TTL (seconds) shortens the TTL, for tests. export const workingTtl = () => Number(process.env.SDLC_TODO_WORKING_TTL) > 0 ? Number(process.env.SDLC_TODO_WORKING_TTL) * 1000 : WORKING_TTL_MS; +// A beat more than 5 s ahead (a wrong clock or a hand edit) is not live: it would otherwise never expire. const liveMark = (mark, now, ttl) => !!mark && typeof mark === 'object' && typeof mark.since === 'string' && - typeof mark.beat === 'string' && now - Date.parse(mark.beat) < ttl; + typeof mark.beat === 'string' && now - Date.parse(mark.beat) < ttl && Date.parse(mark.beat) <= now + 5000; // Live markers only; a missing or unreadable file is no marker. export function readWorking(file = todoPath(), now = Date.now()) { let marks; @@ -638,6 +641,20 @@ export function withWorking(items, file = todoPath(), now = Date.now()) { const live = readWorking(file, now); return items.map(item => ({ ...item, working: !item.done && live[item.id] || null })); } +// An id follows the slug or title: a mutation that changes it (start --slug, a retitle, a renumbered duplicate) +// moves the item's live marker to the new id, so the work shown does not vanish and the next beat finds it. +async function followIds(file, before, model) { + const moved = model.items.filter(item => before.has(item) && before.get(item) !== item.id); + if (!moved.length) return; + const marks = readWorking(file); + // A new id is this item's alone now: a marker already under it belonged to an item that left it. + if (!moved.some(item => marks[before.get(item)] || marks[item.id])) return; + const carried = moved.map(item => [item.id, marks[before.get(item)]]); + for (const item of moved) delete marks[before.get(item)]; + for (const [id, mark] of carried) if (mark) marks[id] = mark; else delete marks[id]; + await atomicWrite(workingPath(file), `${JSON.stringify(marks)} +`, () => true, 0o600); +} // Mark or refresh (`what` undefined keeps the label), or clear with off. No sync and no todo.md write: a heartbeat // calls it every minute. Two writers at once can lose one update; the next beat restores it. export async function working(file, id, what, { off = false, now = new Date() } = {}) { @@ -659,7 +676,8 @@ export function watchWorking(file, onChange) { clearTimeout(timer); const beats = Object.values(readWorking(file)).map(mark => Date.parse(mark.beat)); if (!beats.length) return; - timer = setTimeout(() => { onChange(); arm(); }, Math.max(0, Math.min(...beats) + workingTtl() - Date.now()) + 50); + // setTimeout fires at once for a delay over 2^31-1 ms; a TTL override that long must not spin. + timer = setTimeout(() => { onChange(); arm(); }, Math.min(Math.max(0, Math.min(...beats) + workingTtl() - Date.now()) + 50, 2 ** 31 - 1)); timer.unref?.(); }; const stop = watch(workingPath(file), () => { onChange(); arm(); }); diff --git a/todo/page/app.js b/todo/page/app.js index 6d3f5ff..3d5f8e1 100644 --- a/todo/page/app.js +++ b/todo/page/app.js @@ -490,7 +490,7 @@ const dialog = $('detail'); const wideQuery = matchMedia('(min-width: 1100px)'); let isWide = wideQuery.matches, quietClose = false; // detailId is what the dialog shows ('' when closed); selectedId is the row chosen for the pane. -let detailId = '', selectedId = '', opener = null, artifact = null, artifactRequest = 0, detailVersion = ''; +let detailId = '', selectedId = '', opener = null, artifact = null, artifactRequest = 0, detailVersion = '', detailPill = null; function draftFor(id) { if (!drafts.has(id)) drafts.set(id, { reply: '', words: '', seed: '' }); return drafts.get(id); } // The agent's suggested answer fills the reply field until the person edits it; a new suggestion replaces an unedited one. @@ -591,8 +591,9 @@ function field(dl, name, value) { } function renderDetail() { const item = items.find(i => i.id === detailId); - const version = JSON.stringify(item); - if (version === detailVersion) return; + // A heartbeat only moves working.beat: refresh the status words in place, so Details keeps focus. + const version = item ? JSON.stringify({ ...item, working: item.working && { what: item.working.what, since: item.working.since } }) : ''; + if (version === detailVersion) { if (item && detailPill) detailPill.textContent = statusLabel(t, item); return; } detailVersion = version; $('detail-gone').hidden = !!item; for (const form of [$('approve-form'), $('reply-form')]) for (const c of form.elements) c.disabled = !item; @@ -606,7 +607,8 @@ function renderDetail() { const dl = $('detail-fields'); dl.replaceChildren(); const actor = statusOf(item).actor; - field(dl, t('field.status'), pill(item)); + detailPill = pill(item); + field(dl, t('field.status'), detailPill); if (actor === 'you') field(dl, t('field.next'), whatWaits(item)); if (actor === 'others') field(dl, t('field.others'), item.others); if (!item.done && item.run) field(dl, t('field.run'), el('code', '', item.run)); From 6c823b3bd48e0165cbcfbe230b9523928d410876 Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:14:52 +0900 Subject: [PATCH 3/3] =?UTF-8?q?feat(todo):=20=EC=95=B1=20=EC=A0=9C?= =?UTF-8?q?=EB=AA=A9=20=EC=95=84=EB=9E=98=EC=97=90=20=EC=A7=80=EA=B8=88=20?= =?UTF-8?q?=EC=9E=91=EC=97=85=20=EC=A4=91=EC=9D=B8=20=EC=97=90=EC=9D=B4?= =?UTF-8?q?=EC=A0=84=ED=8A=B8=20=EC=88=98=C2=B7=EC=B2=AB=20=ED=95=AD?= =?UTF-8?q?=EB=AA=A9=EC=9D=84=20=EB=B3=B4=EC=9D=B4=EA=B3=A0=20=EC=9E=91?= =?UTF-8?q?=EC=97=85=20=EC=A4=91=20=ED=96=89=EC=9D=84=20=EB=A7=A8=20?= =?UTF-8?q?=EC=9C=84=C2=B7=ED=96=89=20=EC=9C=84=20=ED=91=9C=EC=8B=9C?= =?UTF-8?q?=EB=A1=9C=20(v2.26.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 목록 접힌 행에서는 점 색만 달라 작업 중인지 알기 어려웠다. 탭 위 한 줄로 작업 중 N건(없으면 '없음')을, 행에는 '지금 작업 중 · N분째 · 하는 일'을 바로 보이고, 작업 중 행을 탭 맨 위로 올린다. --- log/changelog-v2.26.0.md | 1 + todo/app/src/i18n.rs | 4 +++- todo/app/src/main.rs | 35 +++++++++++++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/log/changelog-v2.26.0.md b/log/changelog-v2.26.0.md index ef1225d..e079c81 100644 --- a/log/changelog-v2.26.0.md +++ b/log/changelog-v2.26.0.md @@ -12,6 +12,7 @@ Every open item whose next step was an agent's read "Agent working" (`status.age - **"Agent working" is now "Agent's turn"** / "에이전트 차례": an open item an agent should take next but nobody has marked. - **Item JSON** (`list --json`, `next`/`take --json`, `/api/items`, `/events`) carries `working: { what, since, beat }` or `null` (null when the item is done or the mark expired). - **Every surface tells it apart:** the app gives it its own green tint, a halo around the row dot and a pulsing dot in its pill, repainting once a second only while an item is working; the web page shows a green pill with a CSS-pulsing dot and a green row bar; the TUI marks it `◉` in bold green with a "Working now · 12 min · build" line under the row (legend updated). +- **The app says it above the tabs:** a line under the title reads "N건 지금 작업 중 — — 지금 작업 중 · 6분째 · build" (click opens 진행 중), or a muted "지금 작업 중인 에이전트 없음". Working rows lead their tab and carry the label pill on the row itself, not only on hover. The empty Needs-you text no longer claims agents keep working. - **Expiry without a write:** the server and the TUI watch `todo-working.json` and also arm a timer for the oldest live mark's expiry (`core.watchWorking`), so a mark nobody refreshes leaves every view within the TTL (plus 50 ms), with no file change. - **Agents:** `todo/AGENT.md` asks to run `working ""` at least every 60 s while working an item and `working --off` when they stop; README and CLI help describe the command. diff --git a/todo/app/src/i18n.rs b/todo/app/src/i18n.rs index b8dc22a..caebce3 100644 --- a/todo/app/src/i18n.rs +++ b/todo/app/src/i18n.rs @@ -31,6 +31,8 @@ pub fn t(lang: Lang, key: &str) -> &'static str { "status.working" => ("Working now", "지금 작업 중"), "working.minutes" => (" min", "분째"), "working.justNow" => ("just started", "방금 시작"), + "working.count" => (" agent(s) working now", "건 지금 작업 중"), + "working.none" => ("No agent is working right now", "지금 작업 중인 에이전트 없음"), "status.handoff" => ("Answered — not picked up yet", "답변 전달됨 — 에이전트 수신 전"), "status.new" => ("Not started", "시작 전"), "status.blocked" => ("Blocked — needs action", "막힘 — 조치 필요"), @@ -40,7 +42,7 @@ pub fn t(lang: Lang, key: &str) -> &'static str { "live" => ("Live", "실시간"), "connecting" => ("Connecting…", "연결 중…"), "offline" => ("Offline", "연결 끊김"), - "empty.focus" => ("Nothing needs you right now. Agents keep working.", "지금은 정해 주실 게 없어요. 에이전트가 계속 일하고 있어요."), + "empty.focus" => ("Nothing needs you right now.", "지금은 정해 주실 게 없어요."), "empty" => ("Nothing here.", "항목이 없어요."), "waits" => ("The agent is asking", "에이전트가 묻고 있어요"), "ask.intent" => ("Is this the right scope to start? Read below, then approve or answer.", "이 범위로 시작해도 될까요? 아래를 보고 승인하거나 답해 주세요."), diff --git a/todo/app/src/main.rs b/todo/app/src/main.rs index 7d4722c..6d3f491 100644 --- a/todo/app/src/main.rs +++ b/todo/app/src/main.rs @@ -404,6 +404,9 @@ impl eframe::App for App { ui.label(RichText::new(reason).color(theme::tone("blocked", dark).0).size(12.0)); } ui.add_space(6.0); + // Whether any agent is actually working, before the tabs: an agent's turn alone is not work. + if working_strip(ui, &p, lang, dark, &model.items) { self.tab = Tab::Agent; } + ui.add_space(8.0); let queue = decision_queue(&model.items); // Items waiting on someone else are in progress, not yours. let in_progress = |i: &Item| !i.done && !i.pin && matches!(i.turn.actor.as_str(), "agent" | "others"); @@ -426,12 +429,14 @@ impl eframe::App for App { // Pinned items (settings) sit above every open tab, outside the tab's own list and counts. let pinned: Vec<&Item> = if self.tab == Tab::Done { Vec::new() } else { model.items.iter().filter(|i| i.pin && !i.done).collect() }; - let listed: Vec<&Item> = model.items.iter().filter(|i| !(i.pin && !i.done)).filter(|i| match self.tab { + let mut listed: Vec<&Item> = model.items.iter().filter(|i| !(i.pin && !i.done)).filter(|i| match self.tab { Tab::Focus => false, Tab::Agent => in_progress(i), Tab::All => !i.done, Tab::Done => i.done, }).collect(); + // Work happening now leads the list; the rest keep their order. + listed.sort_by_key(|i| i.turn.kind != "working"); let toast_height = if toast.is_some() { 44.0 } else { 0.0 }; // The decision on screen: the same one while it waits, else whatever now sits at its place. // Arrow keys turn the page unless a field is being typed in. @@ -945,13 +950,39 @@ fn meta_of(item: &Item) -> String { meta.join(" · ") } +/// One line above the tabs saying whether an agent is working right now: a pulsing pill with the count and the first +/// item's label, or a muted "none". Returns true when clicked (the caller opens the in-progress tab). +fn working_strip(ui: &mut egui::Ui, p: &theme::Palette, lang: Lang, dark: bool, items: &[Item]) -> bool { + let working: Vec<&Item> = items.iter().filter(|i| !i.done && i.turn.kind == "working").collect(); + let row = ui.horizontal(|ui| { + match working.first() { + None => { + let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover()); + ui.painter().circle_stroke(rect.center(), 3.5, Stroke::new(1.2, p.muted)); + ui.label(RichText::new(t(lang, "working.none")).color(p.muted).size(12.5)); + } + Some(first) => { + pill(ui, &format!("{}{}", working.len(), t(lang, "working.count")), "working", dark); + ui.add(egui::Label::new(RichText::new(format!("{} — {}", first.title, status_label(lang, first))) + .color(p.muted).size(12.5)).truncate().selectable(false)); + } + } + }).response; + !working.is_empty() && ui.interact(row.rect, egui::Id::new("working-strip"), Sense::click()) + .on_hover_cursor(egui::CursorIcon::PointingHand).clicked() +} + /// One line for an item: a dot in its actor's colour and the title, cut to fit; the hint shows on hover. /// Returns true when the line is clicked. fn line(ui: &mut egui::Ui, p: &theme::Palette, color: Color32, item: &Item, hint: &str) -> bool { let row = ui.horizontal(|ui| { let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover()); ui.painter().circle_filled(rect.center(), 4.0, color); - if item.turn.kind == "working" { ui.painter().circle_stroke(rect.center(), 6.0, Stroke::new(1.5, color.gamma_multiply(pulse(ui) - 0.3))); } + if item.turn.kind == "working" { + ui.painter().circle_stroke(rect.center(), 6.0, Stroke::new(1.5, color.gamma_multiply(pulse(ui) - 0.3))); + // Shown on the line itself, not only on hover: how long and on what the agent has been working. + pill(ui, hint, "working", ui.visuals().dark_mode); + } ui.add(egui::Label::new(RichText::new(&item.title).color(p.text).size(13.5)).truncate().selectable(false)); }).response; // The whole width answers the click, not only the text.