diff --git a/README.ko.md b/README.ko.md index c7cf7d3..841bb7a 100644 --- a/README.ko.md +++ b/README.ko.md @@ -182,7 +182,7 @@ TUI에서는 `L`, 웹 페이지에서는 언어 메뉴로 바꾸며 다시 시 사람이 직접 실행해야 하는 명령(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`는 그 서버가 응답하는 동안 다시 씁니다. -고정 항목(`todo.mjs pin `, 예: 선택지로 켜고 끄는 설정)은 앱의 모든 탭 맨 위에 남고 내 차례 건수에 들어가지 않습니다. 앱(`todo/app`, macOS·Windows)은 메뉴 막대나 트레이에서 내 차례 건수를 보여 주고, 새로 생기면 알림을 띄우며, 결정마다 결정할 것·한 줄 요약·왜만 짧게 보여 주고(전체 작업 문서는 접어 둠) 관련 티켓을 열며, 답변·승인·자가 조치를 같은 웹 API로 보냅니다. `todo.md`를 직접 쓰지 않습니다. 창을 닫아도 트레이에 남고, 종료하면 앱이 띄운 서버도 멈춥니다. macOS에서는 `todo/app/install-macos.sh [폴더]`가 `~/Applications`에 `sdlc To-do.app`(이름은 `SDLC_TODO_APP_NAME`)을 만듭니다. Finder는 셸 `PATH` 없이 앱을 띄우므로 키트·node·언어·`SDLC_TODO` 경로를 Info.plist에 적어 둡니다. 키트를 업데이트하거나 node를 옮기면 다시 실행하세요. +고정 항목(`todo.mjs pin `, 예: 선택지로 켜고 끄는 설정)은 앱의 모든 탭 맨 위에 남고 내 차례 건수에 들어가지 않습니다. 앱(`todo/app`, macOS·Windows)은 메뉴 막대나 트레이에서 내 차례 건수를 보여 주고, 새로 생기면 알림을 띄우며, 내 차례인 결정을 책장처럼 한 번에 한 건씩 보여 줍니다. 승인·막힘, 그리고 에이전트 권장 답이 없는 질문이 먼저 나옵니다. 쪽 번호와 화살표는 창 아래에 있고, 좌우 화살표 키로도 넘깁니다. 질문·지금 상황·답하면 하려는 것·왜·AI 권장·선택지별 설명이 보이고, 진행 단계·저장소·전체 작업 문서는 '자세히'에 접혀 있습니다. 창이 넓으면 두 쪽으로 펼쳐져 왼쪽에서 읽고 오른쪽 '내 답'에서 답합니다. 항목마다 나만 보는 메모를 적을 수 있고 글자 크기와 글꼴(Pretendard 내장)을 바꿀 수 있습니다. 둘 다 세션 파일 옆 `todo-app.json`에 남고 에이전트에게 가지 않습니다. 관련 티켓을 열며, 답변·승인·자가 조치를 같은 웹 API로 보냅니다. `todo.md`를 직접 쓰지 않습니다. 창을 닫아도 트레이에 남고, 종료하면 앱이 띄운 서버도 멈춥니다. macOS에서는 `todo/app/install-macos.sh [폴더]`가 `~/Applications`에 `sdlc To-do.app`(이름은 `SDLC_TODO_APP_NAME`)을 만듭니다. Finder는 셸 `PATH` 없이 앱을 띄우므로 키트·node·언어·`SDLC_TODO` 경로를 Info.plist에 적어 둡니다. 키트를 업데이트하거나 node를 옮기면 다시 실행하세요. 막힌 sdlc 항목의 **자가 조치**(앱·페이지 버튼, TUI `f`)는 `fix requested`를 남기고, 다음 `next`나 `take`가 그 막힘을 에이전트에게 한 번 넘깁니다(종료 코드 `0`, `"fix": true`). 그 뒤 풀릴 때까지는 다시 큐를 멈춥니다. 바로 에이전트를 띄우려면 to-do 파일 옆 `todo-agent.json`에 명령을 적으세요. 예: `{"fix": ["claude", "-p", "follow {kit}/todo/AGENT.md; take {id} and clear its block"]}`. `{id}`·`{kit}`·`{project}`를 채워 프로젝트 폴더에서 분리 실행합니다. 언어를 더하려면 `todo/locales/en.mjs`를 `todo/locales/.mjs`로 복사해 `name`과 모든 문구를 옮기고, `todo/i18n.mjs`의 `locales`에 import를 하나 더하세요. diff --git a/README.md b/README.md index 5eefbd1..7840184 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ An agent can also prefill the answer it recommends (`suggest "answer"`, sto 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. -A pinned item (`todo.mjs pin `), such as a setting switched with its choices, stays at the top of every app tab and is not counted as needing you. The app (`todo/app`, macOS and Windows) sits in the menu bar or tray with a count of items that need you, notifies you when one appears, and shows each decision as what to decide, a one-line summary and why (the full work document folds away), opens the related tickets, and answers, approves and requests fixes through the same web API, so it never writes `todo.md` itself; closing the window keeps it in the tray, and Quit stops the server it started. On macOS, `todo/app/install-macos.sh [DIR]` builds `sdlc To-do.app` (name: `SDLC_TODO_APP_NAME`) in `~/Applications`; its Info.plist records the kit, node, language and `SDLC_TODO`, because Finder starts apps without a shell `PATH`. Run it again after updating the kit or moving node. +A pinned item (`todo.mjs pin `), such as a setting switched with its choices, stays at the top of every app tab and is not counted as needing you. The app (`todo/app`, macOS and Windows) sits in the menu bar or tray with a count of items that need you, notifies you when one appears, and shows the decisions that need you one at a time, like pages of a book (the page number and arrows sit at the foot; the arrow keys turn the page), with approvals, blocks and questions the agent recommends no answer for first: the question, the situation, what happens once you answer, why, the agent's pick and what each choice does (the phase, repos and full work document fold away under More). On a wide window a decision opens as a two-page spread, what to read on the left and how to answer on the right. You can keep a memo of your own on an item and set the text size and font (Pretendard is built in); both stay in `todo-app.json` beside the session file and never reach agents. It opens the related tickets, and answers, approves and requests fixes through the same web API, so it never writes `todo.md` itself; closing the window keeps it in the tray, and Quit stops the server it started. On macOS, `todo/app/install-macos.sh [DIR]` builds `sdlc To-do.app` (name: `SDLC_TODO_APP_NAME`) in `~/Applications`; its Info.plist records the kit, node, language and `SDLC_TODO`, because Finder starts apps without a shell `PATH`. Run it again after updating the kit or moving node. **Fix by agent** (app and page button, TUI `f`) on a blocked sdlc item records `fix requested`; the next `next` or `take` hands the block to an agent once (exit `0`, `"fix": true`), then it stops the queue again until cleared. To start an agent right away, put a command in `todo-agent.json` beside the to-do file, for example `{"fix": ["claude", "-p", "follow {kit}/todo/AGENT.md; take {id} and clear its block"]}`; `{id}`, `{kit}` and `{project}` are filled in and it runs detached in the project. To add a language, copy `todo/locales/en.mjs` to `todo/locales/.mjs`, translate `name` and every message, and add its import to `locales` in `todo/i18n.mjs`. diff --git a/VERSION b/VERSION index 0f5dfbe..5c18f91 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.24.1 +2.25.0 diff --git a/log/changelog-v2.25.0.md b/log/changelog-v2.25.0.md new file mode 100644 index 0000000..c8e76cd --- /dev/null +++ b/log/changelog-v2.25.0.md @@ -0,0 +1,24 @@ +# v2.25.0: The app reads like a book, one decision at a time + +To-do app (`todo/app`) only. The web page, the TUI, the server and `todo.md` are unchanged. + +## Problem + +The **Needs you** tab opened every waiting item at once. With 16 items waiting, 16 full cards shared one scroll, each with a status pill, the six-phase stepper, a "now · next" line and the repos. Five count pills sat over four tabs that said the same thing. The one thing each card exists for, what the human has to decide, did not stand out from the rest, and a choice was a bare label: what each option does was only in the folded document. + +## Changes + +- **One decision at a time.** The Needs-you tab shows a single decision. Its page number (`3 / 16`) with previous/next arrows sits at the foot of the window, outside the scrolling area, like a book's page number; the left/right arrow keys turn the page unless a field is being typed in. Answering brings up the decision now at that place; a newly arrived decision does not move the one on screen. The others fold under **Other decisions**, one line each. +- **What only you can decide comes first.** Gate approvals, blocks and questions with no agent-recommended answer lead the queue and are marked **Yours to decide**; a question with a recommended answer is marked **AI suggestion ready**. Decisions for one ticket stay together, the one offering choices first. +- **A book-like page.** Paper tones in light and dark, a page with wide margins, roomier line spacing and no bullet dots. On a wide window (960 points or more) a decision opens as a two-page spread: the left page is what to read (the question, the situation, what happens once you answer, why, the agent's pick), the right page, **Your answer**, is how to answer (the choices with what each does, the answer field, approve, fix, tickets, memo, **More**). A narrower window shows both on one page in a centred column of at most 760 points; the spread is at most 1240 points wide. List tabs run in two columns on a wide window. The window opens at 600×820. +- **A fuller brief.** A leading `(AS-IS):` or `(TO-BE):` tag is dropped, repeated lines show once, brief lines are cut at 320 characters instead of 160, and the agent's pick has its own box. +- **Choices say what they do.** When the document has an `## Options` (or `## 선택지`) section with one numbered line per choice (`1. **label** — what it does`), each choice button is stacked over the line whose label matches it; a list that does not match the choices one to one shows nothing rather than mislabel them. +- **Less on screen.** Tabs carry the counts and the five count pills are gone; the connection is a dot, with words only when it is not live; the phase stepper, the repos and the whole document are under **More**; help lines became hover text. The other tabs list one line per item and open on a click; a decision's line leads to the Needs-you tab. +- **Memo.** Each open item has a memo of your own. Memos are never sent to agents or written to `todo.md`. The approval note field is now labelled **Words for the approval (optional)** so it is not confused with the memo. +- **Text size and font.** The header's **Aa** button opens the size (5% steps, 80–200%, default 115%; Cmd/Ctrl with `+`/`-` is kept as well) and the font. Pretendard Regular (SIL OFL 1.1, licence in `todo/app/fonts/Pretendard-LICENSE.txt`) is built into the binary as the default. Other readable Hangul fonts found on the machine can be picked: Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK/KR, NanumGothic, NanumSquare, Spoqa Han Sans Neo, SUIT, AppleGothic, AppleMyungjo and NanumMyeongjo. Malgun Gothic is not bundled: it is Microsoft's and can be picked only where it is installed. +- **`todo-app.json`**, beside the session file (mode 0600), keeps the size, the font and the memos. It is saved through a temporary file, and a file that cannot be read or does not parse is set aside as `todo-app.json.bad` and reported rather than overwritten. Memos of done items are dropped. +- **Tests.** `cargo test` in `todo/app` covers the queue order, where the focus lands after an answer, the option lines (matched to choices by label, not position), the tag removal and the settings file. The Rust app is not built in CI. + +## After updating + +Rebuild the app: run `todo/app/install-macos.sh` again (macOS), or `cargo build --release` in `todo/app`. diff --git a/todo/app/Cargo.lock b/todo/app/Cargo.lock index 58bb992..3a919e0 100644 --- a/todo/app/Cargo.lock +++ b/todo/app/Cargo.lock @@ -2843,6 +2843,7 @@ dependencies = [ "serde", "serde_json", "tray-icon", + "ttf-parser", "ureq", ] diff --git a/todo/app/Cargo.toml b/todo/app/Cargo.toml index eec727b..6975bae 100644 --- a/todo/app/Cargo.toml +++ b/todo/app/Cargo.toml @@ -15,6 +15,7 @@ notify-rust = "4" ureq = { version = "2", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" +ttf-parser = { version = "=0.25.1", default-features = false } [profile.release] opt-level = "s" diff --git a/todo/app/fonts/Pretendard-LICENSE.txt b/todo/app/fonts/Pretendard-LICENSE.txt new file mode 100644 index 0000000..160421b --- /dev/null +++ b/todo/app/fonts/Pretendard-LICENSE.txt @@ -0,0 +1,104 @@ +Copyright (c) 2021, Kil Hyung-jin (https://github.com/orioncactus/pretendard), +with Reserved Font Name 'Pretendard'. + +Copyright 2014-2021 Adobe (http://www.adobe.com/), +with Reserved Font Name 'Source'. +Source is a trademark of Adobe in the United States and/or other countries. + +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter), +with Reserved Font Name 'Inter'. + +Copyright 2021 The M+ FONTS Project Authors (https://github.com/coz-m/MPLUS_FONTS), +with Reserved Font Name 'M PLUS 1'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/todo/app/fonts/Pretendard-Regular.otf b/todo/app/fonts/Pretendard-Regular.otf new file mode 100644 index 0000000..08bf4cf Binary files /dev/null and b/todo/app/fonts/Pretendard-Regular.otf differ diff --git a/todo/app/src/i18n.rs b/todo/app/src/i18n.rs index 7b7a8f5..bb6cd7f 100644 --- a/todo/app/src/i18n.rs +++ b/todo/app/src/i18n.rs @@ -20,12 +20,6 @@ pub fn t(lang: Lang, key: &str) -> &'static str { "phase.done" => ("Done", "완료"), "phase.legacy" => ("Legacy", "구버전"), "phase.now" => ("Now", "지금"), - "phase.next" => ("next", "다음"), - "you" => ("Your turn", "내 차례"), - "agent" => ("Agent", "에이전트"), - "others" => ("Waiting on others", "다른 사람 대기"), - "blocked" => ("Blocked", "막힘"), - "done" => ("Done", "완료"), "tab.focus" => ("Needs you", "확인 필요"), "tab.agent" => ("In progress", "진행 중"), "tab.all" => ("All", "전체"), @@ -49,17 +43,29 @@ pub fn t(lang: Lang, key: &str) -> &'static str { "ask.intent" => ("Is this the right scope to start? Read below, then approve or answer.", "이 범위로 시작해도 될까요? 아래를 보고 승인하거나 답해 주세요."), "ask.plan" => ("Is this plan good to build? Read below, then approve or answer.", "이 계획대로 만들어도 될까요? 아래를 보고 승인하거나 답해 주세요."), "problem" => ("What is stuck", "막힌 이유"), - "doc.questions" => ("Your call", "정해 주실 것"), "doc.summary" => ("In one line", "한 줄로 보면"), + "doc.changes" => ("Once you answer", "답하면 하려는 것"), + "pick" => ("AI pick", "AI 권장"), + "memo" => ("Memo", "메모"), + "memo.hint" => ("Only you see this; it is not sent to agents.", "나만 봐요. 에이전트에게 가지 않아요."), + "view" => ("Aa", "가"), + "view.help" => ("Text size and font", "글자 크기·글꼴"), + "view.size" => ("Size", "크기"), + "view.font" => ("Font", "글꼴"), + "view.font.default" => ("Pretendard (default)", "Pretendard (기본)"), "doc.background" => ("Background", "지금 상황"), "doc.why" => ("Why it matters", "왜 필요한가요"), - "doc.full" => ("More detail", "자세히 보기"), + "more" => ("More", "자세히"), + "decide.yours" => ("Yours to decide", "직접 정해 주세요"), + "decide.suggested" => ("AI suggestion ready", "AI 권장 있음"), + "queue.rest" => ("Other decisions", "다른 결정"), + "page.answer" => ("Your answer", "내 답"), "doc.loading" => ("Loading the work document…", "작업 문서 불러오는 중…"), "reply.hint" => ("Your answer, in one line", "한 줄로 답해 주세요"), "reply.send" => ("Send answer", "답변 보내기"), "reply.sent" => ("Answer sent", "답변 보냄"), "reply.help" => ("Enter sends. An answer helps the agent; it is not an approval.", "Enter로 보내요. 답변은 에이전트가 참고할 뿐, 승인으로 치지 않아요."), - "approve.note" => ("Note (optional)", "메모 (선택)"), + "approve.note" => ("Words for the approval (optional)", "승인에 남길 말 (선택)"), "approve.button" => ("Approve this version", "이 버전 승인"), "approve.done" => ("Approved", "승인함"), "run.button" => ("Open in Terminal", "터미널에서 열기"), diff --git a/todo/app/src/main.rs b/todo/app/src/main.rs index b8a2ea8..b509333 100644 --- a/todo/app/src/main.rs +++ b/todo/app/src/main.rs @@ -3,11 +3,13 @@ #![cfg_attr(windows, windows_subsystem = "windows")] mod client; mod i18n; +mod prefs; mod theme; use client::{Artifact, Item, Launcher, Model, Session}; use eframe::egui::{self, Align, Color32, CornerRadius, Layout, Margin, RichText, Sense, Stroke, ViewportCommand}; use i18n::{t, Lang}; +use prefs::Prefs; use serde_json::json; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; @@ -39,17 +41,68 @@ struct App { state: State, lang: Lang, tab: Tab, + /// Rows opened on the list tabs. open: HashSet, - closed: HashSet, + /// The decision on screen in the Needs-you tab and its place in the queue: when it leaves + /// the queue (answered), the decision now at that place takes over. + focus: Option, + focus_at: usize, /// Reply drafts by item: (text, the suggestion it started from). drafts: HashMap, notes: HashMap, + /// The human's view settings and memos, saved beside the session file whenever they change. + prefs: Prefs, + prefs_file: PathBuf, + prefs_dirty: bool, + /// Fonts found on this machine, as (name, file); the settings card lists them. + fonts: Vec<(String, String)>, + settings: bool, tray: Option, badge: Option, } +/// The window width, in points, from which the content opens as a two-page spread. +const SPREAD_FROM: f32 = 960.0; + +/// Which side of a decision to draw: what to read, how to answer, or both on one page. +#[derive(Clone, Copy, PartialEq)] +enum Part { Both, Read, Act } + fn needs_you(item: &Item) -> bool { !item.done && matches!(item.turn.actor.as_str(), "you" | "blocked") } +/// A decision the agent recommends no answer for: a gate approval, a block, or an open question. +/// These lead the queue and are marked; the rest can be settled by taking the recommendation. +fn must_decide(item: &Item) -> bool { + needs_you(item) && (item.turn.kind != "answer" || (item.pick.is_none() && item.suggest.trim().is_empty())) +} + +fn ticket_url(item: &Item) -> Option<&str> { item.link.as_ref().map(|l| l.url.as_str()).filter(|u| !u.is_empty()) } + +/// The decisions waiting for the human, shown one at a time: those without a recommendation first, +/// each with the other decisions for the same ticket. Pinned settings are not decisions. +fn decision_queue(items: &[Item]) -> Vec<&Item> { + let mut mine: Vec<&Item> = items.iter().filter(|i| needs_you(i) && !i.pin).collect(); + mine.sort_by_key(|i| !must_decide(i)); + let mut out: Vec<&Item> = Vec::new(); + for item in &mine { + if out.iter().any(|o| o.id == item.id) { continue; } + let mut group: Vec<&Item> = match ticket_url(item) { + Some(url) => mine.iter().copied().filter(|other| ticket_url(other) == Some(url)).collect(), + None => vec![*item], + }; + // Within a ticket the item that offers choices is the decision; one beside it often only points there. + group.sort_by_key(|i| i.choices.is_empty()); + out.extend(group); + } + out +} + +/// Where the focus lands: on the same decision while it waits, else on whatever now sits at its place. +fn settle(focus: Option<&str>, at: usize, queue: &[&str]) -> Option { + if queue.is_empty() { return None; } + 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 { match item.turn.kind.as_str() { "approve-intent" => t(lang, "status.approve-intent"), @@ -151,9 +204,16 @@ fn connect(state: State, ctx: egui::Context, launcher: Launcher, lang: Lang) { impl App { fn new(cc: &eframe::CreationContext, launcher: Launcher, lang: Lang) -> App { - theme::install(&cc.egui_ctx); + let prefs_file = launcher.session_file.with_file_name("todo-app.json"); + let (mut prefs, prefs_error) = Prefs::load(&prefs_file); + let fonts = theme::fonts(); + // Only a font found on this machine leads; a path that is gone falls back to the built-in one. + if !fonts.iter().any(|(_, file)| *file == prefs.font) { prefs.font.clear(); } + theme::install(&cc.egui_ctx, &prefs.font); + cc.egui_ctx.set_zoom_factor(prefs.zoom); let state: State = Arc::new(Mutex::new(Shared { - model: None, conn: Conn::Connecting, session: None, child: None, toast: None, + model: None, conn: Conn::Connecting, session: None, child: None, + toast: prefs_error.map(|error| (error, true, Instant::now())), artifacts: HashMap::new(), busy: HashSet::new(), })); let tray = build_tray(lang).ok(); @@ -172,7 +232,8 @@ impl App { } })); connect(state.clone(), ctx, launcher, lang); - App { state, lang, tab: Tab::Focus, open: HashSet::new(), closed: HashSet::new(), drafts: HashMap::new(), notes: HashMap::new(), tray, badge: None } + App { state, lang, tab: Tab::Focus, open: HashSet::new(), focus: None, focus_at: 0, drafts: HashMap::new(), notes: HashMap::new(), + prefs, prefs_file, prefs_dirty: false, fonts, settings: false, tray, badge: None } } /// Runs one request off the UI thread; the event stream brings the new list back. @@ -263,137 +324,259 @@ 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 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. + if zoom != ctx.zoom_factor() { ctx.set_zoom_factor(zoom); } + if (zoom - self.prefs.zoom).abs() > 0.001 { self.prefs.zoom = zoom; self.prefs_dirty = true; } let dark = ctx.style().visuals.dark_mode; let p = theme::palette(dark); egui::CentralPanel::default() .frame(egui::Frame::new().fill(p.bg).inner_margin(Margin::symmetric(18, 16))) .show(ctx, |ui| { - ui.horizontal(|ui| { - ui.heading(RichText::new(t(lang, "title")).strong()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let (color, text) = match &conn { - Conn::Live => (Color32::from_rgb(34, 197, 94), t(lang, "live")), - Conn::Connecting => (Color32::from_rgb(245, 158, 11), t(lang, "connecting")), - Conn::Offline(_) => (Color32::from_rgb(239, 68, 68), t(lang, "offline")), - }; - ui.label(RichText::new(text).color(p.muted).size(12.0)); - let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover()); - ui.painter().circle_filled(rect.center(), 4.0, color); + // Lines keep a readable length: a wide window opens like a book, two pages side by side, and a + // narrow one keeps a single page. + let full = ui.max_rect(); + let spread = full.width() >= SPREAD_FROM; + let column = egui::Rect::from_center_size(full.center(), egui::vec2(full.width().min(if spread { 1240.0 } else { 760.0 }), full.height())); + ui.allocate_new_ui(egui::UiBuilder::new().max_rect(column), |ui| { + ui.horizontal(|ui| { + ui.heading(RichText::new(t(lang, "title")).strong()); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + // Live is the normal state and gets only a dot; trouble gets words. + let (color, text) = match &conn { + Conn::Live => (Color32::from_rgb(34, 197, 94), ""), + Conn::Connecting => (Color32::from_rgb(245, 158, 11), t(lang, "connecting")), + Conn::Offline(_) => (Color32::from_rgb(239, 68, 68), t(lang, "offline")), + }; + if !text.is_empty() { ui.label(RichText::new(text).color(p.muted).size(12.0)); } + let (rect, dot) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover()); + ui.painter().circle_filled(rect.center(), 4.0, color); + if text.is_empty() { dot.on_hover_text(t(lang, "live")); } + let view = egui::Button::new(RichText::new(t(lang, "view")).color(p.muted).size(13.0)).frame(self.settings).corner_radius(CornerRadius::same(8)); + if ui.add(view).on_hover_text(t(lang, "view.help")).clicked() { self.settings = !self.settings; } + }); }); - }); - if let Conn::Offline(reason) = &conn { - ui.label(RichText::new(reason).color(theme::tone("blocked", dark).0).size(12.0)); - } - ui.add_space(4.0); - let count = |actor: &str| model.items.iter().filter(|i| i.turn.actor == actor).count(); - ui.horizontal(|ui| { - for (actor, key) in [("you", "you"), ("agent", "agent"), ("others", "others"), ("blocked", "blocked"), ("done", "done")] { - pill(ui, &format!("{} {}", t(lang, key), count(actor)), actor, dark); + if self.settings { self.view_settings(ui, ctx, &p); } + if let Conn::Offline(reason) = &conn { + ui.label(RichText::new(reason).color(theme::tone("blocked", dark).0).size(12.0)); } - }); - ui.add_space(10.0); - egui::Frame::new().fill(p.card).stroke(Stroke::new(1.0, p.stroke)).corner_radius(CornerRadius::same(10)) - .inner_margin(Margin::same(3)).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for (tab, key) in [(Tab::Focus, "tab.focus"), (Tab::Agent, "tab.agent"), (Tab::All, "tab.all"), (Tab::Done, "tab.done")] { - let selected = self.tab == tab; - let text = RichText::new(t(lang, key)).color(if selected { p.on_accent } else { p.muted }).strong(); - let button = egui::Button::new(text).fill(if selected { p.accent } else { Color32::TRANSPARENT }) - .stroke(Stroke::NONE).corner_radius(CornerRadius::same(8)); - if ui.add(button).clicked() { self.tab = tab; } - } + ui.add_space(6.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"); + let counts = [Some(queue.len()), Some(model.items.iter().filter(|i| in_progress(i)).count()), None, None]; + egui::Frame::new().fill(p.card).stroke(Stroke::new(1.0, p.stroke)).corner_radius(CornerRadius::same(10)) + .inner_margin(Margin::same(3)).show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for ((tab, key), count) in [(Tab::Focus, "tab.focus"), (Tab::Agent, "tab.agent"), (Tab::All, "tab.all"), (Tab::Done, "tab.done")].into_iter().zip(counts) { + let selected = self.tab == tab; + let label = match count { Some(n) if n > 0 => format!("{} {n}", t(lang, key)), _ => t(lang, key).to_string() }; + let text = RichText::new(label).color(if selected { p.on_accent } else { p.muted }).strong(); + let button = egui::Button::new(text).fill(if selected { p.accent } else { Color32::TRANSPARENT }) + .stroke(Stroke::NONE).corner_radius(CornerRadius::same(8)); + if ui.add(button).clicked() { self.tab = tab; } + } + }); }); - }); - ui.add_space(10.0); + ui.add_space(10.0); - // 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 shown: Vec<&Item> = model.items.iter().filter(|i| !(i.pin && !i.done)).filter(|i| match self.tab { - Tab::Focus => needs_you(i), - // Items waiting on someone else are in progress, not yours. - Tab::Agent => !i.done && matches!(i.turn.actor.as_str(), "agent" | "others"), - Tab::All => !i.done, - Tab::Done => i.done, - }).collect(); - let toast_height = if toast.is_some() { 44.0 } else { 0.0 }; - egui::ScrollArea::vertical().max_height(ui.available_height() - toast_height).auto_shrink([false, false]).show(ui, |ui| { - ui.add_space(1.0); - for item in &pinned { - self.pinned(ui, ctx, &p, item, busy.contains(&item.id)); - ui.add_space(8.0); - } - if shown.is_empty() && conn == Conn::Live { - ui.add_space(40.0); - ui.vertical_centered(|ui| ui.label(RichText::new(t(lang, if self.tab == Tab::Focus { "empty.focus" } else { "empty" })).color(p.muted))); - } - // Items that need you for the same ticket sit together under its name, at the first one's place. - let mut grouped: HashSet<&str> = HashSet::new(); - for item in &shown { - let ticket = item.link.as_ref().filter(|l| needs_you(item) && !l.url.is_empty()).map(|l| (l.label.as_str(), l.url.as_str())); - let members: Vec<&Item> = match ticket { - Some((_, url)) => shown.iter().copied().filter(|i| needs_you(i) && i.link.as_ref().is_some_and(|l| l.url == url)).collect(), - None => vec![*item], + // 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 { + Tab::Focus => false, + Tab::Agent => in_progress(i), + Tab::All => !i.done, + Tab::Done => i.done, + }).collect(); + 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. + let on_focus = self.tab == Tab::Focus; + let ids: Vec<&str> = queue.iter().map(|i| i.id.as_str()).collect(); + let mut at = if on_focus { settle(self.focus.as_deref(), self.focus_at, &ids) } else { None }; + if let Some(now) = at { + let step = if ctx.memory(|m| m.focused().is_some()) { 0 } else { + ctx.input(|i| i.key_pressed(egui::Key::ArrowRight) as isize - i.key_pressed(egui::Key::ArrowLeft) as isize) }; - if members.len() < 2 { - self.card(ui, ctx, &p, dark, item, busy.contains(&item.id), artifacts.get(&artifact_key(item))); + at = Some(now.saturating_add_signed(step).min(queue.len() - 1)); + } + let foot_height = if at.is_some() && queue.len() > 1 { 42.0 } else { 0.0 }; + // Each decision opens at its top: the scroll offset is kept per decision, not carried to the next. + let scroll_id = at.map(|now| queue[now].id.clone()).unwrap_or_default(); + egui::ScrollArea::vertical().id_salt(("main", scroll_id)).max_height(ui.available_height() - toast_height - foot_height).auto_shrink([false, false]).show(ui, |ui| { + ui.add_space(1.0); + for item in &pinned { + self.pinned(ui, ctx, &p, item, busy.contains(&item.id)); ui.add_space(8.0); - continue; } - let (label, url) = ticket.unwrap(); - if !grouped.insert(url) { continue; } - ui.label(RichText::new(label).color(p.muted).size(13.0).strong()); - ui.add_space(4.0); - for member in members { - ui.horizontal_top(|ui| { - ui.add_space(12.0); - ui.vertical(|ui| self.card(ui, ctx, &p, dark, member, busy.contains(&member.id), artifacts.get(&artifact_key(member)))); - }); - ui.add_space(8.0); + if on_focus { + // One decision at a time; answering it brings the next one up. + match at { + Some(now) => at = Some(self.decision(ui, ctx, &p, dark, spread, &queue, now, &busy, &artifacts)), + None if conn == Conn::Live => { + ui.add_space(40.0); + ui.vertical_centered(|ui| ui.label(RichText::new(t(lang, "empty.focus")).color(p.muted))); + } + None => {} + } + return; } + if listed.is_empty() && conn == Conn::Live { + ui.add_space(40.0); + ui.vertical_centered(|ui| ui.label(RichText::new(t(lang, "empty")).color(p.muted))); + } + // On a wide window the list runs down two columns. + let two = spread && listed.len() > 1; + let per_column = if two { listed.len().div_ceil(2) } else { listed.len().max(1) }; + let mut clicked: Option<&Item> = None; + ui.columns(if two { 2 } else { 1 }, |columns| { + for (column, items) in columns.iter_mut().zip(listed.chunks(per_column)) { + for item in items { + if self.row(column, ctx, &p, dark, item, busy.contains(&item.id), artifacts.get(&artifact_key(item))) { clicked = Some(*item); } + column.add_space(6.0); + } + } + }); + if let Some(item) = clicked { + // A decision is made in one place: its line leads to the Needs-you tab. + if needs_you(item) { (self.tab, self.focus) = (Tab::Focus, Some(item.id.clone())); } + else if !self.open.remove(&item.id) { self.open.insert(item.id.clone()); } + } + }); + // The page number sits at the foot like a book's, with the arrows that turn the page. + if let Some(now) = at.filter(|_| queue.len() > 1) { + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(((ui.available_width() - 150.0) / 2.0).max(0.0)); + let arrow = |ui: &mut egui::Ui, glyph: &str, enabled: bool| ui.add_enabled(enabled, + egui::Button::new(RichText::new(glyph).size(15.0).strong()).corner_radius(CornerRadius::same(8)).min_size(egui::vec2(30.0, 28.0))).clicked(); + if arrow(ui, "‹", now > 0) { at = Some(now - 1); } + ui.add_sized([70.0, 28.0], egui::Label::new(RichText::new(format!("{} / {}", now + 1, queue.len())).color(p.muted).size(13.0).strong())); + if arrow(ui, "›", now + 1 < queue.len()) { at = Some(now + 1); } + }); + } + if on_focus { (self.focus, self.focus_at) = (at.map(|now| queue[now].id.clone()), at.unwrap_or(0)); } + if let Some((text, error, _)) = toast { + let (fg, bg) = if error { theme::tone("blocked", dark) } else { (p.text, p.card) }; + egui::Frame::new().fill(bg).stroke(Stroke::new(1.0, p.stroke)).corner_radius(CornerRadius::same(10)) + .inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(RichText::new(text).color(fg)); }); } }); - if let Some((text, error, _)) = toast { - let (fg, bg) = if error { theme::tone("blocked", dark) } else { (p.text, p.card) }; - egui::Frame::new().fill(bg).stroke(Stroke::new(1.0, p.stroke)).corner_radius(CornerRadius::same(10)) - .inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(RichText::new(text).color(fg)); }); - } }); + if self.prefs_dirty { + self.prefs_dirty = false; + // Empty memos and memos of items the list shows as done are dropped. An id the list does not have is + // kept: ids change with title edits and items can be briefly absent, and a lost memo cannot come back. + let done: HashSet<&str> = model.items.iter().filter(|i| i.done).map(|i| i.id.as_str()).collect(); + self.prefs.memos.retain(|id, text| !text.trim().is_empty() && !done.contains(id.as_str())); + if let Err(error) = self.prefs.save(&self.prefs_file) { + self.state.lock().unwrap().toast = Some((error, true, Instant::now())); + } + } } } impl App { + /// Text size and font, opened from the header: the human's own, kept across runs. + fn view_settings(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette) { + let lang = self.lang; + theme::row(p).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(RichText::new(t(lang, "view.size")).color(p.muted).size(12.5)); + let mut zoom = self.prefs.zoom; + if ui.button("-").clicked() { zoom -= 0.05; } + ui.label(RichText::new(format!("{:.0}%", self.prefs.zoom * 100.0)).strong()); + if ui.button("+").clicked() { zoom += 0.05; } + // Whole 5% steps; the next frame sees the new factor and saves it. + let zoom = ((zoom * 20.0).round() / 20.0).clamp(prefs::ZOOM.0, prefs::ZOOM.1); + if zoom != self.prefs.zoom { ctx.set_zoom_factor(zoom); } + }); + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(t(lang, "view.font")).color(p.muted).size(12.5)); + let built_in = (t(lang, "view.font.default").to_string(), String::new()); + for (name, file) in std::iter::once(built_in).chain(self.fonts.clone()) { + let selected = self.prefs.font == file; + if ui.selectable_label(selected, name).clicked() && !selected { + theme::install(ctx, &file); + self.prefs.font = file; + self.prefs_dirty = true; + } + } + }); + }); + ui.add_space(4.0); + } + + /// The Needs-you tab: one decision on screen, the others folded under it. On a wide window it opens as + /// a spread: what to read on the left page, how to answer on the right. Returns the place to show + /// next (a click on another decision moves it). #[allow(clippy::too_many_arguments)] - fn card(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, dark: bool, item: &Item, busy: bool, artifact: Option<&Result>) { + fn decision(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, dark: bool, spread: bool, queue: &[&Item], at: usize, + busy: &HashSet, artifacts: &HashMap>) -> usize { let lang = self.lang; - // Items that need a decision open by default; others open on demand. - let expanded = if needs_you(item) { !self.closed.contains(&item.id) } else { self.open.contains(&item.id) }; - let id = item.id.clone(); - theme::card(p).show(ui, |ui| { + let item = queue[at]; + let (busy, artifact) = (busy.contains(&item.id), artifacts.get(&artifact_key(item))); + let mut go = at; + theme::page(p).show(ui, |ui| { ui.set_width(ui.available_width()); - pill(ui, status_label(lang, item), &item.turn.actor, dark); - // Where the work stands in the sdlc loop: every phase, the current one highlighted, then what comes next. - if let Some(phase) = phase_of(item, artifact) { ui.add_space(4.0); stepper(ui, p, lang, &phase); } - ui.add_space(2.0); - let header = ui.add(egui::Label::new(RichText::new(&item.title).size(14.5).strong()).sense(Sense::click())) - .on_hover_cursor(egui::CursorIcon::PointingHand); - let mut meta = Vec::new(); - if let Some(project) = item.project.as_deref().filter(|p| !p.is_empty()) { - meta.push(PathBuf::from(project).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| project.to_string())); - } - if let Some(link) = &item.link { meta.push(link.label.clone()); } - if !meta.is_empty() { ui.label(RichText::new(meta.join(" · ")).color(p.muted).size(12.0)); } - // Where the change lands, on every card whether open or folded. - if !item.repos.is_empty() { - ui.label(RichText::new(format!("{} {}", t(lang, "repos"), item.repos.join(", "))).color(p.accent).size(12.0)); + if !spread { + heading(ui, p, dark, lang, item); + self.details(ui, ctx, p, item, busy, artifact, Part::Both); + return; } - if header.clicked() { - let set = if needs_you(item) { &mut self.closed } else { &mut self.open }; - if !set.remove(&id) { set.insert(id.clone()); } + // The gap between the pages; each page gets the usual spacing back, since child Uis copy the parent's. + let spacing = ui.spacing().item_spacing.x; + ui.spacing_mut().item_spacing.x = 44.0; + ui.columns(2, |pages| { + let [left, right] = pages else { return }; + left.spacing_mut().item_spacing.x = spacing; + right.spacing_mut().item_spacing.x = spacing; + heading(left, p, dark, lang, item); + self.details(left, ctx, p, item, busy, artifact, Part::Read); + right.label(RichText::new(t(lang, "page.answer")).color(p.muted).size(12.0)); + right.add_space(4.0); + self.details(right, ctx, p, item, busy, artifact, Part::Act); + }); + // The fold between the two pages. + let rect = ui.min_rect(); + ui.painter().vline(rect.center().x, rect.y_range(), Stroke::new(1.0, p.stroke)); + }); + if queue.len() > 1 { + let yours = queue.iter().enumerate().filter(|(i, other)| *i != at && must_decide(other)).count(); + let mut title = format!("{} {}", t(lang, "queue.rest"), queue.len() - 1); + if yours > 0 { title.push_str(&format!(" · {} {yours}", t(lang, "decide.yours"))); } + 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; } + } + }); + } + go + } + + /// A list tab's item: one line, opened on demand. Returns true when the line is clicked. + #[allow(clippy::too_many_arguments)] + fn row(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, dark: bool, item: &Item, busy: bool, artifact: Option<&Result>) -> bool { + let lang = self.lang; + 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)); + 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); + ui.label(RichText::new(meta_of(item)).color(p.muted).size(12.0)); + }); + self.details(ui, ctx, p, item, busy, artifact, Part::Both); } - if expanded { ui.add_space(6.0); self.details(ui, ctx, p, item, busy, artifact); } }); + clicked } /// A pinned item is one line: its title, then its choices (e.g. a setting's on/off), the current pick highlighted. @@ -403,14 +586,16 @@ impl App { ui.horizontal_wrapped(|ui| { ui.label(RichText::new(&item.title).size(14.0).strong()); ui.add_space(8.0); - self.choice_buttons(ui, ctx, p, item, busy, false); + self.choice_buttons(ui, ctx, p, item, busy, false, &[]); }); }); } /// One button per offered answer; a click sends that label as an ordinary reply. Decisions put the - /// recommended one first; a pinned setting keeps its order and marks the current pick. - fn choice_buttons(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, item: &Item, busy: bool, recommend: bool) { + /// recommended one first, each over what it does (`about`, by choice) when the document says; + /// a pinned setting keeps its order and marks the current pick. + #[allow(clippy::too_many_arguments)] + fn choice_buttons(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, item: &Item, busy: bool, recommend: bool, about: &[String]) { let lang = self.lang; let mut order: Vec<(usize, &String)> = item.choices.iter().enumerate().collect(); if recommend { order.sort_by_key(|(i, _)| item.pick != Some(i + 1)); } @@ -425,10 +610,15 @@ impl App { let (id, version, text, sent) = (item.id.clone(), item.version.clone(), label.clone(), t(lang, "reply.sent")); self.act(ctx, &id.clone(), move |s| client::post(s, "/api/item", json!({ "id": id, "version": version, "op": "reply", "text": text })).map(|_| sent.to_string())); } + if let Some(text) = about.get(i).filter(|text| !text.is_empty()) { + ui.add(egui::Label::new(prose(text, 12.5).color(p.muted)).wrap()); + ui.add_space(2.0); + } } } - fn details(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, item: &Item, busy: bool, artifact: Option<&Result>) { + #[allow(clippy::too_many_arguments)] + fn details(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, p: &theme::Palette, item: &Item, busy: bool, artifact: Option<&Result>, part: Part) { let lang = self.lang; let dark = ui.visuals().dark_mode; let action = item.sdlc.as_ref().map(|s| s.action.clone()).unwrap_or_default(); @@ -443,47 +633,61 @@ impl App { // The brief comes from the work document (intent.md or PLAN.md) or the item's brief file. let doc = if !has_document(item) { None } else { match artifact { - None => { self.load_artifact(ctx, item); None } - Some(Err(error)) => { ui.label(RichText::new(error).color(theme::tone("blocked", dark).0).size(12.0)); None } - Some(Ok(doc)) if doc.sha.is_empty() => { ui.label(RichText::new(t(lang, "doc.loading")).color(p.muted).size(12.0)); None } + // A spread draws this twice a frame; only the reading side fetches. + None => { if part != Part::Act { self.load_artifact(ctx, item); } None } + Some(Err(error)) => { if part != Part::Act { ui.label(RichText::new(error).color(theme::tone("blocked", dark).0).size(12.0)); } None } + Some(Ok(doc)) if doc.sha.is_empty() => { if part != Part::Act { ui.label(RichText::new(t(lang, "doc.loading")).color(p.muted).size(12.0)); } None } Some(Ok(doc)) => Some(doc), } }; let has_doc = doc.is_some(); let [decide, summary, background, why, pick] = doc.map(glance).unwrap_or_default(); - // Situation (AS-IS), then one box with the question, what the agent will do (TO-BE), its pick and - // the reply line, then why. With a document all three always show; a missing part says so. - let missing = vec![t(lang, "doc.none").to_string()]; - let or_missing = |lines: &Vec| if lines.is_empty() && has_doc { missing.clone() } else { lines.clone() }; - bullets(ui, p, t(lang, "doc.background"), &or_missing(&background)); - // The box holds only what the human decides: the question and the agent's pick. The agent's waiting - // line joins only when the document asks nothing, or when the item is blocked (the line is the problem). - let mut asked: Vec = Vec::new(); - // The document's question and the agent's waiting line are often the same words; show each once. + // What a decision needs, in reading order: the question in its box, the situation (AS-IS), what the + // agent does once answered (TO-BE), why it is the human's call, then the agent's pick. With a + // document the situation and the why always show; a missing part says so. The agent's waiting line + // joins the question only when the document asks nothing, or when the item is blocked (the line + // is the problem). + // The same words often come twice (the question and the waiting line, the situation and the why): show each once. let key = |text: &str| text.split_whitespace().collect::().chars().take(40).collect::(); - let waiting_line = (!ask.is_empty() && (decide.is_empty() || item.turn.actor != "you")).then(|| clip(&ask, 160)); - for line in decide.into_iter().chain(pick).chain(waiting_line) { - if !asked.iter().any(|seen| key(seen) == key(&line)) { asked.push(line); } - } - let tobe: Vec = summary.into_iter().filter(|line| !asked.iter().any(|seen| key(seen) == key(line))).collect(); - if !label.is_empty() && !asked.is_empty() { - let (fg, bg) = theme::tone(&item.turn.actor, dark); - egui::Frame::new().fill(bg).corner_radius(CornerRadius::same(10)).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(RichText::new(label).color(fg).size(11.5).strong()); - for line in &asked { ui.label(RichText::new(line).size(13.5)).on_hover_text(&ask); } - }); - // What the agent will do (TO-BE) sits under the box, one muted line. - for line in &tobe { - ui.add(egui::Label::new(RichText::new(line).color(p.muted).size(12.5)).wrap()); + let mut seen: Vec = Vec::new(); + let mut fresh = |lines: Vec| -> Vec { + lines.into_iter().filter(|line| { let k = key(line); let new = !seen.contains(&k); if new { seen.push(k); } new }).collect() + }; + let waiting_line = (!ask.is_empty() && (decide.is_empty() || item.turn.actor != "you")).then(|| clip(&ask, 320)); + let question = fresh(decide.into_iter().chain(waiting_line).collect()); + let none = vec![t(lang, "doc.none").to_string()]; + let (no_background, no_why) = (has_doc && background.is_empty(), has_doc && why.is_empty()); + let untagged = |lines: Vec| lines.into_iter().map(untag).collect::>(); + let (background, tobe, why, pick) = (fresh(untagged(background)), fresh(untagged(summary)), fresh(why), fresh(pick)); + if part != Part::Act { + if !question.is_empty() && label.is_empty() { + bullets(ui, p, t(lang, "doc.summary"), &question); + } else if !question.is_empty() { + let (fg, bg) = theme::tone(&item.turn.actor, dark); + egui::Frame::new().fill(bg).corner_radius(CornerRadius::same(10)).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(label).color(fg).size(11.5).strong()); + for line in &question { ui.add(egui::Label::new(prose(line, 15.5)).wrap()).on_hover_text(&ask); } + }); + } + bullets(ui, p, t(lang, "doc.background"), if no_background { &none } else { &background }); + bullets(ui, p, t(lang, "doc.changes"), &tobe); + bullets(ui, p, t(lang, "doc.why"), if no_why { &none } else { &why }); + // The agent's pick and its reason stand apart: advice, not part of the question. + if !pick.is_empty() { + let heading = t(lang, "pick"); + egui::Frame::new().fill(p.accent.gamma_multiply(0.10)).corner_radius(CornerRadius::same(10)).inner_margin(Margin::symmetric(12, 8)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(heading).color(p.accent).size(11.5).strong()); + for line in &pick { + let text = line.strip_prefix(heading).and_then(|rest| rest.strip_prefix(':')).map(str::trim_start).unwrap_or(line); + ui.add(egui::Label::new(prose(text, 13.5)).wrap()); + } + }); } - } else { - asked.extend(tobe); - bullets(ui, p, t(lang, "doc.summary"), &asked); + ui.add_space(2.0); } - bullets(ui, p, t(lang, "doc.why"), &or_missing(&why)); - if let Some(doc) = doc { self.document(ui, p, item, doc); } - ui.add_space(2.0); + if part == Part::Read { return; } // A command the human runs (e.g. a VPN login asking for an OTP): one click opens a terminal with it typed. if !item.done && !item.run.is_empty() { ui.label(RichText::new(&item.run).monospace().color(p.muted).size(11.5)); @@ -496,16 +700,20 @@ impl App { }); } if !item.done && !item.choices.is_empty() { - ui.horizontal_wrapped(|ui| self.choice_buttons(ui, ctx, p, item, busy, true)); + // With the document's word on each option the choices stack, each over what it does. + let about = doc.map(|doc| options(doc, &item.choices)).unwrap_or_default(); + if about.is_empty() { ui.horizontal_wrapped(|ui| self.choice_buttons(ui, ctx, p, item, busy, true, &[])); } + else { self.choice_buttons(ui, ctx, p, item, busy, true, &about); } } if item.turn.actor == "you" && item.turn.kind == "answer" { // The agent's suggested answer fills the field until the human edits it; a new suggestion replaces an unedited one. let (draft, seed) = self.drafts.entry(item.id.clone()).or_insert_with(|| (item.suggest.clone(), item.suggest.clone())); if draft == seed && *seed != item.suggest { *draft = item.suggest.clone(); *seed = item.suggest.clone(); } - let field = ui.add(egui::TextEdit::singleline(draft).hint_text(t(lang, "reply.hint")).desired_width(f32::INFINITY).margin(Margin::symmetric(10, 7))); + // A fixed id: the automatic one shifts when the document arrives above it and the field would lose focus. + let field = ui.add(egui::TextEdit::singleline(draft).id_salt(("reply", &item.id)).hint_text(t(lang, "reply.hint")).desired_width(f32::INFINITY).margin(Margin::symmetric(10, 7))) + .on_hover_text(t(lang, "reply.help")); // Enter in the field sends, like the button; a single-line field loses focus on Enter. let entered = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); - ui.label(RichText::new(t(lang, "reply.help")).color(p.muted).size(11.5)); let text = draft.trim().to_string(); // The ticket sits beside the send button: the human checks it before answering. let send = ui.horizontal_wrapped(|ui| { @@ -522,7 +730,7 @@ impl App { if item.turn.actor == "you" && !item.turn.gate.is_empty() { if let Some(Ok(doc)) = artifact.filter(|a| a.as_ref().is_ok_and(|d| !d.sha.is_empty() && !d.gate.is_empty())) { let note = self.notes.entry(item.id.clone()).or_default(); - ui.add(egui::TextEdit::singleline(note).hint_text(t(lang, "approve.note")).desired_width(f32::INFINITY).margin(Margin::symmetric(10, 7))); + ui.add(egui::TextEdit::singleline(note).id_salt(("note", &item.id)).hint_text(t(lang, "approve.note")).desired_width(f32::INFINITY).margin(Margin::symmetric(10, 7))); if primary(ui, p, t(lang, "approve.button"), !busy).clicked() { let body = json!({ "id": item.id, "version": item.version, "gate": doc.gate, "sha": doc.sha, "words": note.trim() }); let done = t(lang, "approve.done"); @@ -530,34 +738,46 @@ impl App { } } } - if item.turn.actor == "blocked" && item.error.is_none() { - ui.label(RichText::new(t(lang, "fix.help")).color(p.muted).size(12.0)); - if primary(ui, p, &format!("⚡ {}", t(lang, "fix.button")), !busy).clicked() { - let (id, version) = (item.id.clone(), item.version.clone()); - self.act(ctx, &id.clone(), move |s| { - let data = client::post(s, "/api/item", json!({ "id": id, "version": version, "op": "fix" }))?; - let launch = data.get("launch").and_then(|v| v.as_str()).unwrap_or("queued").to_string(); - match launch.strip_prefix("failed: ") { - Some(reason) => Err(format!("{}{reason}", t(lang, "fix.failed"))), - None => Ok(t(lang, if launch == "started" { "fix.started" } else { "fix.queued" }).to_string()), - } - }); - } + if item.turn.actor == "blocked" && item.error.is_none() + && primary(ui, p, &format!("⚡ {}", t(lang, "fix.button")), !busy).on_hover_text(t(lang, "fix.help")).clicked() { + let (id, version) = (item.id.clone(), item.version.clone()); + self.act(ctx, &id.clone(), move |s| { + let data = client::post(s, "/api/item", json!({ "id": id, "version": version, "op": "fix" }))?; + let launch = data.get("launch").and_then(|v| v.as_str()).unwrap_or("queued").to_string(); + match launch.strip_prefix("failed: ") { + Some(reason) => Err(format!("{}{reason}", t(lang, "fix.failed"))), + None => Ok(t(lang, if launch == "started" { "fix.started" } else { "fix.queued" }).to_string()), + } + }); } if !(item.turn.actor == "you" && item.turn.kind == "answer") { ui.horizontal_wrapped(|ui| ticket_buttons(ui, &tickets(item))); } if busy { ui.spinner(); } - } - - /// The whole work document, folded away under the brief. - fn document(&mut self, ui: &mut egui::Ui, p: &theme::Palette, item: &Item, doc: &Artifact) { - egui::CollapsingHeader::new(RichText::new(t(self.lang, "doc.full")).color(p.muted).size(12.0)) - .id_salt(("full", &item.id)) - .show(ui, |ui| { - ui.label(RichText::new(&doc.file).color(p.muted).size(11.0)); - egui::ScrollArea::vertical().id_salt(("doc", &item.id)).max_height(320.0).show(ui, |ui| { ui.set_width(ui.available_width()); markdown(ui, p, &doc.markdown); }); + // The human's own memo on this item: kept with the app's settings, never sent to an agent. + if !item.done { + let memo = self.prefs.memos.entry(item.id.clone()).or_default(); + let dirty = &mut self.prefs_dirty; + egui::CollapsingHeader::new(RichText::new(t(lang, "memo")).color(p.muted).size(12.0)).id_salt(("memo", &item.id)) + .default_open(!memo.trim().is_empty()).show(ui, |ui| { + let field = egui::TextEdit::multiline(memo).hint_text(t(lang, "memo.hint")).desired_rows(2).desired_width(f32::INFINITY).margin(Margin::symmetric(10, 7)); + if ui.add(field).changed() { *dirty = true; } + }); + } + // The rest opens on demand: where the work stands in the sdlc loop, where the change lands, and the whole document. + let phase = phase_of(item, artifact); + if doc.is_some() || phase.is_some() || !item.repos.is_empty() { + egui::CollapsingHeader::new(RichText::new(t(lang, "more")).color(p.muted).size(12.0)).id_salt(("more", &item.id)).show(ui, |ui| { + if let Some(phase) = &phase { stepper(ui, p, lang, phase); } + if !item.repos.is_empty() { + ui.label(RichText::new(format!("{} {}", t(lang, "repos"), item.repos.join(", "))).color(p.muted).size(12.0)); + } + if let Some(doc) = doc { + ui.label(RichText::new(&doc.file).color(p.muted).size(11.0)); + egui::ScrollArea::vertical().id_salt(("doc", &item.id)).max_height(320.0).show(ui, |ui| { ui.set_width(ui.available_width()); markdown(ui, p, &doc.markdown); }); + } }); + } } fn load_artifact(&self, ctx: &egui::Context, item: &Item) { @@ -586,6 +806,32 @@ fn glance(doc: &Artifact) -> [Vec; 5] { [decide, or(field("What changes"), &["Summary"], 1), or(field("Background"), &["Understanding"], 1), or(field("Why"), &["Why this came up"], 1), pick] } +/// What each offered answer does, from the document's numbered Options list (`1. **label** — what it does`), +/// in the choices' order, each line matched to its choice by the bold label, not by place: a list in another +/// order must not put one option's words under another's button. Empty unless every choice has its own line +/// and the list has no others. +fn options(doc: &Artifact, choices: &[String]) -> Vec { + let sections = sections(&doc.markdown); + let Some((_, body)) = sections.iter().find(|(title, _)| { let title = title.to_lowercase(); title.starts_with("options") || title.starts_with("선택지") }) else { return Vec::new() }; + let norm = |text: &str| text.split_whitespace().collect::>().join(" ").to_lowercase(); + // (label, what it does) per numbered line; a line without a bold label has no label to match. + let lines: Vec<(Option, String)> = body.lines().filter_map(|line| { + let (number, rest) = line.trim_start().split_once(". ")?; + if number.is_empty() || !number.chars().all(|c| c.is_ascii_digit()) { return None; } + let (label, after) = match rest.trim_start().strip_prefix("**").and_then(|bold| bold.split_once("**")) { + Some((label, after)) => (Some(norm(label)), after), + None => (None, rest), + }; + let about = after.split_once(" — ").or_else(|| after.split_once(" - ")).map(|(_, about)| about).unwrap_or(""); + Some((label, clip(&about.replace("**", "").replace('`', ""), 240))) + }).collect(); + if lines.len() != choices.len() { return Vec::new(); } + choices.iter().map(|choice| { + let choice = norm(choice); + lines.iter().find(|(label, _)| label.as_deref() == Some(choice.as_str())).map(|(_, about)| about.clone()) + }).collect::>>().unwrap_or_default() +} + const PHASES: [&str; 6] = ["intent", "plan", "build", "evidence", "deliver", "done"]; /// The sdlc phase of an item, or of the ticket a brief is about (its At a glance `Phase:` line). @@ -621,10 +867,47 @@ fn stepper(ui: &mut egui::Ui, p: &theme::Palette, lang: Lang, phase: &str) { if i + 1 < PHASES.len() { ui.label(RichText::new("›").color(if i < now { p.accent } else { p.muted }).size(12.0)); } } }); - if let Some(next) = PHASES.get(now + 1) { - ui.label(RichText::new(format!("{} {} · {} {}", t(lang, "phase.now"), t(lang, &format!("phase.{}", PHASES[now])), t(lang, "phase.next"), t(lang, &format!("phase.{next}")))) - .color(p.muted).size(11.5)); +} + +/// Reading text: lines stand a little apart, as on a page. +fn prose(text: &str, size: f32) -> RichText { RichText::new(text).size(size).line_height(Some(size * 1.55)) } + +/// The top of a decision's page: where it belongs as a running head, what kind of decision it is, then its title. +fn heading(ui: &mut egui::Ui, p: &theme::Palette, dark: bool, lang: Lang, item: &Item) { + ui.horizontal(|ui| { + ui.label(RichText::new(meta_of(item)).color(p.muted).size(12.0)); + // Decisions the agent recommends no answer for stand out; the rest stay quiet. + 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), + }); + }); + ui.add(egui::Label::new(RichText::new(&item.title).size(19.0).strong().line_height(Some(27.0))).wrap()); + ui.add_space(6.0); +} + +/// The project folder and the ticket, as one muted line. +fn meta_of(item: &Item) -> String { + let mut meta = Vec::new(); + if let Some(project) = item.project.as_deref().filter(|p| !p.is_empty()) { + meta.push(PathBuf::from(project).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| project.to_string())); } + if let Some(link) = &item.link { meta.push(link.label.clone()); } + meta.join(" · ") +} + +/// 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); + 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. + let rect = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), row.rect.y_range()); + ui.interact(rect, egui::Id::new(("line", &item.id)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(hint).clicked() } fn ticket_buttons(ui: &mut egui::Ui, tickets: &[(String, String)]) { @@ -637,9 +920,7 @@ fn bullets(ui: &mut egui::Ui, p: &theme::Palette, title: &str, lines: &[String]) if lines.is_empty() { return; } ui.add_space(2.0); ui.label(RichText::new(title).color(p.accent).size(11.5).strong()); - for line in lines { - ui.horizontal_top(|ui| { ui.label(RichText::new("•").color(p.accent)); ui.add(egui::Label::new(RichText::new(line).size(13.0)).wrap()); }); - } + for line in lines { ui.add(egui::Label::new(prose(line, 13.5)).wrap()); } } fn sections(markdown: &str) -> Vec<(String, String)> { @@ -656,7 +937,7 @@ fn labeled(body: &str, label: &str) -> Option { body.lines().find_map(|line| { let rest = line.trim_start().strip_prefix("- ")?.trim_start().strip_prefix(&format!("**{label}:**"))?; let text = rest.replace("**", "").replace('`', "").trim().to_string(); - (!text.is_empty() && !text.eq_ignore_ascii_case("none") && !text.starts_with('<')).then(|| clip(&text, 160)) + (!text.is_empty() && !text.eq_ignore_ascii_case("none") && !text.starts_with('<')).then(|| clip(&text, 320)) }) } @@ -675,6 +956,16 @@ fn points(body: &str, limit: usize) -> Vec { lines.into_iter().take(limit).map(|l| clip(&l, 140)).collect() } +/// Drops a leading `…(AS-IS):` or `…(TO-BE):` tag: the heading over the line already says which it is. +fn untag(line: String) -> String { + for tag in ["(AS-IS):", "(TO-BE):"] { + if let Some((lead, rest)) = line.split_once(tag) { + if lead.chars().count() <= 12 { return rest.trim_start().to_string(); } + } + } + line +} + fn clip(text: &str, max: usize) -> String { let text = text.split_whitespace().collect::>().join(" "); if text.chars().count() <= max { text } else { format!("{}…", text.chars().take(max).collect::().trim_end()) } @@ -747,8 +1038,85 @@ fn main() -> Result<(), String> { // Without an icon eframe sets its own default as the window and Dock icon, over the bundle's. let icon = eframe::icon_data::from_png_bytes(include_bytes!("../AppIcon.png")).expect("valid app icon"); let options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default().with_title(t(lang, "title")).with_icon(icon).with_inner_size([440.0, 680.0]).with_min_inner_size([360.0, 420.0]), + viewport: egui::ViewportBuilder::default().with_title(t(lang, "title")).with_icon(icon).with_inner_size([600.0, 820.0]).with_min_inner_size([420.0, 480.0]), ..Default::default() }; eframe::run_native("sdlc-todo", options, Box::new(move |cc| Ok(Box::new(App::new(cc, launcher, lang))))).map_err(|e| e.to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + use client::{Link, Turn}; + + fn item(id: &str, actor: &str, kind: &str) -> Item { + Item { id: id.into(), title: id.into(), turn: Turn { actor: actor.into(), kind: kind.into(), gate: String::new() }, ..Default::default() } + } + fn ids(items: &[Item]) -> Vec<&str> { decision_queue(items).into_iter().map(|i| i.id.as_str()).collect() } + + #[test] + fn decisions_without_a_recommendation_lead_the_queue() { + let suggested = Item { suggest: "yes".into(), ..item("suggested", "you", "answer") }; + let picked = Item { choices: vec!["a".into(), "b".into()], pick: Some(1), ..item("picked", "you", "answer") }; + let pinned = Item { pin: true, ..item("pinned", "you", "answer") }; + let done = Item { done: true, ..item("done", "you", "answer") }; + let items = [suggested, picked, item("working", "agent", "agent"), item("blocked", "blocked", "blocked"), + item("open", "you", "answer"), item("gate", "you", "approve-plan"), pinned, done]; + assert_eq!(ids(&items), ["blocked", "open", "gate", "suggested", "picked"]); + } + + #[test] + fn decisions_for_one_ticket_stay_together() { + let on = |mut item: Item, url: &str| { item.link = Some(Link { label: url.into(), url: url.into() }); item }; + let items = [ + Item { suggest: "yes".into(), ..item("other", "you", "answer") }, + Item { suggest: "yes".into(), ..on(item("same", "you", "answer"), "https://t/browse/A-1") }, + on(item("first", "you", "approve-intent"), "https://t/browse/A-1"), + Item { choices: vec!["a".into(), "b".into()], pick: Some(1), ..on(item("choice", "you", "answer"), "https://t/browse/A-1") }, + ]; + // The ticket leads because one of its decisions has no recommendation; the one offering choices shows first. + assert_eq!(ids(&items), ["choice", "first", "same", "other"]); + } + + #[test] + fn option_notes_come_from_the_documents_numbered_list() { + let doc = |markdown: &str| Artifact { gate: String::new(), file: String::new(), markdown: markdown.into(), sha: "x".into() }; + let brief = doc("# D\n\n## At a glance\n- **Your call:** go?\n\n## 선택지 (번호로 답)\n1. **승인** (AI 권장) — 계획대로 `build`.\n2. **보류** — 진행하지 않고 대기.\n\n## Next\n1. unrelated — no\n"); + let choices = |labels: &[&str]| labels.iter().map(|l| l.to_string()).collect::>(); + assert_eq!(options(&brief, &choices(&["승인", "보류"])), ["계획대로 build.", "진행하지 않고 대기."]); + assert_eq!(options(&doc("## Options\n1. **a** - first\n2. **b**\n"), &choices(&["a", "b"])), ["first", ""]); + // A list that does not match the choices one to one says nothing rather than mislabel them. + assert!(options(&brief, &choices(&["승인", "보류", "취소"])).is_empty()); + assert!(options(&doc("## Summary\n1. a — b\n"), &choices(&["a"])).is_empty()); + } + + #[test] + fn option_notes_follow_the_choices_not_the_lists_order() { + let doc = |markdown: &str| Artifact { gate: String::new(), file: String::new(), markdown: markdown.into(), sha: "x".into() }; + let choices = |labels: &[&str]| labels.iter().map(|l| l.to_string()).collect::>(); + let swapped = doc("## Options\n1. **Hold it** — wait for QA.\n2. **Ship** (AI pick) — merge now.\n"); + // Labels match after trimming, collapsing spaces and ignoring case. + assert_eq!(options(&swapped, &choices(&["ship", " Hold it "])), ["merge now.", "wait for QA."]); + // A choice with no line of its own: nothing, not a guess by place. + assert!(options(&swapped, &choices(&["Ship", "Cancel"])).is_empty()); + } + + #[test] + fn a_leading_as_is_or_to_be_tag_is_dropped() { + assert_eq!(untag("지금(AS-IS): 열쇠가 넓다.".into()), "열쇠가 넓다."); + assert_eq!(untag("Planned (TO-BE): narrow it.".into()), "narrow it."); + // Only a short lead is a tag; the words inside a sentence stay. + 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 focus_follows_the_decision_then_takes_the_next_one() { + assert_eq!(settle(None, 0, &[]), None); + assert_eq!(settle(None, 0, &["a", "b"]), Some(0)); + // A new decision ahead does not move the one on screen. + assert_eq!(settle(Some("b"), 1, &["new", "a", "b"]), Some(2)); + // Answered: the decision now at its place shows; the last one falls back to the new end. + assert_eq!(settle(Some("a"), 0, &["b", "c"]), Some(0)); + assert_eq!(settle(Some("c"), 2, &["a", "b"]), Some(1)); + } +} diff --git a/todo/app/src/prefs.rs b/todo/app/src/prefs.rs new file mode 100644 index 0000000..5f26815 --- /dev/null +++ b/todo/app/src/prefs.rs @@ -0,0 +1,91 @@ +//! The human's own view settings and memos, kept beside the session file. Nothing here reaches +//! todo.md, the server or an agent. +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::Path; + +/// How far the window's contents scale. +pub const ZOOM: (f32, f32) = (0.8, 2.0); + +#[derive(Clone, Serialize, Deserialize)] +pub struct Prefs { + /// Scale of everything in the window. + #[serde(default = "default_zoom")] + pub zoom: f32, + /// The font file that leads; empty means the built-in one. + #[serde(default)] + pub font: String, + /// Memos by item id. + #[serde(default)] + pub memos: BTreeMap, +} + +fn default_zoom() -> f32 { 1.15 } + +impl Default for Prefs { + fn default() -> Prefs { Prefs { zoom: default_zoom(), font: String::new(), memos: BTreeMap::new() } } +} + +impl Prefs { + /// Reads the file; only a missing one means defaults. A file that cannot be read or does not parse + /// is set aside as `.bad` (the next save would otherwise overwrite its memos) and reported. + pub fn load(file: &Path) -> (Prefs, Option) { + let error = match std::fs::read_to_string(file) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return (Prefs::default(), None), + Err(error) => error.to_string(), + Ok(text) => match serde_json::from_str::(&text) { + Ok(mut prefs) => { prefs.zoom = prefs.zoom.clamp(ZOOM.0, ZOOM.1); return (prefs, None); } + Err(error) => error.to_string(), + }, + }; + let aside = file.with_extension("json.bad"); + let moved = match std::fs::rename(file, &aside) { Ok(()) => format!(" -> {}", aside.display()), Err(e) => format!(" (not set aside: {e})") }; + (Prefs::default(), Some(format!("{}: {error}{moved}", file.display()))) + } + + /// Writes a temporary file beside it and renames it over the real one, so a crash mid-write + /// leaves the old file whole rather than half-written JSON. + pub fn save(&self, file: &Path) -> Result<(), String> { + let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + let mut name = file.as_os_str().to_owned(); + name.push(".tmp"); + let temp = std::path::PathBuf::from(name); + std::fs::write(&temp, text).map_err(|e| format!("{}: {e}", temp.display()))?; + // Memos are the human's own words; keep the file to them, like the session file. + #[cfg(unix)] + { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(0o600)); } + std::fs::rename(&temp, file).map_err(|e| format!("{}: {e}", file.display())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saves_and_loads_and_sets_a_broken_file_aside() { + let dir = std::env::temp_dir().join(format!("sdlc-todo-prefs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("todo-app.json"); + assert!(Prefs::load(&file).1.is_none()); + let mut prefs = Prefs::default(); + prefs.memos.insert("abc123".into(), "ask QA first".into()); + prefs.zoom = 9.0; + prefs.save(&file).unwrap(); + assert!(!dir.join("todo-app.json.tmp").exists()); + let (loaded, error) = Prefs::load(&file); + assert!(error.is_none()); + assert_eq!(loaded.memos["abc123"], "ask QA first"); + assert_eq!(loaded.zoom, ZOOM.1); + std::fs::write(&file, "{ not json").unwrap(); + let (fallback, error) = Prefs::load(&file); + assert!(error.is_some() && fallback.memos.is_empty()); + assert!(dir.join("todo-app.json.bad").is_file() && !file.exists()); + // A file that is there but cannot be read is not "no file": it is reported and set aside too. + std::fs::remove_file(dir.join("todo-app.json.bad")).unwrap(); + std::fs::create_dir(&file).unwrap(); + let (_, error) = Prefs::load(&file); + assert!(error.is_some() && dir.join("todo-app.json.bad").is_dir() && !file.exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/todo/app/src/theme.rs b/todo/app/src/theme.rs index 2d59f66..31d6ef1 100644 --- a/todo/app/src/theme.rs +++ b/todo/app/src/theme.rs @@ -1,5 +1,6 @@ -//! Look and feel: system fonts with Hangul, a quiet light/dark palette, rounded cards, and tray icons. +//! Look and feel: a built-in Hangul font, paper tones in light and dark like a book's page, cards, and tray icons. use eframe::egui::{self, Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Margin, Stroke, TextStyle, Theme}; +use std::path::PathBuf; use std::sync::Arc; #[derive(Clone, Copy)] @@ -16,11 +17,11 @@ pub struct Palette { pub fn palette(dark: bool) -> Palette { if dark { - Palette { bg: hex(0x111113), card: hex(0x1b1b1f), card_hover: hex(0x222227), stroke: hex(0x2c2c33), - text: hex(0xededf0), muted: hex(0x9a9aa6), accent: hex(0x8b8aff), on_accent: hex(0x0f0f14) } + Palette { bg: hex(0x161412), card: hex(0x1f1c19), card_hover: hex(0x27231f), stroke: hex(0x36312b), + text: hex(0xebe5da), muted: hex(0xa39a8d), accent: hex(0x9a99ff), on_accent: hex(0x12100e) } } else { - Palette { bg: hex(0xf6f6f8), card: hex(0xffffff), card_hover: hex(0xfafafc), stroke: hex(0xe5e5ea), - text: hex(0x1c1c1f), muted: hex(0x6b6b76), accent: hex(0x5e5ce6), on_accent: hex(0xffffff) } + Palette { bg: hex(0xf1ede4), card: hex(0xfcfaf5), card_hover: hex(0xf6f2e9), stroke: hex(0xe3dccd), + text: hex(0x26221e), muted: hex(0x756c61), accent: hex(0x5553d4), on_accent: hex(0xffffff) } } } @@ -54,9 +55,48 @@ fn system_fonts() -> Vec<(&'static str, Vec)> { candidates.iter().filter_map(|path| std::fs::read(path).ok().map(|bytes| (*path, bytes))).collect() } -pub fn install(ctx: &egui::Context) { +/// The default text font, built in so every machine reads the same: Pretendard Regular (SIL OFL 1.1, +/// licence beside the file). System fonts follow it for glyphs it lacks. +const BUILT_IN: &[u8] = include_bytes!("../fonts/Pretendard-Regular.otf"); + +/// Other readable fonts with Hangul the human can pick when installed, by file name without spaces, dashes or case. +const KNOWN_FONTS: [(&str, &str); 11] = [ + ("applesdgothicneo", "Apple SD Gothic Neo"), ("malgun", "Malgun Gothic"), ("notosanscjk", "Noto Sans CJK"), + ("notosanskr", "Noto Sans KR"), ("nanumgothic", "NanumGothic"), ("nanumsquare", "NanumSquare"), + ("spoqahansansneo", "Spoqa Han Sans Neo"), ("suit", "SUIT"), + ("applegothic", "AppleGothic"), ("applemyungjo", "AppleMyungjo"), ("nanummyeongjo", "NanumMyeongjo"), +]; + +/// The known fonts found on this machine, as (name, file): the regular face of each. +pub fn fonts() -> Vec<(String, String)> { + let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).unwrap_or_default(); + let dirs: Vec = if cfg!(target_os = "macos") { + vec!["/System/Library/Fonts".into(), "/System/Library/Fonts/Supplemental".into(), "/Library/Fonts".into(), home.join("Library/Fonts")] + } else if cfg!(windows) { + vec!["C:\\Windows\\Fonts".into(), home.join("AppData\\Local\\Microsoft\\Windows\\Fonts")] + } else { + vec!["/usr/share/fonts/opentype/noto".into(), "/usr/share/fonts/noto-cjk".into(), "/usr/share/fonts/google-noto-cjk".into(), + "/usr/share/fonts/truetype/nanum".into(), home.join(".local/share/fonts"), home.join(".fonts")] + }; + let mut files: Vec = dirs.iter().filter_map(|dir| std::fs::read_dir(dir).ok()).flatten().filter_map(|entry| entry.ok().map(|e| e.path())) + .filter(|path| path.extension().and_then(|e| e.to_str()).is_some_and(|e| ["ttf", "otf", "ttc"].contains(&e.to_lowercase().as_str()))) + .collect(); + files.sort(); + let stem = |path: &PathBuf| path.file_stem().map(|s| s.to_string_lossy().to_lowercase().replace([' ', '-', '_'], "")).unwrap_or_default(); + KNOWN_FONTS.iter().filter_map(|(key, name)| { + let file = files.iter().find(|path| { let stem = stem(path); stem == *key || stem == format!("{key}regular") || stem == format!("{key}variable") })?; + Some((name.to_string(), file.to_string_lossy().to_string())) + }).collect() +} + +/// Sets fonts and the look. `font` is a file from `fonts()` that leads the text, or empty for the built-in one. +pub fn install(ctx: &egui::Context, font: &str) { let mut fonts = FontDefinitions::default(); - for (index, (path, bytes)) in system_fonts().into_iter().enumerate() { + // epaint panics on font data it cannot parse, and this path comes from the settings file: a truncated + // or replaced file would crash every launch, so it is checked first and skipped for the built-in one. + let chosen = (!font.is_empty()).then(|| std::fs::read(font).ok().map(|bytes| (font, bytes))).flatten() + .filter(|(_, bytes)| ttf_parser::Face::parse(bytes, 0).is_ok()); + for (index, (path, bytes)) in chosen.into_iter().chain([("Pretendard", BUILT_IN.to_vec())]).chain(system_fonts()).enumerate() { fonts.font_data.insert(path.to_string(), Arc::new(FontData::from_owned(bytes))); for family in [FontFamily::Proportional, FontFamily::Monospace] { let list = fonts.families.entry(family.clone()).or_default(); @@ -110,6 +150,15 @@ pub fn card(p: &Palette) -> egui::Frame { .inner_margin(Margin::symmetric(14, 12)) } +/// A decision's page: paper with wide margins, lifted a little off the desk. +pub fn page(p: &Palette) -> egui::Frame { + card(p).corner_radius(CornerRadius::same(8)).inner_margin(Margin::symmetric(26, 22)) + .shadow(egui::Shadow { offset: [0, 3], blur: 14, spread: 0, color: Color32::from_black_alpha(22) }) +} + +/// A list row: the card look, tighter, for one line that opens on demand. +pub fn row(p: &Palette) -> egui::Frame { card(p).corner_radius(CornerRadius::same(10)).inner_margin(Margin::symmetric(12, 8)) } + /// A 32×32 tray glyph: a rounded check box, with a dot when something needs the human. pub fn tray_icon(alert: bool, template: bool) -> tray_icon::Icon { let size = 32usize;