From 317f28a75cde329fc18c05622ad20550fc272ee7 Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:09:38 +0900 Subject: [PATCH 1/2] =?UTF-8?q?todo:=20=EC=B9=B8=EB=B0=98=20=EB=B3=B4?= =?UTF-8?q?=EB=93=9C=EB=A5=BC=20=EA=B8=B0=EB=B3=B8=20=ED=99=94=EB=A9=B4?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=E2=80=94=20=EC=B9=B4=EB=93=9C=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EB=B0=94=EB=A1=9C=20=EB=8B=B5=C2=B7=EC=8A=B9?= =?UTF-8?q?=EC=9D=B8,=20=ED=8B=B0=EC=BC=93=20=ED=8C=9D=EC=97=85,=20?= =?UTF-8?q?=EC=84=A0=ED=83=9D=20feed,=20=ED=8A=B8=EB=A0=88=EC=9D=B4=20?= =?UTF-8?q?=EC=95=B1=EC=9D=80=20=EB=B0=B0=EC=A7=80=EC=99=80=20=EB=B3=B4?= =?UTF-8?q?=EB=93=9C=20=EC=97=B4=EA=B8=B0=20(v3.0.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 보드: 열=sdlc 단계(일반·의도·계획·구현·검증·배포·완료), 줄=누구 차례(내 차례·다른 사람·막힘·에이전트). 같은 티켓 링크 항목은 한 카드로 묶고 답은 사람 차례 항목으로 보냄. - 결정 패널: 질문·AI 권장·배경·이유, 선택지 버튼·답변·자가 조치·intent/plan 승인(같은 /api/approve, SHA 고정), 내 차례 n/N 넘기기. - 티켓 열기: 화면 오른쪽 팝업 창 하나가 선택을 따라감(Jira는 iframe 거부). - feed(선택): SDLC_TODO_FEED 또는 할 일 파일 옆 todo-feed.json, GET /api/feed, payload·SSE의 feed. 사람 차례·막힘 카드는 feed가 숨기거나 완료로 옮기지 못함. - 트레이 앱: 창 없이 시작, 배지 유지, 클릭·실행 시 Chrome 앱 창으로 보드, 메뉴 보드 열기·목록 창 열기·끝내기, --background. - 메이저 이유: 기본 화면 변경, payload에 feed 추가. --- README.ko.md | 35 +- README.md | 35 +- VERSION | 2 +- log/changelog-v3.0.0.md | 29 ++ tests/todo-board.test.mjs | 159 ++++++++ tests/todo-page.test.mjs | 60 ++- tests/todo-web.test.mjs | 53 ++- todo/app/Cargo.lock | 1 + todo/app/Cargo.toml | 4 + todo/app/src/i18n.rs | 5 +- todo/app/src/main.rs | 131 +++++-- todo/locales/en.mjs | 85 ++++- todo/locales/ko.mjs | 82 ++++- todo/page/app.css | 274 +++++++++++++- todo/page/app.js | 42 ++- todo/page/board.js | 745 ++++++++++++++++++++++++++++++++++++++ todo/page/index.html | 123 ++++++- todo/status.mjs | 83 +++++ todo/todo.mjs | 2 + todo/web.mjs | 28 +- 20 files changed, 1916 insertions(+), 62 deletions(-) create mode 100644 log/changelog-v3.0.0.md create mode 100644 tests/todo-board.test.mjs create mode 100644 todo/page/board.js diff --git a/README.ko.md b/README.ko.md index 53afa43..d6b3d4b 100644 --- a/README.ko.md +++ b/README.ko.md @@ -194,21 +194,47 @@ Windows에서는 Git Bash나 WSL로 `sdlc.sh`를 실행하세요. ## 개인 to-do 여러 프로젝트의 할 일을 사람이 읽을 수 있는 `~/.sdlc/todo.md` 하나에 모읍니다. -트레이 앱, TUI, localhost 웹 페이지는 같은 파일을 실시간으로 보여 주고 고칩니다. +트레이 배지, TUI, localhost 웹 페이지(기본은 보드, 목록은 버튼 하나로 전환)는 같은 파일을 실시간으로 보여 주고 고칩니다. 다른 파일을 쓰려면 `SDLC_TODO`를 지정하세요. 이 선택 기능에는 Node 18+가 필요하고, 핵심 루프는 여전히 bash만 있으면 됩니다. ```bash cargo build --release --manifest-path ~/sdlc-kit/todo/app/Cargo.toml # 앱을 쓸 때 한 번 (Rust 1.88+) SDLC_TODO_LANG=ko bash ~/sdlc-kit/todo/app/install-macos.sh # macOS: ~/Applications에도 추가 -node ~/sdlc-kit/todo/todo.mjs # 앱 (앱을 빌드하지 않았으면 웹 링크가 있는 TUI) +node ~/sdlc-kit/todo/todo.mjs # 앱: 보드를 여는 트레이 배지 (앱을 빌드하지 않았으면 웹 링크가 있는 TUI) node ~/sdlc-kit/todo/todo.mjs --ui tui,web # tui, web, app 중 원하는 것 -node ~/sdlc-kit/todo/todo.mjs web --open # 웹 페이지만 열기 +node ~/sdlc-kit/todo/todo.mjs web --open # 웹 페이지만 열기 (보드) node ~/sdlc-kit/todo/todo.mjs add "Fix login ~/code/web https://acme.atlassian.net/browse/WEB-123" --by jira node ~/sdlc-kit/todo/todo.mjs next # 첫 Open 항목 node ~/sdlc-kit/todo/todo.mjs take --json # 작업자가 맡은 항목 하나와 그 답 ``` +웹 페이지는 **보드**로 열리고, 보드에서 바로 답하고 승인합니다. +열은 sdlc 단계입니다. 일반(sdlc 작업이 없는 항목, 있을 때만 보임), 의도, 계획, 구현, 검증, 배포, 그리고 최근 7일 완료(접혀 있음) 순이고, 이전 형식(`legacy`) 항목은 아래 접힌 상자에 있습니다. +행은 다른 화면과 같은 상태로 누구 차례인지 나눕니다. 내 차례, 다른 사람 답 대기, 막힘·환경 대기, 에이전트 차례이며, 에이전트가 작업 중인 카드에는 깜박이는 점이 붙습니다. +같은 티켓 링크를 가진 열린 항목은 카드 하나로 합칩니다. 14일 넘게 변화가 없는 카드는 토글 뒤에 숨기며, 내 차례·막힘·고정 카드는 숨기지 않습니다. +위쪽 띠에는 건수, 피드 상태와 알림, 마지막 업데이트, 언어 메뉴, 보기 전환 [보드] [목록] [실행] [건강]이 있고, [실행]과 [건강]은 피드가 있을 때만 보입니다. +화면 폭이 약 900px보다 좁으면 목록을 보여 주며, [목록] 보기는 이전 페이지의 기능을 모두 그대로 둡니다. + +카드를 누르면 결정 패널이 열립니다. 질문, 권장 선택지의 **AI 권장** 배지, 브리프의 배경과 이유, 선택지 버튼, 직접 답하기 칸, 의도·계획 승인(같은 SHA 묶음 `/api/approve`), 막힌 항목의 자가 조치가 보입니다. +선택지는 목록과 같은 보통 답변을 보내고, 카드 안에서 내 차례인 항목으로 갑니다. +"내 차례 n/N"은 ←/→ 또는 j/k로 내 카드를 넘기고, Esc로 패널을 닫습니다. 요청 중에는 버튼이 잠기고, 끝나면 토스트로 알리며, 실패하면 이유를 패널에 보여 줍니다. +**티켓 열기**는 링크를 탭이 아닌 화면 오른쪽에 붙은 팝업 창 하나로 열고, 다른 카드로 넘어가면 같은 창을 그 티켓으로 바꿉니다. Jira 같은 티켓 사이트는 iframe을 거부(X-Frame-Options)하므로 팝업을 씁니다. +새 보드 창이 열리면 이전 보드 창에 닫으라고 알립니다(BroadcastChannel). 브라우저는 스크립트가 닫을 수 있는 창(앱이 연 창 등)만 닫습니다. + +선택 기능인 **피드**로 다른 프로그램(티켓 공장 같은 자동화)이 보드에 자기 상태를 더할 수 있습니다. 서버는 `SDLC_TODO_FEED`, 없으면 할 일 파일 옆 `todo-feed.json`(기본 `~/.sdlc/todo-feed.json`, 최대 1MB)을 읽고 바뀌면 다시 읽습니다. 다른 `/api`처럼 토큰이 있어야 하는 `GET /api/feed`로 내주고, 모든 응답과 이벤트에 `feed`(읽지 못하면 `feedError`도)로 싣습니다. 파일이 없어도 보드는 똑같이 동작합니다. 스키마는 버전 1이고, 모든 필드는 선택이며 문자열은 모두 일반 텍스트로만 보입니다. + +```json +{"version": 1, "source": "factory", "generatedAt": "ISO time", + "status": {"state": "idle|running|held|off", "text": "", "lanes": {"busy": 1, "total": 3}, "nextRunAt": "ISO time"}, + "alerts": [{"level": "bad|warn|info", "text": "", "since": "ISO time"}], + "items": {"": {"slug": "", "column": "", "chip": "", "turn": "", "waitingText": "", "service": "", "nextStep": "", "updatedAt": "ISO time"}}, + "runs": [{"key": "", "label": "", "startedAt": "ISO time", "endedAt": "ISO time", "outcome": "ok|fail|unknown"}], + "health": [{"title": "", "rows": [{"label": "", "value": "", "level": "bad|warn|info"}]}]} +``` + +피드 항목은 티켓 라벨(`WEB-123`)로, 없으면 카드 안 항목의 sdlc slug로 카드에 맞춥니다. `column`(단계 또는 `done`)은 카드의 열을 바꿉니다. `turn`(`you`, `others`, `blocked`, `agent`)은 to-do 상태가 에이전트 차례나 다른 사람 대기일 때만 행을 바꾸므로, 피드가 내 차례나 막힘을 가리는 일은 없습니다. `chip`은 카드에 표시됩니다. [실행]은 `runs`를 하루 타임라인으로, [건강]은 `health`와 `alerts`를 보여 줍니다. 키트는 여전히 티켓 API를 부르지 않고, 파일은 피드를 만드는 쪽이 씁니다. + TUI와 웹 페이지는 영어나 한국어로 표시합니다. `--lang ko`(TUI 또는 `web`)를 주거나 `SDLC_TODO_LANG=ko`를 지정하세요. 플래그가 우선하고, 모르는 값이면 영어, 기본값도 영어입니다. TUI에서는 `L`, 웹 페이지에서는 언어 메뉴로 바꾸며 다시 시작하거나 새로 고칠 때까지 유지됩니다. 상태는 다음에 누가 움직일지 보여 줍니다. 내 차례(범위 승인·계획 승인·답변), 지금 작업 중(에이전트가 3분 안에 `working`으로 표시한 항목, 몇 분째·무슨 일인지 함께 보임), 에이전트 차례(아직 아무도 잡지 않음), 답변 전달됨 — 에이전트 수신 전, 시작 전, 막힘 — 조치 필요, 완료이며, 에이전트가 멈추는 행에는 그 사실을 적습니다. @@ -223,7 +249,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)은 메뉴 막대나 트레이에서 내 차례 건수를 보여 주고, 새로 생기면 알림을 띄우며, 내 차례인 결정을 책장처럼 한 번에 한 건씩 보여 줍니다. 승인·막힘, 그리고 에이전트 권장 답이 없는 질문이 먼저 나옵니다. 쪽 번호와 화살표는 창 아래에 있고, 좌우 화살표 키로도 넘깁니다. 질문·지금 상황·답하면 하려는 것·왜·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를 옮기면 다시 실행하세요. +고정 항목(`todo.mjs pin `, 예: 선택지로 켜고 끄는 설정)은 앱의 모든 탭 맨 위에 남고 내 차례 건수에 들어가지 않습니다. 앱(`todo/app`, macOS·Windows)은 창 없이 시작해 메뉴 막대나 트레이에서 내 차례 건수를 보여 주고, 새로 생기면 알림을 띄웁니다. 앱을 실행하거나 아이콘을 왼쪽 클릭하면 보드를 엽니다. macOS에 Google Chrome이 있으면 탭 없는 Chrome 앱 창(`--app`)으로, 없으면 기본 브라우저로 엽니다. 메뉴에는 보드 열기, 목록 창 열기, 끝내기가 있습니다. 로그인 항목처럼 트레이 아이콘만 띄우려면 `--background`나 `SDLC_TODO_BACKGROUND=1`을 쓰세요. 서버가 오프라인이면 클릭했을 때 그 이유와 함께 목록 창을 보여 줍니다. 대체 화면인 목록 창은 내 차례인 결정을 책장처럼 한 번에 한 건씩 보여 줍니다. 승인·막힘, 그리고 에이전트 권장 답이 없는 질문이 먼저 나옵니다. 쪽 번호와 화살표는 창 아래에 있고, 좌우 화살표 키로도 넘깁니다. 질문·지금 상황·답하면 하려는 것·왜·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를 하나 더하세요. @@ -251,6 +277,7 @@ Done에는 최근 30개를 두고, 넘치면 오래된 항목부터 같은 폴 키트는 토큰을 디스크에 쓰지 않습니다. 브라우저는 연 URL을 방문 기록에 남길 수 있으며, 프로세스가 종료되면 토큰도 효력을 잃습니다. 승인은 `sdlc.sh approve --human "" --sha `로 화면에 보여 준 바이트에 묶이며, 내용이 바뀌면 거부됩니다. 같은 사용자 계정으로 실행되는 프로그램은 기존 `--human`과 마찬가지로 이 보안 경계 밖에 있습니다. +보드와 피드는 이 모델을 바꾸지 않습니다. 피드는 믿을 수 없는 텍스트로 다루어 일반 텍스트로만 보여 주며, 카드를 옮기거나 표시를 붙일 수는 있어도 답하거나 승인하거나 내 차례를 가릴 수는 없습니다. ## v0.x에서 올리기 diff --git a/README.md b/README.md index c9a6d8d..df9e046 100644 --- a/README.md +++ b/README.md @@ -233,21 +233,47 @@ commit unless you said more. Windows: run `sdlc.sh` in Git Bash or WSL. ## Personal to-do Keep work across projects in one human-readable `~/.sdlc/todo.md`. -A tray app, a TUI and a localhost web page show and update the same file live. +A tray badge, a TUI and a localhost web page (a board by default, the list one click away) show and update the same file live. Set `SDLC_TODO` to use another file. This optional add-on requires Node 18+; the core loop still needs only bash. ```bash cargo build --release --manifest-path ~/sdlc-kit/todo/app/Cargo.toml # once, for the app (Rust 1.88+) SDLC_TODO_LANG=ko bash ~/sdlc-kit/todo/app/install-macos.sh # macOS: also add it to ~/Applications -node ~/sdlc-kit/todo/todo.mjs # the app (TUI with its web link if the app is not built) +node ~/sdlc-kit/todo/todo.mjs # the app: tray badge that opens the board (TUI with its web link if the app is not built) node ~/sdlc-kit/todo/todo.mjs --ui tui,web # any of tui, web, app -node ~/sdlc-kit/todo/todo.mjs web --open # web page only +node ~/sdlc-kit/todo/todo.mjs web --open # web page only (the board) node ~/sdlc-kit/todo/todo.mjs add "Fix login ~/code/web https://acme.atlassian.net/browse/WEB-123" --by jira node ~/sdlc-kit/todo/todo.mjs next # first Open item node ~/sdlc-kit/todo/todo.mjs take --json # one item a worker owns, with its replies ``` +The web page opens on the **board**, where you answer and approve without leaving it. +Columns follow the sdlc phase: General (items with no sdlc work, shown only when there are some), Intent, Plan, Build, Evidence, Deliver, then Done for the last 7 days, collapsed; older-format (`legacy`) items sit in a collapsed box below. +Rows say whose turn it is, from the same status as everywhere else: your turn, waiting on others, blocked, agent's turn; a pulsing dot marks a card an agent is working on. +Open items that share one ticket link are one card. Cards with no change for more than 14 days hide behind a toggle, unless they are your turn, blocked or pinned. +The top strip shows the counts, the feed status and alerts, the last update, the language menu, and the views Board, List, Runs and Health; Runs and Health appear only with a feed. +Below about 900 px wide the page shows the list, and the List view keeps everything the page did before. + +A card opens the decision panel: the question, an **AI pick** badge on the suggested choice, the brief's Background and Why, the choice buttons, a free reply box, Approve intent/plan through the same SHA-bound `/api/approve`, and Fix by agent on a block. +A choice sends the same ordinary reply as in the list, to the card's item whose turn is yours. +"Your turn n/N" pages through your cards with ←/→ or j/k, and Esc closes the panel. While a request runs the buttons wait; a toast confirms it, and a failure shows its reason in the panel. +**Open ticket** opens the link in one popup window docked to the right of the screen, not a tab, and points that window at the next card's ticket as you move on; ticket sites such as Jira refuse to be framed (X-Frame-Options). +A newly opened board asks older board windows to close (BroadcastChannel); a browser closes only windows scripts may close, such as the app's. + +An optional **feed** lets another program, such as a ticket factory, add its own status to the board. The server reads `SDLC_TODO_FEED`, else `todo-feed.json` beside the to-do file (`~/.sdlc/todo-feed.json` by default; up to 1 MB), watches it, serves it at `GET /api/feed` behind the token like every `/api` route, and sends it as `feed` (and `feedError` when unreadable) in every payload and event. Without the file the board works the same. Schema version 1; every field is optional and every string is shown as plain text: + +```json +{"version": 1, "source": "factory", "generatedAt": "ISO time", + "status": {"state": "idle|running|held|off", "text": "", "lanes": {"busy": 1, "total": 3}, "nextRunAt": "ISO time"}, + "alerts": [{"level": "bad|warn|info", "text": "", "since": "ISO time"}], + "items": {"": {"slug": "", "column": "", "chip": "", "turn": "", "waitingText": "", "service": "", "nextStep": "", "updatedAt": "ISO time"}}, + "runs": [{"key": "", "label": "", "startedAt": "ISO time", "endedAt": "ISO time", "outcome": "ok|fail|unknown"}], + "health": [{"title": "", "rows": [{"label": "", "value": "", "level": "bad|warn|info"}]}]} +``` + +A feed item matches a card by its ticket label (`WEB-123`), else by a member's sdlc slug. `column` (a phase or `done`) moves the card; `turn` (`you`, `others`, `blocked` or `agent`) changes its row only while the to-do says agent's or others' turn, so a feed never hides your turn or a block; `chip` is shown on the card. Runs draws `runs` as a day timeline; Health shows `health` and `alerts`. The kit still calls no ticket API: the producer writes the file. + 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), 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. @@ -262,7 +288,7 @@ An agent working on an item right now marks it with `todo.mjs working ["ste 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 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. +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) starts with no window: it sits in the menu bar or tray with a count of items that need you and notifies you when one appears. Launching it or a left click on the icon opens the board, in a Google Chrome app window (`--app`, no tabs) on macOS when Chrome is installed, otherwise in the default browser; its menu has Open board, Open list window and Quit. `--background` or `SDLC_TODO_BACKGROUND=1` starts it in the tray only, for a login item. While the server is offline a click shows the list window with the reason. The list window, the fallback, 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`. @@ -290,6 +316,7 @@ Web access stays on `127.0.0.1`, with Host/Origin checks and a per-run token hel The kit never writes the token to disk; the browser may keep the opened URL in history. The token dies when the process exits. Approve binds the bytes shown through `sdlc.sh approve --human "" --sha `; changed bytes are refused. Same-user programs are outside this boundary, as with `--human`. +The board and the feed change none of this. The feed is untrusted text: the page shows it as plain text, and it can move or label a card but never answer, approve or hide your turn. ## Upgrading from v0.x diff --git a/VERSION b/VERSION index 90efbd4..4a36342 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.28.0 +3.0.0 diff --git a/log/changelog-v3.0.0.md b/log/changelog-v3.0.0.md new file mode 100644 index 0000000..366406c --- /dev/null +++ b/log/changelog-v3.0.0.md @@ -0,0 +1,29 @@ +# v3.0.0: The to-do opens on a board where you answer and approve, and the tray app opens it + +## Problem + +The web page and the tray app showed one long list or one decision at a time. With 40 open items across tickets, phases and agents, the human could not see at a glance what waited on them, what an agent was doing, and where each piece of work stood, and a ticket with a decision item showed up twice. Factory or automation status (lanes busy, runs, failures) had no place on the page, so it lived in another tool. + +This release is major because the default screen changed: the page opens on the board instead of the list, and the tray app no longer opens its own window. The payload and SSE frames also carry the new `feed` and `feedError` fields. + +## Changes + +- **`todo/page/board.js`, `todo/page/index.html`, `todo/page/app.css`, `todo/page/app.js`:** the page's default view is a kanban board. Columns are sdlc phases (General for items without sdlc work, then intent, plan, build, evidence, deliver, and a collapsed Done for the last 7 days; `legacy` items sit in a collapsed box). Rows are whose turn it is (your turn, waiting on others, blocked, agent's turn), and a pulsing dot marks a card an agent works on. A top strip shows counts, the feed status and alerts, the last update, the language menu and the views Board, List, Runs and Health (the last two only with a feed). Below about 900 px the page shows the list; the List view keeps every previous feature. A card opens a decision panel with the question, an AI pick badge on the suggested choice, the brief's Background and Why, the choice buttons (the same ordinary reply as before), a free reply box, Approve intent/plan through the same SHA-bound `/api/approve`, and Fix by agent on a block; "Your turn n/N" pages with ←/→ or j/k and Esc closes. A toast confirms a sent answer and a failure shows its reason in the panel. Open ticket opens the link in one popup window docked to the screen's right edge and re-targets it for the next card, because ticket sites such as Jira refuse frames. A newer board window asks older ones to close over BroadcastChannel. +- **`todo/status.mjs`:** `boardCards` builds the cards: open items that share one ticket link merge into one card, done items of the last 7 days get one card each, and cards with no change for more than 14 days are marked stale unless they are your turn, blocked or pinned. `targetOf` picks the member an answer goes to (your turn first, preferring offered choices, then a gate, then an item outside sdlc). `feedEntryOf` matches a feed item by ticket label, else by sdlc slug. +- **`todo/web.mjs`:** an optional feed is read from `SDLC_TODO_FEED`, else `todo-feed.json` beside the to-do file (`~/.sdlc/todo-feed.json` by default; at most 1 MB), watched for changes, served at token-protected `GET /api/feed`, and included as `feed` (and `feedError` when unreadable) in every payload and SSE frame. Schema v1, every field optional, every string shown as text: `status`, `alerts`, `items` keyed by ticket label or sdlc slug (`column`, `chip`, `turn`, `waitingText`, `service`, `nextStep`, `updatedAt`), `runs` (a day timeline) and `health`. `column` moves a card; `turn` changes its row only when the to-do says agent's or others' turn, so a feed never hides the human's turn or a block. The kit still calls no ticket API; a producer, such as a ticket factory, writes the file. +- **`todo/app/src/main.rs`, `todo/app/src/i18n.rs`, `todo/app/Cargo.toml`:** the tray app starts with no window and keeps the badge with the your-turn count. Launching it or a left click opens the board in a Google Chrome app window (`--app`, no tabs) on macOS when Chrome is installed, otherwise in the default browser. The menu is Open board, Open list window (the previous window, kept as the fallback) and Quit. `--background` or `SDLC_TODO_BACKGROUND=1` starts with the tray icon only, for login items. While the server is offline a click shows the list window with the reason. On macOS the badge updates through the main dispatch queue, because a hidden window gets no frames. `install-macos.sh` is unchanged. +- **`todo/todo.mjs`, `todo/locales/en.mjs`, `todo/locales/ko.mjs`:** help text for the tray and `SDLC_TODO_BACKGROUND`; board, panel, feed, runs and health messages in both languages. +- **`README.md`, `README.ko.md`:** the board, the feed and its schema, and the tray app's new behaviour; the security model is unchanged (127.0.0.1, per-run token, Host/Origin checks) and the feed is untrusted text. + +## Verification + +- `node --test tests/*.test.mjs`: 232 tests, 226 pass, 6 fail, all timing failures under machine load (`HTTP request timed out`, `timed out waiting for TUI state`, `timed out waiting for lock`). Rerun alone, 5 of the 6 pass. The sixth, "S14: twenty parallel CLI writers…", also fails on the previous release commit 518a1d6, and this release does not touch the lock code. +- New tests cover board card grouping, lane and column with and without a feed, a feed that must not hide a card needing the human or move an open card to done, feed endpoint auth, a missing or invalid feed, the single-window rule, and test helpers that never read the real feed. `tests/todo-board.test.mjs`, `tests/todo-page.test.mjs` and `tests/todo-web.test.mjs` pass. +- `todo/app`: `cargo build --release` passes, and `cargo test --release --offline` passes 8 tests. +- Live QA used a copy of a real 40-item list, a real factory feed and Chromium at 1440×900 in light and dark, with zero console errors. Checked: + - a ticket and its decision item show as one card in plan × your turn, and a choice click appended the reply to the decision item; + - a feed change moved a card without a reload, and the selection stayed; + - one ticket popup followed three selections; + - the page falls back to the list below 900 px. +- An independent review found two must-fix defects before release: a feed column could hide a card that needed the human, and the single-window rule closed list tabs. Both are fixed and tested. +- `todo/AGENT.md` and the prompts are unchanged, so the `tests/selftest.sh` word budgets are unaffected. The full `tests/selftest.sh` was not run locally, because a local hook blocks its `git reset --hard` step. diff --git a/tests/todo-board.test.mjs b/tests/todo-board.test.mjs new file mode 100644 index 0000000..fe2a8e6 --- /dev/null +++ b/tests/todo-board.test.mjs @@ -0,0 +1,159 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import * as core from '../todo/core.mjs'; +import { boardCards, feedEntryOf, targetOf } from '../todo/status.mjs'; + +const now = Date.parse('2026-11-19T12:00'); +// Items as the board receives them: parsed by core from a to-do file. +function itemsOf(t, body) { + const root = mkdtempSync(join(tmpdir(), 'sdlc-todo-board-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const file = join(root, 'todo.md'); + writeFileSync(file, `# To-do\n\n## Open\n\n${body}\n`); + return core.load(file).items; +} +const ticket = `- [ ] [Decision D99] T-1 · which textbook + - link: [T-1](https://tracker.invalid/browse/T-1) + - waiting: 1) grade 9 · 2) class + - choices: grade 9 | class + - pick: 1 + - 2026-11-18 12:36 factory: added + +- [ ] T-1 which textbook + - project: /tmp/project + - link: [T-1](https://tracker.invalid/browse/T-1) + - sdlc: t-1-textbook · plan · READY — plan not approved + - waiting: answer in D99 + - repos: api + - 2026-11-18 12:38 agent: started t-1-textbook + +- [ ] T-2 agent work + - link: [T-2](https://tracker.invalid/browse/T-2) + - sdlc: t-2-work · build · READY — build next + - 2026-11-18 09:00 agent: started t-2-work + +- [ ] T-3 blocked work + - link: [T-3](https://tracker.invalid/browse/T-3) + - sdlc: t-3-work · evidence · BLOCKED — dev database unreachable + - 2026-11-18 09:00 agent: started t-3-work + +- [ ] [Notice] factory line + - waiting: read the morning report + - 2026-11-19 08:31 agent: waiting — read the morning report + +- [ ] Old idea + - 2026-10-01 10:00 human: added + +- [ ] Pinned setting + - others: setting · judge on + - pin: yes + - 2026-10-01 10:00 agent: pinned`; + +test('board: items sharing a ticket link are one card in the work item\'s column, answered on the item with choices', t => { + const cards = boardCards(itemsOf(t, ticket), null, now); + const t1 = cards.filter(card => card.link?.label === 'T-1'); + assert.equal(t1.length, 1, 'one card for the ticket'); + assert.equal(t1[0].members.length, 2); + assert.equal(t1[0].column, 'plan', 'the column comes from the member with an sdlc phase'); + assert.equal(t1[0].lane, 'you'); + assert.match(t1[0].target.title, /Decision D99/, 'answers go to the decision, not the work item'); + assert.equal(targetOf(t1[0].members).id, t1[0].target.id); + const notice = cards.find(card => card.target.title.startsWith('[Notice]')); + assert.equal(notice.column, 'general', 'an item without an sdlc phase sits in the general column'); + assert.equal(notice.lane, 'you'); + assert.equal(cards.find(card => card.link?.label === 'T-3').lane, 'blocked'); + assert.equal(cards.find(card => card.link?.label === 'T-2').lane, 'agent'); +}); + +test('board: the most urgent member decides the lane: you, then blocked, then others, then agent', t => { + const items = itemsOf(t, `- [ ] T-9 work + - link: [T-9](https://tracker.invalid/browse/T-9) + - sdlc: t-9 · deliver · BLOCKED — stg down + - 2026-11-18 09:00 agent: started t-9 + +- [ ] T-9 waiting on QA + - link: [T-9](https://tracker.invalid/browse/T-9) + - others: QA + - 2026-11-18 09:00 agent: waiting on others — QA`); + const [card] = boardCards(items, null, now); + assert.equal(card.lane, 'blocked'); + assert.equal(card.column, 'deliver'); + assert.equal(card.target.sdlc?.slug, 't-9', 'a blocked member is the target when nobody waits on you'); +}); + +test('board: a feed moves agent and others cards but never hides your turn or a block', t => { + const items = itemsOf(t, ticket); + const feed = { version: 1, items: { + 'T-1': { column: 'deliver', turn: 'agent', chip: 'dev' }, + 'T-2': { column: 'evidence', turn: 'others', chip: 'stg' }, + 't-3-work': { turn: 'agent', column: 'deliver' }, + 'Pinned setting': { turn: 'nobody' } + } }; + const cards = boardCards(items, feed, now), by = label => cards.find(card => card.link?.label === label); + assert.equal(by('T-1').lane, 'you', 'your turn from the to-do file stays'); + assert.equal(by('T-1').column, 'plan', 'the feed column does not move your turn'); + assert.equal(by('T-1').chip, 'dev'); + assert.equal(by('T-2').lane, 'others', 'an agent card follows the feed turn'); + assert.equal(by('T-2').column, 'evidence'); + assert.equal(by('T-3').lane, 'blocked', 'a block from the to-do file stays, matched by slug'); + assert.equal(by('T-3').column, 'evidence', 'nor a block'); + const pinned = cards.find(card => card.pinned); + assert.equal(pinned.lane, 'others', 'an unknown feed turn is ignored'); + const without = boardCards(items, null, now); + assert.equal(without.find(card => card.link?.label === 'T-2').column, 'build'); + assert.equal(without.find(card => card.link?.label === 'T-2').chip, ''); +}); + +test('board: a feed never moves a card that needs you or is blocked, and never moves an open card to Done', t => { + const items = itemsOf(t, `${ticket} + +- [ ] T-9 pick one + - link: [T-9](https://tracker.invalid/browse/T-9) + - waiting: which? + - choices: a | b + - 2026-11-18 09:00 agent: waiting — which?`); + const feed = { items: { 'T-9': { column: 'done' }, 'T-1': { column: 'build' }, 'T-3': { column: 'intent' }, 'T-2': { column: 'done' } } }; + const by = label => boardCards(items, feed, now).find(card => card.link?.label === label); + assert.deepEqual([by('T-9').lane, by('T-9').column, by('T-9').needsHuman], ['you', 'general', true]); + assert.equal(by('T-1').column, 'plan', 'your turn keeps its sdlc column'); + assert.equal(by('T-3').column, 'evidence', 'a block keeps its sdlc column'); + assert.equal(by('T-2').column, 'build', 'an open agent card never moves to Done'); + assert.ok(boardCards(items, feed, now).filter(card => card.column === 'done').every(card => card.target.done)); +}); + +test('board: feed entries match by ticket label, then slug key, then slug field; junk is ignored', t => { + const items = itemsOf(t, ticket), members = items.filter(item => item.link?.label === 'T-2'); + assert.equal(feedEntryOf({ items: { 'T-2': { chip: 'a' } } }, members).chip, 'a'); + assert.equal(feedEntryOf({ items: { 't-2-work': { chip: 'b' } } }, members).chip, 'b'); + assert.equal(feedEntryOf({ items: { other: { slug: 't-2-work', chip: 'c' } } }, members).chip, 'c'); + for (const feed of [null, 'text', [], { items: [] }, { items: { 'T-2': 'x' } }, { items: { 'T-2': ['x'] } }]) { + assert.equal(feedEntryOf(feed, members), null, JSON.stringify(feed)); + } + assert.doesNotThrow(() => boardCards(items, { items: { 'T-1': { column: 42, turn: {}, chip: ['x'], updatedAt: 'soon' } } }, now)); + const card = boardCards(items, { items: { 'T-1': { column: 42, chip: ['x'] } } }, now).find(c => c.link?.label === 'T-1'); + assert.equal(card.column, 'plan'); + assert.equal(card.chip, ''); +}); + +test('board: cards quiet for over 14 days are stale unless pinned or needing you; done shows for 7 days', t => { + const items = itemsOf(t, `${ticket} + +## Done + +- [x] ~~Shipped yesterday~~ + - 2026-11-18 10:00 agent: done — shipped + +- [x] ~~Shipped last month~~ + - 2026-10-10 10:00 agent: done — shipped`); + const cards = boardCards(items, null, now); + assert.equal(cards.find(card => card.target.title === 'Old idea').stale, true); + assert.equal(cards.find(card => card.pinned).stale, false, 'pinned stays visible'); + assert.ok(cards.filter(card => card.lane === 'you').every(card => !card.stale)); + const done = cards.filter(card => card.column === 'done'); + assert.deepEqual(done.map(card => card.target.title), ['Shipped yesterday']); + const fresh = boardCards(items, { items: { 'Old idea': {} } }, now).find(card => card.target.title === 'Old idea'); + assert.equal(fresh.stale, true, 'a feed entry that does not match keeps the card stale'); +}); diff --git a/tests/todo-page.test.mjs b/tests/todo-page.test.mjs index 1bf1e42..53bcbba 100644 --- a/tests/todo-page.test.mjs +++ b/tests/todo-page.test.mjs @@ -33,7 +33,9 @@ for (const mode of ['light', 'dark']) { } } assert.ok(contrast(colors.bad, colors['bad-bg']) >= 4.5, `${mode} error notice text`); - for (const [foreground, background] of [['accent', 'highlight'], ['busy', 'busy-bg'], ['ok', 'ok-bg'], ['muted', 'open-bg'], ['bad', 'bad-bg'], ['busy', 'paper'], ['busy', 'highlight']]) { + // Board surfaces: the canvas around it, cards, and the tint of the your-turn lane. + for (const [foreground, background] of [['accent', 'highlight'], ['busy', 'busy-bg'], ['ok', 'ok-bg'], ['muted', 'open-bg'], ['bad', 'bad-bg'], ['busy', 'paper'], ['busy', 'highlight'], + ['ink', 'card'], ['muted', 'card'], ['muted', 'canvas'], ['muted', 'lane-you'], ['accent', 'lane-you'], ['bad', 'lane-you'], ['busy', 'lane-you'], ['ok', 'card'], ['muted', 'paper']]) { const ratio = contrast(colors[foreground], colors[background]); assert.ok(ratio >= 4.5, `${mode} status --${foreground} on --${background}: ${ratio.toFixed(3)}:1 < 4.5:1`); } @@ -570,3 +572,59 @@ test('narrow keeps the modal; resizing moves the selection between modal and pan p.setWide(true); assert.equal(p.nodes.get('detail-title').textContent, 'Queued task', 'the selection is kept'); }); + +test('single window: a newer tray window asks older ones to close; its own or an older message does not', () => { + const p = page(); + const channels = []; + let closed = 0; + p.context.close = () => { closed++; }; + p.context.FakeChannel = class { + constructor(name) { this.name = name; this.listeners = []; channels.push(this); } + addEventListener(type, listener) { if (type === 'message') this.listeners.push(listener); } + // Like BroadcastChannel: every other channel of the same name receives it, the sender does not. + postMessage(data) { for (const other of channels) if (other !== this && other.name === this.name) for (const fn of other.listeners) fn({ data }); } + }; + const older = vm.runInContext('singleWindow(FakeChannel, true)', p.context); + assert.equal(older.name, 'sdlc-todo-board'); + assert.equal(closed, 0, 'the first page stays'); + vm.runInContext('singleWindow(FakeChannel, true)', p.context); + assert.equal(closed, 1, 'the older page closes when a newer one opens'); + for (const fn of older.listeners) fn({ data: { type: 'board-open', at: 0 } }); + assert.equal(closed, 1, 'a message from before this page was born is ignored'); + assert.equal(vm.runInContext('singleWindow(undefined, true)', p.context), null, 'no BroadcastChannel: nothing happens'); + // A page that is not a tray window neither announces itself nor closes. + assert.equal(vm.runInContext('singleWindow(FakeChannel, false)', p.context), null); + assert.equal(vm.runInContext('appWindow', p.context), false, 'no app=1 in the fragment'); + assert.equal(channels.length, 2); + // An unsent draft or a request in flight keeps the older window open. + vm.runInContext(`drafts.set('x', { reply: 'half an answer', words: '', seed: '' })`, p.context); + vm.runInContext('singleWindow(FakeChannel, true)', p.context); + assert.equal(closed, 1, 'a draft keeps the window'); + vm.runInContext(`drafts.clear(); todoPage.addBusyCheck(() => true)`, p.context); + vm.runInContext('singleWindow(FakeChannel, true)', p.context); + assert.equal(closed, 1, 'a busy view keeps the window'); +}); + +test('single window: only a fragment with app=1 marks a tray window; the token is read the same', () => { + const app = page('#t=0123456789abcdef0123456789abcdef&app=1'); + assert.equal(vm.runInContext('appWindow', app.context), true); + assert.equal(vm.runInContext('token', app.context), '0123456789abcdef0123456789abcdef'); + assert.equal(vm.runInContext('appWindow', page('#t=0123456789abcdef0123456789abcdef').context), false); +}); + +test('board hook: views subscribe to snapshots and read the feed the server sent', () => { + const p = page(); + vm.runInContext(` + var calls = 0; + todoPage.subscribe(() => calls++); + apply({ items: [], file: '/tmp/todo.md', feed: { source: 'line' }, feedError: '' }); + `, p.context); + assert.equal(vm.runInContext('calls', p.context), 1); + assert.equal(vm.runInContext('todoPage.feed.source', p.context), 'line'); + vm.runInContext(`apply({ items: [], file: '/tmp/todo.md' })`, p.context); + assert.equal(vm.runInContext('todoPage.feed.source', p.context), 'line', 'a snapshot without a feed field keeps the feed'); + vm.runInContext(`apply({ items: [], file: '/tmp/todo.md', feed: null, feedError: 'feed is not valid JSON' })`, p.context); + assert.equal(vm.runInContext('todoPage.feed', p.context), null); + assert.equal(vm.runInContext('todoPage.feedError', p.context), 'feed is not valid JSON'); + assert.equal(vm.runInContext('calls', p.context), 3); +}); diff --git a/tests/todo-web.test.mjs b/tests/todo-web.test.mjs index 4a1275b..0ae25a6 100644 --- a/tests/todo-web.test.mjs +++ b/tests/todo-web.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import http from 'node:http'; import { createHash } from 'node:crypto'; import { execFileSync } from 'node:child_process'; -import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, symlinkSync, realpathSync, statSync, existsSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, symlinkSync, realpathSync, statSync, existsSync } from 'node:fs'; import { tmpdir, networkInterfaces } from 'node:os'; import { dirname, join, resolve, relative as pathRelative } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -41,7 +41,8 @@ async function web(t, options = {}) { const root = mkdtempSync(join(tmpdir(), 'sdlc-todo-web-')); const file = join(root, 'todo.md'); let opened; - const server = await startWeb({ file, kit, port: 0, open: false, onUrl(url) { opened = url; }, ...options }); + // A temp feed: no test reads or watches ~/.sdlc/todo-feed.json. + const server = await startWeb({ file, kit, port: 0, open: false, onUrl(url) { opened = url; }, feed: join(root, 'feed.json'), ...options }); t.after(async () => { await server.close(); rmSync(root, { recursive: true, force: true }); }); const url = new URL(opened || server.url); const token = new URLSearchParams(url.hash.slice(1)).get('t'); @@ -694,7 +695,7 @@ if [ "$1" = status ]; then printf '{"store":"%s/.sdlc","features":[{"slug":"probe","phase":"intent","state":"NEEDS-HUMAN","action":"approve intent --human"}]}\\n' "$PWD" fi `); - const server = await startWeb({ file: ctx.file, kit: stub, onUrl() {} }); + const server = await startWeb({ file: ctx.file, kit: stub, onUrl() {}, feed: join(ctx.root, 'feed.json') }); t.after(() => server.close()); const url = new URL(server.url), token = new URLSearchParams(url.hash.slice(1)).get('t'); const target = { ...ctx, url, token }; @@ -737,7 +738,7 @@ test('session file shares the running server with the owner only and goes away o t.after(() => rmSync(root, { recursive: true, force: true })); const file = join(root, 'todo.md'), session = join(root, 'todo-web.json'); await core.add(file, 'Needs nothing yet'); - const server = await startWeb({ file, kit, port: 0, open: false, onUrl() {}, session }); + const server = await startWeb({ file, kit, port: 0, open: false, onUrl() {}, session, feed: join(dirname(file), 'feed.json') }); const stored = JSON.parse(readFileSync(session, 'utf8')); assert.match(stored.token, /^[a-f0-9]{32}$/); assert.equal(stored.pid, process.pid); @@ -809,3 +810,47 @@ test('artifact syncs only the requested item, not every open sdlc item', async t assert.equal(model.items.find(i => i.id === item.id).sdlc.state, 'NEEDS-HUMAN', 'the shown item is synced'); assert.equal(model.items.find(i => i.id === other.id).sdlc.state, '', 'another item keeps its last state (no status call)'); }); + +test('feed: without SDLC_TODO_FEED the feed sits beside the list, never in ~/.sdlc for another list', async () => { + const { feedPath } = await import('../todo/web.mjs'); + const saved = process.env.SDLC_TODO_FEED; + delete process.env.SDLC_TODO_FEED; + try { assert.equal(feedPath('/tmp/x/todo.md'), join('/tmp/x', 'todo-feed.json')); } + finally { if (saved !== undefined) process.env.SDLC_TODO_FEED = saved; } +}); + +test('feed: /api/feed needs the token like every /api route; a missing feed is no feed', async t => { + const dir = mkdtempSync(join(tmpdir(), 'sdlc-todo-feed-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const ctx = await web(t, { feed: join(dir, 'missing', 'feed.json') }); + for (const token of [null, '0'.repeat(32)]) assert.equal((await request(ctx, '/api/feed', { token })).status, 403); + const response = await request(ctx, '/api/feed'); + assert.equal(response.status, 200, response.text); + assert.deepEqual(response.json, { feed: null, error: '' }); + const snapshot = await request(ctx, '/api/items'); + assert.equal(snapshot.json.feed, null); + assert.equal(snapshot.json.feedError, undefined); +}); + +test('feed: an invalid feed says so, and an atomic replacement reaches the live stream', async t => { + const dir = mkdtempSync(join(tmpdir(), 'sdlc-todo-feed-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const feed = join(dir, 'feed.json'); + writeFileSync(feed, '{"version":1,"items":'); + const ctx = await web(t, { feed }); + assert.deepEqual((await request(ctx, '/api/feed')).json, { feed: null, error: 'feed is not valid JSON' }); + assert.equal((await request(ctx, '/api/items')).json.feedError, 'feed is not valid JSON'); + const waitFor = eventStream(ctx, t); + await waitFor(value => Array.isArray(value.items)); + const replaced = waitFor(value => value.feed?.source === 'line', 3000); + writeFileSync(`${feed}.tmp`, JSON.stringify({ version: 1, source: 'line', status: { state: 'running' } })); + renameSync(`${feed}.tmp`, feed); + const frame = await replaced; + assert.equal(frame.feedError, undefined); + assert.deepEqual((await request(ctx, '/api/feed')).json.feed.status, { state: 'running' }, 'text stays as written; the page shows it as text'); + const gone = waitFor(value => value.feed === null && value.feedError === undefined, 3000); + rmSync(feed); + await gone; + writeFileSync(feed, '[1,2]'); + await waitFor(value => value.feedError === 'feed is not a JSON object', 3000); +}); diff --git a/todo/app/Cargo.lock b/todo/app/Cargo.lock index 3a919e0..874d9f1 100644 --- a/todo/app/Cargo.lock +++ b/todo/app/Cargo.lock @@ -2838,6 +2838,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" name = "sdlc-todo" version = "0.1.0" dependencies = [ + "dispatch", "eframe", "notify-rust", "serde", diff --git a/todo/app/Cargo.toml b/todo/app/Cargo.toml index 6975bae..45b7607 100644 --- a/todo/app/Cargo.toml +++ b/todo/app/Cargo.toml @@ -17,6 +17,10 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" ttf-parser = { version = "=0.25.1", default-features = false } +[target.'cfg(target_os = "macos")'.dependencies] +# Already in the tree through winit; runs badge updates on the main thread while the window is hidden. +dispatch = "0.2" + [profile.release] opt-level = "s" lto = true diff --git a/todo/app/src/i18n.rs b/todo/app/src/i18n.rs index caebce3..8649101 100644 --- a/todo/app/src/i18n.rs +++ b/todo/app/src/i18n.rs @@ -81,8 +81,9 @@ pub fn t(lang: Lang, key: &str) -> &'static str { "fix.started" => ("Fix requested; an agent started", "자가 조치 요청됨 — 에이전트 시작"), "fix.queued" => ("Fix requested; the next agent run picks it up", "자가 조치 요청됨 — 다음 에이전트 실행 때 처리"), "fix.failed" => ("Fix requested, but no agent started: ", "자가 조치 요청됨, 에이전트 시작 실패: "), - "tray.open" => ("Open To-do", "할 일 열기"), - "tray.quit" => ("Quit", "종료"), + "tray.board" => ("Open board", "보드 열기"), + "tray.list" => ("Open list window", "목록 창 열기"), + "tray.quit" => ("Quit", "끝내기"), "notify.title" => ("To-do needs you", "할 일 — 확인 필요"), "server.failed" => ("Could not reach the to-do server: ", "할 일 서버에 연결하지 못했어요: "), _ => ("", ""), diff --git a/todo/app/src/main.rs b/todo/app/src/main.rs index 6d3f491..4f7c0ae 100644 --- a/todo/app/src/main.rs +++ b/todo/app/src/main.rs @@ -17,7 +17,7 @@ use std::process::Child; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use tray_icon::menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem}; -use tray_icon::{TrayIcon, TrayIconBuilder, TrayIconEvent}; +use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent}; #[derive(Clone, PartialEq)] enum Conn { Connecting, Live, Offline(String) } @@ -57,8 +57,8 @@ struct App { /// Fonts found on this machine, as (name, file); the settings card lists them. fonts: Vec<(String, String)>, settings: bool, - tray: Option, - badge: Option, + /// eframe shows the window after its first frame; the app starts in the tray, so that frame hides it again. + hidden_at_start: bool, } /// The window width, in points, from which the content opens as a two-page spread. @@ -152,6 +152,45 @@ fn open_url(url: &str) { let _ = std::process::Command::new(program).args(args).spawn(); } +/// The board's address: the web page with the token in its fragment, as `urlOf` in todo/web.mjs builds it, plus +/// `app=1`: only tray-opened windows close an older board window (singleWindow in todo/page/app.js). +fn board_url(session: &Session) -> String { format!("{}/#t={}&app=1", session.origin(), session.token) } + +/// Google Chrome in /Applications or ~/Applications; it can open the board as an app window. +fn chrome_installed() -> bool { + let home = std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Applications")); + std::iter::once(PathBuf::from("/Applications")).chain(home).any(|dir| dir.join("Google Chrome.app").is_dir()) +} + +/// Opens the board in a window of its own: a Chrome app window (no tabs or address bar) on macOS when +/// Chrome is installed, else the default browser. The token goes only into the URL handed to the browser. +fn open_board(session: &Session) { + let url = board_url(session); + if cfg!(target_os = "macos") && chrome_installed() { + let opened = std::process::Command::new("open").args(["-na", "Google Chrome", "--args"]).arg(format!("--app={url}")) + .stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()) + .status().is_ok_and(|status| status.success()); + if opened { return; } + } + open_url(&url); +} + +/// Shows the list window, the fallback for the board. +fn show_list(ctx: &egui::Context) { + ctx.send_viewport_cmd(ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(ViewportCommand::Focus); +} + +/// The tray's main action: the board while the server is live; otherwise the list window, which shows +/// why it is offline, rather than a dead URL. +fn show_board(state: &State, ctx: &egui::Context) { + let session = { let shared = state.lock().unwrap(); if shared.conn == Conn::Live { shared.session.clone() } else { None } }; + match session { + Some(session) => { std::thread::spawn(move || open_board(&session)); } + None => show_list(ctx), + } +} + /// Opens Terminal with `command` typed at the prompt but not run, so the human reads it and presses Enter. /// A throwaway ZDOTDIR loads the human's ~/.zshrc, then `print -z` puts the command in the line editor; nothing is /// typed into the terminal, so nothing can run early. Returns false where that is not possible (not macOS, no zsh). @@ -179,7 +218,8 @@ fn quit(state: &State) -> ! { } /// Finds or starts the server, then follows its events; reconnects whenever the stream drops. -fn connect(state: State, ctx: egui::Context, launcher: Launcher, lang: Lang) { +/// With `open_board_once`, the board opens the first time the server answers with the list, as a launch shows it. +fn connect(state: State, ctx: egui::Context, launcher: Launcher, lang: Lang, mut open_board_once: bool) { std::thread::spawn(move || { let mut known: Option> = None; loop { @@ -215,11 +255,14 @@ fn connect(state: State, ctx: egui::Context, launcher: Launcher, lang: Lang) { } } known = Some(current); + badge_from_events(&model, lang); let mut shared = state.lock().unwrap(); shared.model = Some(model); shared.conn = Conn::Live; drop(shared); ctx.request_repaint(); + // The same path as a click on the tray icon. + if std::mem::take(&mut open_board_once) { show_board(&state, &ctx); } }); if let Err(error) = result { state.lock().unwrap().conn = Conn::Offline(error); @@ -231,7 +274,7 @@ fn connect(state: State, ctx: egui::Context, launcher: Launcher, lang: Lang) { } impl App { - fn new(cc: &eframe::CreationContext, launcher: Launcher, lang: Lang) -> App { + fn new(cc: &eframe::CreationContext, launcher: Launcher, lang: Lang, background: bool) -> App { 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(); @@ -244,24 +287,25 @@ impl App { toast: prefs_error.map(|error| (error, true, Instant::now())), artifacts: HashMap::new(), busy: HashSet::new(), })); - let tray = build_tray(lang).ok(); + if let Ok(tray) = build_tray(lang) { TRAY.set(Some((tray, None))); } let ctx = cc.egui_ctx.clone(); let (menu_state, menu_ctx) = (state.clone(), ctx.clone()); MenuEvent::set_event_handler(Some(move |event: MenuEvent| match event.id.0.as_str() { - "open" => { menu_ctx.send_viewport_cmd(ViewportCommand::Visible(true)); menu_ctx.send_viewport_cmd(ViewportCommand::Focus); } + "board" => show_board(&menu_state, &menu_ctx), + "list" => show_list(&menu_ctx), "quit" => quit(&menu_state), _ => {} })); - let click_ctx = ctx.clone(); + // A left click opens the board; the right button keeps the menu (build_tray turns the left-click menu off). + let (click_state, click_ctx) = (state.clone(), ctx.clone()); TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| { - if let TrayIconEvent::DoubleClick { .. } = event { - click_ctx.send_viewport_cmd(ViewportCommand::Visible(true)); - click_ctx.send_viewport_cmd(ViewportCommand::Focus); + if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { + show_board(&click_state, &click_ctx); } })); - connect(state.clone(), ctx, launcher, lang); + connect(state.clone(), ctx, launcher, lang, !background); 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 } + prefs, prefs_file, prefs_dirty: false, fonts, settings: false, hidden_at_start: false } } /// Runs one request off the UI thread; the event stream brings the new list back. @@ -279,29 +323,52 @@ impl App { }); } - fn update_tray(&mut self, count: usize) { - if self.badge == Some(count) { return; } - self.badge = Some(count); - if let Some(tray) = &self.tray { - let _ = tray.set_icon(Some(theme::tray_icon(count > 0, cfg!(target_os = "macos")))); - if cfg!(target_os = "macos") { tray.set_icon_as_template(true); } - #[cfg(target_os = "macos")] - tray.set_title(if count > 0 { Some(count.to_string()) } else { None }); - let _ = tray.set_tooltip(Some(format!("{} · {} {count}", t(self.lang, "title"), t(self.lang, "tab.focus")))); - } +} + +thread_local! { + /// The tray icon and the count its badge shows. It lives on the main thread, where the OS wants it. + static TRAY: std::cell::RefCell)>> = const { std::cell::RefCell::new(None) }; +} + +/// Sets the badge and tooltip to `count`. Main thread only; a call from elsewhere finds no tray and does nothing. +fn update_tray(count: usize, lang: Lang) { + TRAY.with_borrow_mut(|slot| { + let Some((tray, badge)) = slot else { return }; + if *badge == Some(count) { return; } + *badge = Some(count); + let _ = tray.set_icon(Some(theme::tray_icon(count > 0, cfg!(target_os = "macos")))); + if cfg!(target_os = "macos") { tray.set_icon_as_template(true); } + #[cfg(target_os = "macos")] + tray.set_title(if count > 0 { Some(count.to_string()) } else { None }); + let _ = tray.set_tooltip(Some(format!("{} · {} {count}", t(lang, "title"), t(lang, "tab.focus")))); + }); +} + +/// Updates the badge from the event thread. A hidden window gets no frames on macOS, so while the app sits in the +/// tray the frame loop cannot do it; the main dispatch queue can. Elsewhere the frame loop keeps doing it. +fn badge_from_events(model: &Model, lang: Lang) { + #[cfg(target_os = "macos")] + { + let count = model.items.iter().filter(|i| needs_you(i)).count(); + let lang = if model.lang.is_empty() { lang } else { Lang::parse(&model.lang) }; + dispatch::Queue::main().exec_async(move || update_tray(count, lang)); } + #[cfg(not(target_os = "macos"))] + let _ = (model, lang); } fn build_tray(lang: Lang) -> Result { let menu = Menu::new(); let items = [ - MenuItem::with_id("open", t(lang, "tray.open"), true, None), + MenuItem::with_id("board", t(lang, "tray.board"), true, None), + MenuItem::with_id("list", t(lang, "tray.list"), true, None), ]; for item in &items { menu.append(item).map_err(|e| e.to_string())?; } menu.append(&PredefinedMenuItem::separator()).map_err(|e| e.to_string())?; menu.append(&MenuItem::with_id("quit", t(lang, "tray.quit"), true, None)).map_err(|e| e.to_string())?; TrayIconBuilder::new() .with_menu(Box::new(menu)) + .with_menu_on_left_click(false) .with_icon(theme::tray_icon(false, cfg!(target_os = "macos"))) .with_icon_as_template(cfg!(target_os = "macos")) .with_tooltip(t(lang, "title")) @@ -349,6 +416,10 @@ fn markdown(ui: &mut egui::Ui, p: &theme::Palette, text: &str) { impl eframe::App for App { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + if !self.hidden_at_start { + self.hidden_at_start = true; + ctx.send_viewport_cmd(ViewportCommand::Visible(false)); + } if ctx.input(|i| i.viewport().close_requested()) { ctx.send_viewport_cmd(ViewportCommand::CancelClose); ctx.send_viewport_cmd(ViewportCommand::Visible(false)); @@ -361,7 +432,7 @@ impl eframe::App for App { if !model.lang.is_empty() { self.lang = Lang::parse(&model.lang); } let lang = self.lang; let attention = model.items.iter().filter(|i| needs_you(i)).count(); - self.update_tray(attention); + update_tray(attention, lang); 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)); } @@ -1073,7 +1144,8 @@ fn tickets(item: &Item) -> Vec<(String, String)> { /// A document is cached per item version, so an edited intent or plan is fetched again. fn artifact_key(item: &Item) -> String { format!("{}:{}", item.id, item.version) } -struct Args { session: PathBuf, kit: PathBuf, node: String, lang: String } +/// `background` (`--background`, or SDLC_TODO_BACKGROUND=1 for login items) starts in the tray without opening the board. +struct Args { session: PathBuf, kit: PathBuf, node: String, lang: String, background: bool } fn args() -> Result { let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).unwrap_or_default(); @@ -1088,16 +1160,18 @@ fn args() -> Result { .unwrap_or_default(), node: std::env::var("SDLC_TODO_NODE").unwrap_or_else(|_| "node".into()), lang: std::env::var("SDLC_TODO_LANG").unwrap_or_else(|_| "en".into()), + background: std::env::var("SDLC_TODO_BACKGROUND").is_ok_and(|value| value == "1"), }; let mut list = std::env::args().skip(1); while let Some(flag) = list.next() { + if flag == "--background" { parsed.background = true; continue; } let value = list.next().ok_or_else(|| format!("missing value for {flag}"))?; match flag.as_str() { "--session" => parsed.session = value.into(), "--kit" => parsed.kit = value.into(), "--node" => parsed.node = value, "--lang" => parsed.lang = value, - _ => return Err(format!("unknown option: {flag}\nusage: sdlc-todo [--session FILE] [--kit DIR] [--node PATH] [--lang en|ko]")), + _ => return Err(format!("unknown option: {flag}\nusage: sdlc-todo [--session FILE] [--kit DIR] [--node PATH] [--lang en|ko] [--background]")), } } if !parsed.kit.join("todo").join("todo.mjs").is_file() { return Err(format!("no todo/todo.mjs under --kit {}", parsed.kit.display())); } @@ -1114,6 +1188,7 @@ fn main() -> Result<(), String> { } let args = args()?; let lang = Lang::parse(&args.lang); + let background = args.background; let launcher = Launcher { session_file: args.session, kit: args.kit, node: args.node, lang: args.lang }; // 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"); @@ -1121,7 +1196,7 @@ fn main() -> Result<(), String> { 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()) + eframe::run_native("sdlc-todo", options, Box::new(move |cc| Ok(Box::new(App::new(cc, launcher, lang, background))))).map_err(|e| e.to_string()) } #[cfg(test)] diff --git a/todo/locales/en.mjs b/todo/locales/en.mjs index c10a72d..1bfc8ca 100644 --- a/todo/locales/en.mjs +++ b/todo/locales/en.mjs @@ -209,6 +209,89 @@ export default { 'tui.error.gone': 'Item changed or was removed; try again', 'tui.error.changed': 'Item changed; review it and try again', 'tui.error.undo': 'Cannot undo: item changed elsewhere', - 'tui.error.url': 'Only http(s) URLs can be opened' + 'tui.error.url': 'Only http(s) URLs can be opened', + 'board.title': 'To-do board', + 'board.views': 'View', + 'board.view.board': 'Board', + 'board.view.list': 'List', + 'board.view.runs': 'Runs', + 'board.view.health': 'Health', + 'board.loading': 'Loading the board…', + 'board.lane.you': 'Your turn', + 'board.lane.others': 'Waiting on others', + 'board.lane.blocked': 'Blocked or waiting on setup', + 'board.lane.agent': "Agent's turn", + 'board.column.general': 'General', + 'board.column.intent': 'Intent', + 'board.column.plan': 'Plan', + 'board.column.build': 'Build', + 'board.column.evidence': 'Evidence', + 'board.column.deliver': 'Deliver', + 'board.column.done': 'Done', + 'board.column.legacy': 'Older format', + 'board.tally.you': 'Your turn', + 'board.tally.agent': 'Agent', + 'board.tally.others': 'Waiting', + 'board.tally.blocked': 'Blocked', + 'board.count.one': 'One card', + 'board.count.other': '{count} cards', + 'board.hidden': '{count} hidden', + 'board.youEmpty': 'Nothing is your turn right now', + 'board.stale.one': 'One card unchanged for {days}+ days', + 'board.stale.other': '{count} cards unchanged for {days}+ days', + 'board.staleShown': 'Hide {count} unchanged for {days}+ days', + 'board.today': 'today', + 'board.days.one': 'day {count}', + 'board.days.other': 'day {count}', + 'board.sent': 'Answered', + 'board.sentWhat': 'Answered “{text}” · applies on the next agent run', + 'board.sentToast': 'Answer sent · applies on the next agent run', + 'board.updated': 'Updated {time}', + 'board.doneShow': 'Show done cards', + 'board.doneHide': 'Hide done cards', + 'board.legacy': 'Older format · {count}', + 'feed.source': 'Feed', + 'feed.state.idle': 'Idle', + 'feed.state.running': 'Running', + 'feed.state.held': 'On hold', + 'feed.state.off': 'Off', + 'feed.lanes': 'Lanes {busy}/{total}', + 'feed.next': 'Next run {time}', + 'feed.error': 'The feed could not be read', + 'feed.generated': 'Feed written {time}', + 'panel.page': 'Your turn {n}/{total}', + 'panel.pageOther': 'Your turn: {total}', + 'panel.prev': 'Previous (← or k)', + 'panel.next': 'Next (→ or j)', + 'panel.close': 'Close (Esc)', + 'panel.gone': 'This card changed or went away.', + 'panel.ask': 'What to decide', + 'panel.problem': 'What is blocked', + 'panel.waitingOn': 'Waiting on', + 'panel.state': 'Where it is', + 'panel.ai': 'AI pick', + 'panel.background': 'Background', + 'panel.why': 'Why', + 'panel.target': 'Your answer goes to “{title}”', + 'panel.noGlance': 'This document has no At a glance section. Open More to read it in full.', + 'panel.reply': 'Answer in your own words', + 'panel.send': 'Send', + 'panel.ticket': 'Open ticket', + 'panel.popupBlocked': 'The browser blocked the ticket window. Allow pop-ups for this page.', + 'panel.more': 'More', + 'panel.less': 'Less', + 'panel.members': 'Items on this ticket', + 'panel.noDocument': 'No work document.', + 'panel.nextStep': 'Next step', + 'runs.title': '{date} · {count} runs', + 'runs.summary': '08:00–19:00 · done {ok} · failed {fail} · no result {unknown}', + 'runs.today': 'today', + 'runs.ok': 'Done', + 'runs.fail': 'Failed', + 'runs.unknown': 'No result', + 'runs.failCount': 'failed {count}', + 'runs.empty': 'No runs on this day.', + 'health.alerts': 'Alerts', + 'health.empty': 'The feed has no health information.' } }; diff --git a/todo/locales/ko.mjs b/todo/locales/ko.mjs index f66d47e..305df1a 100644 --- a/todo/locales/ko.mjs +++ b/todo/locales/ko.mjs @@ -206,6 +206,86 @@ export default { 'tui.error.gone': '항목이 바뀌었거나 삭제되었습니다. 다시 시도하세요', 'tui.error.changed': '항목이 바뀌었습니다. 확인한 뒤 다시 시도하세요', 'tui.error.undo': '되돌릴 수 없음: 다른 곳에서 항목이 바뀌었습니다', - 'tui.error.url': 'http(s) 링크만 열 수 있습니다' + 'tui.error.url': 'http(s) 링크만 열 수 있습니다', + 'board.title': '할 일 보드', + 'board.views': '보기', + 'board.view.board': '보드', + 'board.view.list': '목록', + 'board.view.runs': '실행', + 'board.view.health': '건강', + 'board.loading': '보드를 불러오는 중…', + 'board.lane.you': '내 차례', + 'board.lane.others': '다른 사람 답 대기', + 'board.lane.blocked': '막힘·환경 대기', + 'board.lane.agent': '에이전트 차례', + 'board.column.general': '일반', + 'board.column.intent': '의도', + 'board.column.plan': '계획', + 'board.column.build': '구현', + 'board.column.evidence': '검증', + 'board.column.deliver': '배포', + 'board.column.done': '완료', + 'board.column.legacy': '이전 형식', + 'board.tally.you': '내 차례', + 'board.tally.agent': '에이전트', + 'board.tally.others': '대기', + 'board.tally.blocked': '막힘', + 'board.count.other': '{count}건', + 'board.hidden': '숨김 {count}', + 'board.youEmpty': '지금 내 차례인 일이 없어요', + 'board.stale.other': '{days}일 넘게 변화 없음 {count}건', + 'board.staleShown': '{days}일 넘게 변화 없는 {count}건 숨기기', + 'board.today': '오늘', + 'board.days.other': '{count}일째', + 'board.sent': '답 보냄', + 'board.sentWhat': '답 보냄 “{text}” · 다음 에이전트 실행에 반영', + 'board.sentToast': '답 보냄 · 다음 에이전트 실행에 반영', + 'board.updated': '업데이트 {time}', + 'board.doneShow': '완료 카드 펼치기', + 'board.doneHide': '완료 카드 접기', + 'board.legacy': '이전 형식 {count}건', + 'feed.source': '피드', + 'feed.state.idle': '대기', + 'feed.state.running': '실행 중', + 'feed.state.held': '보류', + 'feed.state.off': '꺼짐', + 'feed.lanes': '레인 {busy}/{total}', + 'feed.next': '다음 실행 {time}', + 'feed.error': '피드를 읽지 못했어요', + 'feed.generated': '피드 작성 {time}', + 'panel.page': '내 차례 {n}/{total}', + 'panel.pageOther': '내 차례 {total}건', + 'panel.prev': '이전 (← 또는 k)', + 'panel.next': '다음 (→ 또는 j)', + 'panel.close': '닫기 (Esc)', + 'panel.gone': '이 카드가 바뀌었거나 사라졌어요.', + 'panel.ask': '정해 주실 것', + 'panel.problem': '막힌 이유', + 'panel.waitingOn': '기다리는 것', + 'panel.state': '지금 상태', + 'panel.ai': 'AI 권장', + 'panel.background': '배경', + 'panel.why': '이유', + 'panel.target': '답은 “{title}” 항목으로 가요', + 'panel.noGlance': '이 문서에는 At a glance 절이 없어요. 자세히에서 전체를 읽어 주세요.', + 'panel.reply': '직접 답하기', + 'panel.send': '답 보내기', + 'panel.ticket': '티켓 열기', + 'panel.popupBlocked': '브라우저가 티켓 창을 막았어요. 이 페이지의 팝업을 허용해 주세요.', + 'panel.more': '자세히', + 'panel.less': '접기', + 'panel.members': '같은 티켓의 항목', + 'panel.noDocument': '작업 문서가 없어요.', + 'panel.nextStep': '다음 단계', + 'runs.title': '{date} 실행 {count}건', + 'runs.summary': '08:00–19:00 · 완료 {ok} · 실패 {fail} · 결과 미상 {unknown}', + 'runs.today': '오늘', + 'runs.ok': '완료', + 'runs.fail': '실패', + 'runs.unknown': '결과 미상', + 'runs.failCount': '실패 {count}', + 'runs.empty': '이 날은 실행 기록이 없어요.', + 'health.alerts': '알림', + 'health.empty': '피드에 건강 정보가 없어요.' } }; diff --git a/todo/page/app.css b/todo/page/app.css index 4e2fe30..452bcbf 100644 --- a/todo/page/app.css +++ b/todo/page/app.css @@ -19,7 +19,15 @@ --live: #0a7a52; --live-bg: #e3f6ee; --open-bg: #f2f2f7; - font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Apple SD Gothic Neo", system-ui, sans-serif; + --canvas: #f5f5f7; + --card: #ffffff; + --card-line: #e5e5ea; + --lane-you: #fffbea; + --shadow: rgb(0 0 0 / 0.08); + /* board sizes (board.js) */ + --strip-h: 3.5rem; --lane-w: 7.75rem; --col: minmax(8.5rem, 1fr); --col-general: minmax(8.5rem, 0.8fr); + --col-done: 3.5rem; --col-done-open: 14rem; --panel-w: clamp(21rem, 26vw, 29rem); + font-family: "Pretendard Variable", Pretendard, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Apple SD Gothic Neo", system-ui, sans-serif; font-size: 100%; line-height: 1.55; /* Break Korean between words, never mid-word; anywhere still splits a token too long for its line. */ @@ -45,6 +53,11 @@ --live: #6ee7b7; --live-bg: #123227; --open-bg: #2c2c2e; + --canvas: #111113; + --card: #232325; + --card-line: #3a3a3c; + --lane-you: #2a2616; + --shadow: rgb(0 0 0 / 0.4); } } * { box-sizing: border-box; } @@ -325,3 +338,262 @@ a.chip { display: inline-block; min-height: 44px; min-width: 44px; line-height: @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } } + +/* ---------- board (board.js): strip, lanes × phases, side panel, runs and health ---------- */ +body:not([data-view="list"]) { background: var(--canvas); display: flex; flex-direction: column; height: 100dvh; } +body:not([data-view="list"]) > .strip { flex-shrink: 0; } +.strip { + position: sticky; top: 0; z-index: 10; display: flex; align-items: center; gap: 1rem; + min-height: var(--strip-h); padding: 0.4rem 1.25rem; background: var(--paper); + border-bottom: 1px solid var(--line); font-size: 0.85rem; +} +body[data-view="list"] .strip { position: static; } +.strip-main { display: flex; align-items: center; gap: 0.5rem 1rem; flex: 1; min-width: 0; overflow: hidden; } +.strip-side { display: flex; align-items: center; gap: 0.75rem; flex-shrink: 0; } +.counts { display: flex; gap: 0.9rem; white-space: nowrap; } +.count-part { display: inline-flex; gap: 0.3rem; color: var(--muted); } +.count-part b { color: var(--ink); font-variant-numeric: tabular-nums; } +.count-part.lane-you b { color: var(--accent); } +.count-part.lane-blocked b { color: var(--bad); } +.feed-status { display: flex; align-items: center; gap: 0.85rem; padding-left: 1rem; border-left: 1px solid var(--line); white-space: nowrap; color: var(--muted); } +.feed-head { display: inline-flex; align-items: center; gap: 0.4rem; } +.feed-head b { color: var(--ink); } +.feed-status .dot, .alert-row .dot, .health-rows .dot { width: 7px; height: 7px; flex-shrink: 0; } +.feed-status[data-state="running"] .dot { background: var(--live); animation: working 1.4s ease-in-out infinite; } +.feed-status[data-state="held"] .dot { background: var(--yellow); } +.feed-status[data-state="off"] .dot { background: var(--bad); } +.feed-bit { font-variant-numeric: tabular-nums; } +/* Feed alerts get their own row under the strip: the most important text there, never cut. */ +.alerts { + display: flex; flex-wrap: wrap; gap: 0.35rem 0.5rem; margin: 0; padding: 0.4rem 1.25rem; + background: var(--paper); border-bottom: 1px solid var(--line); +} +.alert { display: inline-block; padding: 0.05rem 0.6rem; border-radius: 999px; line-height: 1.6; font-size: 0.8rem; font-weight: 600; overflow-wrap: anywhere; } +.feed-status .alert { white-space: nowrap; } +.alert.bad { color: var(--bad); background: var(--bad-bg); } +.alert.warn { color: var(--accent); background: var(--highlight); } +.alert.info { color: var(--busy); background: var(--busy-bg); } +.stale-toggle { + min-height: 32px; padding: 0 0.7rem; border-radius: 999px; border: 1px solid var(--line); + color: var(--control); font-size: 0.8rem; white-space: nowrap; +} +.stale-toggle[aria-pressed="true"] { background: var(--open-bg); color: var(--ink); } +.strip .live { color: var(--muted); } +.strip .live[data-state="live"] .dot { background: var(--live); } +.strip .live[data-state="live"] #live-text { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); } +.updated { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } +.strip .lang { min-height: 32px; margin-left: 0; } +.seg { display: inline-flex; gap: 2px; padding: 3px; border-radius: 10px; background: var(--open-bg); } +.seg button { min-height: 30px; min-width: 0; padding: 0 0.85rem; border-radius: 8px; color: var(--muted); font-weight: 600; font-size: 0.85rem; } +.seg button:hover { background: transparent; color: var(--ink); } +.seg button[aria-pressed="true"] { background: var(--paper); color: var(--ink); box-shadow: 0 1px 2px var(--shadow); } + +.board-view { display: grid; grid-template-columns: minmax(0, 1fr) auto; flex: 1; min-height: 0; } +.board-scroll { min-width: 0; overflow: auto; padding: 1rem 1.25rem 2rem; overscroll-behavior: contain; } +.board-loading { padding: 3rem 1rem; text-align: center; color: var(--muted); } +.board { + display: grid; grid-template-columns: var(--lane-w) var(--columns); width: max(100%, max-content); + border: 1px solid var(--line); border-radius: 12px; background: var(--paper); overflow: clip; +} +.col-head, .corner { + position: sticky; top: -1rem; z-index: 2; display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; + min-height: 2.5rem; padding: 0 0.75rem; background: var(--paper); border-bottom: 1px solid var(--line); font-size: 0.82rem; +} +.corner { left: 0; z-index: 4; } +.col-head + .col-head, .corner + .col-head { border-left: 1px solid var(--line); } +.col-name { font-weight: 700; } +.col-count { color: var(--muted); font-variant-numeric: tabular-nums; } +.col-done, .col-general { background: var(--paper); } +.done-toggle { + display: flex; align-items: center; justify-content: space-between; gap: 0.35rem; width: 100%; min-height: 2.5rem; + min-width: 0; padding: 0; color: var(--ink); font-size: inherit; +} +.done-toggle:hover { background: transparent; } +.board:not(.done-open) .done-toggle { flex-direction: column; justify-content: center; gap: 0; line-height: 1.2; } +.lane-head { + position: sticky; left: 0; z-index: 1; display: flex; flex-direction: column; gap: 0.15rem; + padding: 0.75rem; background: var(--paper); border-top: 1px solid var(--line); font-size: 0.82rem; +} +.lane-name { font-weight: 700; } +.lane-count, .lane-empty { color: var(--muted); font-size: 0.78rem; } +.lane-empty { margin-top: 0.35rem; } +.lane-head.lane-you, .cell.lane-you { background: var(--lane-you); } +.lane-you .lane-name { color: var(--accent); } +.lane-blocked .lane-name { color: var(--bad); } +.lane-others .lane-name { color: var(--busy); } +.cell { + display: flex; flex-direction: column; gap: 0.45rem; min-width: 0; min-height: 4.75rem; padding: 0.5rem; + border-top: 1px solid var(--line); border-left: 1px solid var(--line); container-type: inline-size; +} +/* A cell too narrow for the project chip drops it rather than showing one letter; the card's name keeps it. */ +@container (max-width: 10.5rem) { .card-proj { display: none; } } +.cell:empty::after { content: ""; width: 4px; height: 4px; margin: auto; border-radius: 50%; background: var(--line); } +.done-cell { border-top: 0; } +.board:not(.done-open) .done-cell > .card { display: none; } +.card { + display: flex; flex-direction: column; gap: 0.2rem; width: 100%; min-height: 0; min-width: 0; padding: 0.5rem 0.65rem 0.45rem; + border: 1px solid var(--card-line); border-radius: 9px; background: var(--card); color: var(--ink); + text-align: left; font-size: 0.8rem; line-height: 1.4; cursor: pointer; + transition: border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease; +} +.card:hover { background: var(--card); border-color: var(--ring); box-shadow: 0 2px 10px var(--shadow); } +.card:active { transform: translateY(1px); } +.card.edge { box-shadow: inset 3px 0 0 var(--accent); } +.card.edge[data-tone="blocked"] { box-shadow: inset 3px 0 0 var(--bad); } +.card[aria-current="true"] { border-color: var(--ink); box-shadow: 0 0 0 1px var(--ink); } +.card.edge[aria-current="true"] { box-shadow: inset 3px 0 0 var(--accent), 0 0 0 1px var(--ink); } +.card.edge[data-tone="blocked"][aria-current="true"] { box-shadow: inset 3px 0 0 var(--bad), 0 0 0 1px var(--ink); } +.card-top { display: flex; align-items: center; justify-content: space-between; gap: 0.4rem; min-width: 0; } +.card-key { flex-shrink: 0; max-width: 100%; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.card-proj { + flex: 0 1 auto; min-width: 0; padding: 0 0.45rem; border-radius: 999px; background: var(--open-bg); + color: var(--muted); font-size: 0.72rem; line-height: 1.6; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.card-title { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.card-meta { display: flex; align-items: center; gap: 0.45rem; min-height: 1.25rem; color: var(--muted); font-size: 0.72rem; } +.card-chip { padding: 0 0.4rem; border-radius: 5px; background: var(--busy-bg); color: var(--busy); font-weight: 600; white-space: nowrap; } +.card-sent { color: var(--ok); font-weight: 600; white-space: nowrap; } +.card-age { white-space: nowrap; } +.status-dot { flex-shrink: 0; width: 7px; height: 7px; margin-left: auto; border-radius: 50%; background: var(--ring); } +.status-dot[data-tone="wait"] { background: var(--yellow); } +.status-dot[data-tone="busy"] { background: var(--busy); } +.status-dot[data-tone="blocked"] { background: var(--bad); } +.status-dot[data-tone="ok"] { background: var(--ok); } +.status-dot[data-tone="working"] { background: var(--live); animation: working 1.4s ease-in-out infinite; } +.legacy { margin-top: 1rem; } +.legacy summary { min-height: 36px; padding: 0.4rem 0; color: var(--control); font-size: 0.85rem; cursor: pointer; } +.legacy-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); gap: 0.5rem; } + +/* side panel: beside the board, never over it */ +.panel { + width: var(--panel-w); min-height: 0; overflow-y: auto; padding: 0 1.5rem 2rem; background: var(--paper); + border-left: 1px solid var(--line); animation: panel-in 0.18s ease-out; overscroll-behavior: contain; +} +@keyframes panel-in { from { opacity: 0; transform: translateX(10px); } } +@keyframes shimmer { to { background-position: -200% 0; } } +.panel-bar { + position: sticky; top: 0; z-index: 1; display: flex; align-items: center; gap: 0.15rem; + margin: 0 -1.5rem 0.5rem; padding: 0.4rem 0.75rem 0.4rem 1.5rem; background: var(--paper); border-bottom: 1px solid var(--line); +} +.panel-page { margin-right: auto; color: var(--muted); font-size: 0.8rem; font-variant-numeric: tabular-nums; } +.panel-bar .icon { min-height: 36px; min-width: 36px; } +#panel-title { margin-top: 1rem; font-size: 1.15rem; line-height: 1.4; text-wrap: balance; } +.tag.key-tag { background: transparent; padding-left: 0; color: var(--ink); } +.panel-bar svg { display: block; } +.tags { display: flex; flex-wrap: wrap; gap: 0.3rem; margin-top: 0.55rem; } +.tag { padding: 0 0.5rem; border-radius: 999px; background: var(--open-bg); color: var(--muted); font-size: 0.75rem; font-weight: 600; line-height: 1.7; } +.tag.tone-wait { color: var(--accent); background: var(--highlight); } +.tag.tone-busy { color: var(--busy); background: var(--busy-bg); } +.tag.tone-blocked { color: var(--bad); background: var(--bad-bg); } +.tag.tone-working { color: var(--live); background: var(--live-bg); } +.tag.tone-ok { color: var(--ok); background: var(--ok-bg); } +.sent { margin-top: 1rem; padding: 0.6rem 0.8rem; border-radius: 10px; background: var(--ok-bg); color: var(--ok); font-size: 0.9rem; font-weight: 600; } +.ask { margin-top: 1.25rem; } +.ask-label { color: var(--muted); font-size: 0.8rem; font-weight: 600; } +.question { margin-top: 0.25rem; font-size: 1.05rem; font-weight: 650; line-height: 1.55; } +.question.skeleton { + height: 3.1em; border-radius: 8px; background: linear-gradient(90deg, var(--open-bg) 0%, var(--line) 50%, var(--open-bg) 100%); + background-size: 200% 100%; animation: shimmer 1.2s linear infinite; +} +.ai { margin-top: 0.85rem; padding: 0.7rem 0.85rem; border-radius: 10px; background: var(--highlight); } +.ai p { margin-top: 0.2rem; font-size: 0.9rem; } +.ai-badge { display: inline-block; color: var(--accent); font-size: 0.72rem; font-weight: 700; letter-spacing: 0.02em; } +.why { margin-top: 0.55rem; color: var(--muted); font-size: 0.85rem; } +.muted-label { margin-right: 0.4rem; font-weight: 600; } +.target { margin-top: 1rem; color: var(--muted); font-size: 0.8rem; } +.board-choices { display: flex; flex-direction: column; gap: 0.5rem; margin: 1rem 0 0; } +.board-choices .choice { + display: flex; align-items: center; gap: 0.6rem; width: 100%; min-height: 48px; padding: 0.55rem 0.85rem; + border-radius: 10px; text-align: left; font-weight: 600; transition: background-color 0.15s ease, border-color 0.15s ease; +} +.board-choices .choice.secondary { border: 1px solid var(--line); color: var(--ink); } +.board-choices .choice.secondary:hover { border-color: var(--ring); background: var(--open-bg); } +.choice-number { + display: grid; place-content: center; flex-shrink: 0; width: 1.5rem; height: 1.5rem; border-radius: 50%; + background: var(--open-bg); color: var(--muted); font-size: 0.75rem; +} +.choice.primary .choice-number { background: rgb(255 255 255 / 0.55); color: #1d1d1f; } +.choice-label { flex: 1; min-width: 0; } +.choice.primary .ai-badge { padding: 0 0.45rem; border-radius: 999px; background: rgb(255 255 255 / 0.6); color: #1d1d1f; } +.gate { margin-top: 1rem; } +.gate .glance { font-size: 0.9rem; } +.gate input { margin-top: 0.75rem; } +.fix { margin-top: 1rem; border: 1px solid var(--control); } +.reply { margin-top: 1.25rem; } +.reply label { font-size: 0.8rem; color: var(--muted); } +.reply .actions { justify-content: flex-end; margin-top: 0.4rem; } +.reply .actions button { border: 1px solid var(--line); } +.reply .hint { margin-top: 0.35rem; font-size: 0.78rem; } +.panel-actions { display: flex; gap: 0.5rem; margin-top: 1.25rem; padding-top: 1rem; border-top: 1px solid var(--line); } +.panel-actions .secondary { border: 1px solid var(--line); color: var(--ink); } +.panel-details { margin-top: 0.5rem; } +.panel-details h3 { margin: 1.5rem 0 0.5rem; font-size: 0.9rem; } +.panel .fields { grid-template-columns: max-content minmax(0, 1fr); font-size: 0.85rem; } +.panel .artifact { max-height: none; overflow: visible; padding: 0; border-bottom: 0; font-size: 0.92rem; } +.members { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; font-size: 0.85rem; } +.member { display: flex; align-items: baseline; gap: 0.5rem; } +.member.current { font-weight: 600; } + +/* toasts: errors (#error) and confirmations (#toast) float above every view */ +.toast { + position: fixed; left: 50%; bottom: 1.25rem; z-index: 50; transform: translateX(-50%); + max-width: min(38rem, calc(100vw - 2rem)); margin: 0; border-radius: 12px; box-shadow: 0 8px 28px var(--shadow); + animation: toast-in 0.2s ease-out; +} +@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } } +.error.toast { padding: 0.4rem 0.4rem 0.4rem 1rem; flex-wrap: nowrap; } +.toast.ok { padding: 0.7rem 1.1rem; background: var(--ink); color: var(--paper); font-weight: 600; font-size: 0.9rem; } + +/* runs and health (feed views) */ +.feed-view { flex: 1; min-height: 0; overflow-y: auto; padding: 1.25rem; } +.days { display: flex; flex-wrap: wrap; gap: 0.6rem; } +.day { + display: flex; flex-direction: column; align-items: flex-start; gap: 0.05rem; min-width: 7.5rem; min-height: 0; padding: 0.6rem 0.85rem; + border: 1px solid var(--line); border-radius: 10px; background: var(--paper); color: var(--ink); text-align: left; +} +.day:hover { background: var(--paper); border-color: var(--ring); } +.day[aria-pressed="true"] { border-color: var(--ink); box-shadow: 0 0 0 1px var(--ink); } +.day-name { color: var(--muted); font-size: 0.78rem; } +.day-count { font-size: 1.35rem; font-variant-numeric: tabular-nums; } +.day-fail { color: var(--muted); font-size: 0.75rem; } +.day-fail.bad { color: var(--bad); } +.runs-head { margin: 1.25rem 0 0.6rem; font-size: 1rem; } +.muted { color: var(--muted); font-size: 0.85rem; font-weight: 400; } +.timeline { padding: 0.6rem 1rem 1rem; border: 1px solid var(--line); border-radius: 12px; background: var(--paper); } +.axis { position: relative; height: 1.5rem; margin-right: 8rem; } +.tick { position: absolute; transform: translateX(-50%); color: var(--muted); font-size: 0.72rem; font-variant-numeric: tabular-nums; } +.tick:first-child { transform: none; } +.track { + position: relative; margin-right: 8rem; min-height: 2rem; + background-image: linear-gradient(to right, var(--line) 1px, transparent 1px); background-size: calc(100% / 11) 100%; +} +.run { position: absolute; height: 1.4rem; margin-top: 0.3rem; } +.run-bar { display: block; width: 100%; min-width: 4px; height: 100%; border-radius: 5px; border: 1px solid var(--ok); background: var(--ok-bg); } +.run.fail .run-bar { border-color: var(--bad); background: var(--bad-bg); } +.run.unknown .run-bar { border: 1px dashed var(--ring); background: transparent; } +.run-label { position: absolute; top: 0; left: calc(100% + 0.35rem); line-height: 1.4rem; white-space: nowrap; font-size: 0.75rem; color: var(--muted); } +.legend { display: flex; gap: 1rem; margin-top: 0.75rem; color: var(--muted); font-size: 0.8rem; } +.legend .run { position: static; display: inline-flex; align-items: center; gap: 0.35rem; height: auto; margin: 0; } +.legend .run-bar { width: 1rem; height: 0.8rem; } +.health-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr)); gap: 1rem; margin-top: 1rem; } +.health-card { padding: 1rem 1.25rem; border: 1px solid var(--line); border-radius: 12px; background: var(--paper); } +.health-card h3 { margin: 0 0 0.75rem; font-size: 1rem; } +.health-rows { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 0.45rem 1.25rem; margin: 0; font-size: 0.88rem; } +.health-rows dt { color: var(--muted); } +.health-rows dd { display: flex; align-items: center; gap: 0.45rem; margin: 0; overflow-wrap: anywhere; } +.health-rows .level-none .dot { display: none; } +.level-ok .dot, .alert-row.info .dot { background: var(--ok); } +.level-warn .dot, .alert-row.warn .dot { background: var(--yellow); } +.level-bad .dot, .alert-row.bad .dot { background: var(--bad); } +.level-bad { color: var(--bad); font-weight: 600; } +.alert-list { list-style: none; display: grid; gap: 0.45rem; margin: 0; padding: 0; font-size: 0.88rem; } +.alert-row { display: flex; align-items: center; gap: 0.5rem; } +.alert-row.bad { color: var(--bad); font-weight: 600; } +.alert-row .muted { margin-left: auto; } +#health-generated { margin-top: 1rem; } + +/* Small screens show the list; the board needs width. */ +@media (max-width: 899px) { + .seg, #board-tools, .feed-status, .alerts, .updated { display: none; } + .strip { min-height: 0; } +} diff --git a/todo/page/app.js b/todo/page/app.js index 3d5f8e1..d68a9c5 100644 --- a/todo/page/app.js +++ b/todo/page/app.js @@ -32,16 +32,21 @@ function setLanguage(next) { // Token stays in page memory. Keep the terminal's fragment so a reload can read it again. let openOnLoad = ''; -let token = ''; +let token = '', appWindow = false; { const hash = location.hash.slice(1); const params = new URLSearchParams(hash.includes('=') ? hash : ''); token = params.get('t') || ''; + // The tray marks its app windows with app=1; only those take part in single-window (see singleWindow). + appWindow = params.get('app') === '1'; if (!hash.includes('=') && /^[0-9a-f]{6}(?:-\d+)?$/.test(hash)) openOnLoad = hash; if (params.get('id')) openOnLoad = params.get('id'); } let items = [], file = ''; +// The board's optional feed (see web.mjs readFeed); untrusted text, shown with textContent only. +let feed = null, feedError = ''; +const listeners = []; // views that redraw after every snapshot (board.js) let seenSnapshot = false, changedAt = null; const drafts = new Map(); // item id -> {reply, words} // The inbox keeps one event per line, so the server rejects line breaks; join the lines the textarea allows. @@ -51,7 +56,12 @@ const oneLine = value => value.trim().replace(/\s*[\r\n]+\s*/g, ' / '); class RequestError extends Error { constructor(source, status) { super(say(source)); this.source = source; this.status = status; } } +let inFlight = 0; async function api(path, body) { + inFlight++; + try { return await request(path, body); } finally { inFlight--; } +} +async function request(path, body) { let response; try { response = await fetch(path, { @@ -300,6 +310,7 @@ function apply(data) { const before = new Map(items.map(i => [i.id, i])); items = Array.isArray(data.items) ? data.items : []; file = data.file || file; + if ('feed' in data) { feed = data.feed && typeof data.feed === 'object' ? data.feed : null; feedError = data.feedError || ''; } // Pinned items (settings) stay on top, as in the app. const open = items.filter(i => !i.done).sort((a, b) => Number(!!b.pin) - Number(!!a.pin)), done = items.filter(i => i.done); queue = queueOf(items); @@ -334,6 +345,7 @@ function apply(data) { } syncPane(); if (detailId) renderDetail(); + for (const listener of listeners) listener(); return before; } @@ -479,6 +491,8 @@ $('add').addEventListener('submit', async event => { document.addEventListener('keydown', event => { if ((event.key !== '/' && event.key !== 'n') || event.altKey || event.ctrlKey || event.metaKey) return; const t = event.target; + // The list's add shortcut; the board has its own keys. + if (document.body?.dataset?.view && document.body.dataset.view !== 'list') return; if (($('detail').open && !isWide) || t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName)) return; event.preventDefault(); addText.focus(); @@ -850,6 +864,32 @@ $('lang').addEventListener('change', () => { announce(t('announce.language', { name: locales[lang].name })); }); +// The board (board.js, a separate module) reads state and acts through this; the list keeps its own code paths. +const busyChecks = [() => inFlight > 0 || adding || !!$('add-text').value.trim() || + [...drafts.values()].some(draft => (draft.reply.trim() && draft.reply !== draft.seed) || draft.words.trim())]; +const busy = () => busyChecks.some(check => check()); +globalThis.todoPage = { + get items() { return items; }, get feed() { return feed; }, get feedError() { return feedError; }, + get lang() { return lang; }, get t() { return t; }, get token() { return token; }, + api, apply, announce, showError, sourceOf, oneLine, say, + subscribe(listener) { listeners.push(listener); if (seenSnapshot) listener(); }, + addBusyCheck(check) { busyChecks.push(check); } +}; + +// One board window: the tray opens a new app window (#…&app=1) on every click, so a newer one asks older ones to +// close. Only app windows talk; a tab opened with `todo web --open` never closes. A window with an unsent draft or +// a request in flight stays. A browser closes only script-opened or single-entry windows; otherwise nothing happens. +function singleWindow(Channel = globalThis.BroadcastChannel, app = appWindow) { + if (!app || typeof Channel !== 'function') return null; + const channel = new Channel('sdlc-todo-board'), born = Date.now(); + channel.addEventListener('message', event => { + if (event.data?.type === 'board-open' && event.data.at >= born && !busy()) globalThis.close?.(); + }); + channel.postMessage({ type: 'board-open', at: born }); + return channel; +} +singleWindow(); + if (!token) { setLive('off', 'live.off'); showError({ key: 'error.noToken' }); diff --git a/todo/page/board.js b/todo/page/board.js new file mode 100644 index 0000000..c2af426 --- /dev/null +++ b/todo/page/board.js @@ -0,0 +1,745 @@ +// Board view, the page's default screen: sdlc phases are columns, who acts next is the lane, and a side panel +// answers and approves in place. State and requests come from app.js (globalThis.todoPage); every item and feed +// string is shown with textContent, never as HTML. Only renderMarkdown output (it escapes first) uses innerHTML. +import { phaseLabel } from './i18n.mjs'; +import { boardCards, boardColumns, boardLanes, statusLabel, statusOf, timeOf, DAY_MS, STALE_DAYS } from './status.mjs'; + +const page = globalThis.todoPage; +const $ = id => document.getElementById(id); +const t = (key, vars) => page.t(key, vars); +const el = (tag, className, text) => { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; +}; +const str = value => typeof value === 'string' ? value : ''; +const list = value => Array.isArray(value) ? value : []; +const record = value => value && typeof value === 'object' && !Array.isArray(value) ? value : null; +const isHttp = url => typeof url === 'string' && /^https?:\/\//i.test(url); +const basename = project => project.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || project; +const clock = ms => new Intl.DateTimeFormat(page.lang, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(ms); +const dateTime = ms => new Intl.DateTimeFormat(page.lang, { dateStyle: 'medium', timeStyle: 'short' }).format(ms); +const alertLevel = alert => ['bad', 'warn'].includes(alert.level) ? alert.level : 'info'; +const feedAlerts = feed => list(feed?.alerts).map(record).filter(alert => alert && str(alert.text)); +const typing = target => target?.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target?.tagName); + +// ---------- words ---------- +// The panel's top section is for a person, not an agent: no code spans, file paths or command flags. +function plain(text) { + return str(text) + .replace(/`[^`]*`/g, ' ') + .replace(/\[([^\]]+)\]\((?:[^)]+)\)/g, '$1') + .replace(/\*\*|__/g, '') + .replace(/(?:^|\s)(?:~|\.{1,2})?\/[^\s,)]*\/[^\s,)]*/g, ' ') + .replace(/(?:^|\s)--[\w-]+/g, ' ') + .replace(/\s+/g, ' ').replace(/\s+([,.)])/g, '$1').trim(); +} +// "## At a glance" bullets of a brief or work document: { 'your call': '…', 'ai pick': '…', … }. +function glanceOf(markdown) { + const lines = str(markdown).split(/\r?\n/), start = lines.findIndex(line => /^##\s+At a glance\s*$/i.test(line)); + if (start < 0) return null; + const fields = {}, section = []; + for (const line of lines.slice(start + 1)) { + if (/^#{1,2}\s/.test(line)) break; + section.push(line); + const field = line.match(/^\s*[-*]\s+\*\*([^*:]+):?\*\*:?\s*(.*)$/); + if (field) fields[field[1].trim().toLowerCase()] = field[2].trim(); + } + return { fields, markdown: section.join('\n').trim() }; +} +const tagOf = title => title.match(/^\[([^\]]+)\]\s*/); +// Line 1 names the ticket (or the [tag] of a title); line 2 is the title without it. +function cardWords(card) { + const main = card.work || card.target; + const tag = tagOf(main.title); + const key = card.link?.label || tag?.[1] || ''; + let title = main.title; + if (tag) title = title.slice(tag[0].length); + for (let i = 0; key && i < 3 && title.startsWith(key); i++) title = title.slice(key.length).replace(/^[\s·:—-]+/, ''); + return { key, title: title.replace(/^[\s·:—-]+/, '') || main.title }; +} +function projectChip(card) { + const service = str(card.entry?.service); + if (service) return service; + const repos = card.members.flatMap(member => member.repos || []); + const unique = [...new Set(repos)]; + if (unique.length) return unique.length > 1 ? `${unique[0]} +${unique.length - 1}` : unique[0]; + const project = card.members.find(member => member.project)?.project; + return project ? basename(project) : ''; +} +function ageOf(card, now) { + if (!Number.isFinite(card.last)) return ''; + const days = Math.floor((now - card.last) / DAY_MS); + return days < 1 ? t('board.today') : t('board.days', { count: days }); +} +const toneOf = card => card.working ? 'working' : { you: 'wait', blocked: 'blocked', others: 'open', agent: 'busy', done: 'ok' }[card.lane]; +const lastReply = item => [...item.events].reverse().find(event => event.who === 'human' && /^reply — /.test(event.what))?.what.slice(8) || ''; + +// ---------- view ---------- +const narrow = matchMedia('(max-width: 899px)'); +let chosenView = 'board'; +function currentView() { + if (narrow.matches) return 'list'; + if ((chosenView === 'runs' || chosenView === 'health') && !page.feed) return 'board'; + return chosenView; +} +function syncView() { + const view = currentView(); + document.body.dataset.view = view; + $('board-view').hidden = view !== 'board'; + $('runs-view').hidden = view !== 'runs'; + $('health-view').hidden = view !== 'health'; + $('list-view').hidden = view !== 'list'; + $('panel').hidden = view !== 'board' || !selectedKey; + $('board-tools').hidden = view !== 'board'; + for (const button of $('views').querySelectorAll('[data-view]')) { + button.setAttribute('aria-pressed', String(button.dataset.view === view)); + button.hidden = (button.dataset.view === 'runs' || button.dataset.view === 'health') && !page.feed; + } +} +$('views').addEventListener('click', event => { + const button = event.target.closest('[data-view]'); + if (!button) return; + chosenView = button.dataset.view; + render(); +}); +narrow.addEventListener('change', () => render()); + +// ---------- render ---------- +let cards = [], selectedKey = '', showStale = false, doneOpen = false, updatedAt = 0, loaded = false; +function render() { + const now = Date.now(); + cards = boardCards(page.items, page.feed, now); + updatedAt = now; + syncView(); + renderStrip(); + renderBoard(now); + const view = currentView(); + if (view === 'runs') renderRuns(now); + if (view === 'health') renderHealth(); + renderPanel(now); + const yours = cards.filter(card => card.lane === 'you').length; + document.title = yours ? `(${yours}) ${t('board.title')}` : t('board.title'); +} + +// ---------- strip ---------- +function renderStrip() { + const count = lane => cards.filter(card => card.lane === lane).length; + const counts = $('board-counts'); + const parts = [['you', 'board.tally.you'], ['agent', 'board.tally.agent'], ['others', 'board.tally.others'], ['blocked', 'board.tally.blocked']] + .map(([lane, key]) => { + const part = el('span', `count-part lane-${lane}`); + part.append(el('span', '', t(key)), el('b', '', String(count(lane)))); + return part; + }); + counts.replaceChildren(...parts); + const feed = record(page.feed), status = record(feed?.status), box = $('feed-status'); + box.hidden = !feed && !page.feedError; + if (!box.hidden) { + const bits = []; + if (feed) { + const state = ['idle', 'running', 'held', 'off'].includes(status?.state) ? status.state : 'idle'; + box.dataset.state = state; + const head = el('span', 'feed-head'); + head.append(el('span', 'dot', ''), el('b', '', str(feed.source) || t('feed.source')), el('span', '', str(status?.text) || t(`feed.state.${state}`))); + bits.push(head); + const lanes = record(status?.lanes); + if (Number.isFinite(lanes?.busy) && Number.isFinite(lanes?.total)) bits.push(el('span', 'feed-bit', t('feed.lanes', { busy: lanes.busy, total: lanes.total }))); + const next = timeOf(str(status?.nextRunAt)); + if (Number.isFinite(next)) bits.push(el('span', 'feed-bit', t('feed.next', { time: clock(next) }))); + } else box.dataset.state = 'off'; + if (page.feedError) bits.push(el('span', 'alert warn', t('feed.error'))); + box.replaceChildren(...bits); + } + const alerts = feedAlerts(feed); + $('feed-alerts').hidden = !alerts.length || currentView() === 'list'; + $('feed-alerts').replaceChildren(...alerts.map(alert => { + const chip = el('span', `alert ${alertLevel(alert)}`, alert.text); + const since = timeOf(str(alert.since)); + chip.title = Number.isFinite(since) ? `${alert.text} · ${dateTime(since)}` : alert.text; + return chip; + })); + const stale = cards.filter(card => card.stale && card.column !== 'done').length, toggle = $('stale-toggle'); + toggle.hidden = !stale; + toggle.setAttribute('aria-pressed', String(showStale)); + toggle.textContent = t(showStale ? 'board.staleShown' : 'board.stale', { count: stale, days: STALE_DAYS }); + $('board-updated').textContent = loaded ? t('board.updated', { time: clock(updatedAt) }) : ''; +} +$('stale-toggle').addEventListener('click', () => { showStale = !showStale; render(); }); + +// ---------- board ---------- +const nodes = new Map(); // card key -> card button, reused so focus, selection and position survive live updates +let layout = ''; +const cells = new Map(); // `${lane}|${column}` or 'done' -> cell +function buildGrid(columns) { + const grid = $('board'); + grid.replaceChildren(); + grid.classList.toggle('done-open', doneOpen); + cells.clear(); + grid.style.setProperty('--columns', columns.map(column => column === 'general' ? 'var(--col-general)' : + column === 'done' ? (doneOpen ? 'var(--col-done-open)' : 'var(--col-done)') : 'var(--col)').join(' ')); + const corner = el('div', 'col-head corner'); + grid.append(corner); + for (const column of columns) { + const head = el('div', `col-head col-${column}`); + head.dataset.column = column; + if (column === 'done') { + const toggle = el('button', 'done-toggle'); + toggle.type = 'button'; + toggle.id = 'done-toggle'; + toggle.setAttribute('aria-expanded', String(doneOpen)); + toggle.append(el('span', 'col-name'), el('span', 'col-count')); + head.append(toggle); + } else head.append(el('span', 'col-name'), el('span', 'col-count')); + grid.append(head); + } + boardLanes.forEach((lane, row) => { + const head = el('div', `lane-head lane-${lane}`); + head.dataset.lane = lane; + head.style.gridRow = String(row + 2); + head.append(el('span', 'lane-name'), el('span', 'lane-count'), el('span', 'lane-empty')); + grid.append(head); + for (const column of columns) { + if (column === 'done') continue; + const cell = el('div', `cell lane-${lane} col-${column}`); + cell.style.gridRow = String(row + 2); + cell.dataset.lane = lane; + grid.append(cell); + cells.set(`${lane}|${column}`, cell); + } + }); + if (columns.includes('done')) { + const cell = el('div', 'cell done-cell'); + cell.style.gridRow = `2 / span ${boardLanes.length}`; + cell.style.gridColumn = String(columns.length + 1); + grid.append(cell); + cells.set('done', cell); + } +} +function cardNode(card, now) { + let node = nodes.get(card.key); + if (!node) { + node = el('button', 'card'); + node.type = 'button'; + node.dataset.key = card.key; + const top = el('span', 'card-top'), meta = el('span', 'card-meta'); + node._refs = { key: el('span', 'card-key'), proj: el('span', 'card-proj'), title: el('span', 'card-title'), + chip: el('span', 'card-chip'), age: el('span', 'card-age'), sent: el('span', 'card-sent'), dot: el('span', 'status-dot') }; + const r = node._refs; + top.append(r.key, r.proj); + meta.append(r.chip, r.age, r.sent, r.dot); + node.append(top, r.title, meta); + nodes.set(card.key, node); + } + const r = node._refs, words = cardWords(card), proj = projectChip(card), age = ageOf(card, now); + const status = statusLabel(t, card.target, now); + const sig = JSON.stringify([page.lang, words, proj, age, card.chip, card.lane, card.working, card.sent, card.pinned, card.needsHuman, status]); + if (node._sig !== sig) { + node._sig = sig; + r.key.textContent = words.key || words.title; + r.title.textContent = words.key ? words.title : ''; + r.title.hidden = !words.key; + r.proj.textContent = proj; + r.proj.hidden = !proj; + r.chip.textContent = card.chip; + r.chip.hidden = !card.chip; + r.age.textContent = age; + r.sent.textContent = card.sent ? t('board.sent') : ''; + r.sent.hidden = !card.sent; + r.dot.dataset.tone = toneOf(card); + r.dot.title = status; + node.dataset.tone = toneOf(card); + node.classList.toggle('edge', card.pinned || card.needsHuman); + node.title = (card.work || card.target).title; + node.setAttribute('aria-label', [words.key, words.key ? words.title : '', proj, card.chip, status, age, card.sent ? t('board.sent') : ''].filter(Boolean).join(' · ')); + } + node.setAttribute('aria-current', String(card.key === selectedKey)); + node._card = card; + return node; +} +function renderBoard(now) { + const visible = cards.filter(card => card.column === 'done' || showStale || !card.stale); + const general = visible.some(card => card.column === 'general'); + const columns = [...(general ? ['general'] : []), ...boardColumns, 'done']; + const signature = JSON.stringify([columns, doneOpen]); + if (signature !== layout) { layout = signature; buildGrid(columns); } + $('board-loading').hidden = loaded; + $('board').hidden = !loaded; + const grid = $('board'); + for (const head of grid.querySelectorAll('.col-head[data-column]')) { + const column = head.dataset.column; + head.querySelector('.col-name').textContent = t(`board.column.${column}`); + head.querySelector('.col-count').textContent = String(visible.filter(card => card.column === column).length); + } + const done = $('done-toggle'); + if (done) done.setAttribute('aria-label', t(doneOpen ? 'board.doneHide' : 'board.doneShow')); + for (const head of grid.querySelectorAll('.lane-head')) { + const lane = head.dataset.lane, here = cards.filter(card => card.lane === lane && !['done', 'legacy'].includes(card.column)); + const hidden = showStale ? 0 : here.filter(card => card.stale).length; + head.querySelector('.lane-name').textContent = t(`board.lane.${lane}`); + head.querySelector('.lane-count').textContent = [t('board.count', { count: here.length - hidden }), hidden ? t('board.hidden', { count: hidden }) : ''].filter(Boolean).join(' · '); + const empty = head.querySelector('.lane-empty'); + empty.textContent = lane === 'you' && !here.length && loaded ? t('board.youEmpty') : ''; + empty.hidden = !empty.textContent; + } + const active = document.activeElement; + const want = new Map([...cells.values()].map(cell => [cell, []])); + const legacy = []; + for (const card of visible) { + if (card.column === 'legacy') { legacy.push(cardNode(card, now)); continue; } + const cell = card.column === 'done' ? cells.get('done') : cells.get(`${card.lane}|${card.column}`); + if (!cell) continue; + // Pinned cards lead their cell; otherwise the list's order, which is the order agents work in. + want.get(cell)[card.pinned ? 'unshift' : 'push'](cardNode(card, now)); + } + const kept = new Set([...want.values()].flat().concat(legacy)); + for (const [key, node] of nodes) if (!kept.has(node)) { node.remove(); nodes.delete(key); } + for (const [cell, wanted] of want) patchChildren(cell, wanted, kept); + const legacyBox = $('legacy'); + legacyBox.hidden = !legacy.length; + $('legacy-title').textContent = t('board.legacy', { count: legacy.length }); + patchChildren($('legacy-cards'), legacy, kept); + if (active?.classList?.contains('card') && active.isConnected && document.activeElement !== active) active.focus({ preventScroll: true }); +} +// Move only what changed: a node re-inserted at its own place would lose focus and replay its transition. +function patchChildren(parent, wanted, kept) { + for (const child of [...parent.children]) if (!kept.has(child)) child.remove(); + wanted.forEach((node, index) => { if (parent.children[index] !== node) parent.insertBefore(node, parent.children[index] || null); }); + while (parent.children.length > wanted.length) parent.lastElementChild.remove(); +} +$('board').addEventListener('click', event => { + if (event.target.closest('#done-toggle')) { doneOpen = !doneOpen; layout = ''; render(); return; } + const node = event.target.closest('.card'); + if (node) select(node.dataset.key, event.detail === 0); +}); +$('legacy-cards').addEventListener('click', event => { + const node = event.target.closest('.card'); + if (node) select(node.dataset.key, event.detail === 0); +}); + +// ---------- panel ---------- +const drafts = new Map(); // target item id -> reply draft +// Work documents by item and status kind: a sync can change an item's version, so the version alone would refetch +// in a loop; a new kind (a gate opened or closed) fetches again. 409 on approval drops the entry. +const documents = new Map(); // `${id}|${kind}` -> { markdown, gate, sha, version } | { error } | { pending } +let panelSig = '', panelTarget = null, panelCard = null, sending = false; +function yourQueue() { + const order = [...(cards.some(card => card.column === 'general') ? ['general'] : []), ...boardColumns]; + return order.flatMap(column => cards.filter(card => card.lane === 'you' && card.column === column && (showStale || !card.stale))); +} +function select(key, focusPanel) { + if (!cards.some(card => card.key === key)) return; + selectedKey = key; + render(); + if (focusPanel) $('panel-title').focus(); + followTicket(cards.find(card => card.key === key)); + nodes.get(key)?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' }); +} +function closePanel() { + const key = selectedKey; + selectedKey = ''; + render(); + nodes.get(key)?.focus({ preventScroll: true }); +} +function step(delta) { + const queue = yourQueue(); + if (!queue.length) return; + const at = queue.findIndex(card => card.key === selectedKey); + const next = at < 0 ? (delta > 0 ? 0 : queue.length - 1) : (at + delta + queue.length) % queue.length; + select(queue[next].key, false); +} +$('panel-close').addEventListener('click', closePanel); +$('panel-prev').addEventListener('click', () => step(-1)); +$('panel-next').addEventListener('click', () => step(1)); +document.addEventListener('keydown', event => { + if (currentView() !== 'board' || event.altKey || event.ctrlKey || event.metaKey) return; + if (event.key === 'Escape' && selectedKey) { event.preventDefault(); closePanel(); return; } + if (typing(event.target) || !selectedKey) return; + if (event.key === 'ArrowRight' || event.key === 'j') { event.preventDefault(); step(1); } + else if (event.key === 'ArrowLeft' || event.key === 'k') { event.preventDefault(); step(-1); } +}); + +const skeletonMs = 1500; +const docKey = item => `${item.id}|${statusOf(item).kind}`; +function documentOf(item) { + if (item.done || !(item.brief || item.sdlc)) return null; + const key = docKey(item); + if (!documents.has(key)) { + documents.set(key, { pending: true, started: Date.now() }); + // A brief usually arrives at once; an sdlc document waits for its status. Past the skeleton's time, show the + // item's own words instead of a placeholder. + setTimeout(() => { if (panelTarget?.id === item.id && documents.get(key)?.pending) { panelSig = ''; renderPanel(Date.now()); } }, skeletonMs + 50); + page.api(`/api/artifact?id=${encodeURIComponent(item.id)}`) + .then(data => documents.set(key, { markdown: str(data.markdown), gate: str(data.gate), sha: str(data.sha), version: item.version })) + .catch(error => documents.set(key, { error: page.say(page.sourceOf(error)) })) + .finally(() => { if (panelTarget?.id === item.id) { panelSig = ''; renderPanel(Date.now()); } }); + } + return documents.get(key); +} + +function renderPanel(now) { + const panel = $('panel'); + const card = cards.find(c => c.key === selectedKey); + if (!selectedKey || currentView() !== 'board') { panel.hidden = true; panelSig = ''; panelTarget = panelCard = null; return; } + panel.hidden = false; + $('panel-gone').hidden = !!card; + $('panel-content').hidden = !card; + const queue = yourQueue(), at = card ? queue.findIndex(c => c.key === card.key) : -1; + $('panel-page').textContent = at >= 0 ? t('panel.page', { n: at + 1, total: queue.length }) : t('panel.pageOther', { total: queue.length }); + $('panel-prev').disabled = $('panel-next').disabled = !queue.length || (queue.length === 1 && at === 0); + if (!card) return; + const item = card.target, doc = documentOf(item); + const loading = !!doc?.pending && !!item.brief && Date.now() - doc.started < skeletonMs; + const sig = JSON.stringify([page.lang, card.key, card.members.map(m => [m.id, m.version, m.working?.what]), card.lane, card.entry, doc, loading, sending, showDetails]); + if (sig === panelSig) return; + panelSig = sig; + if (panelTarget?.id !== item.id) { + $('panel-reply-text').value = drafts.get(item.id) || ''; + $('panel-error').hidden = true; + $('panel-note').value = ''; + } + panelTarget = item; + panelCard = card; + const words = cardWords(card), status = statusOf(item), glance = doc && !doc.pending && !doc.error ? glanceOf(doc.markdown) : null; + $('panel-title').textContent = words.key ? words.title : (card.work || item).title; + // The ticket and project sit with the status under the title, not as a label above it. + const tags = [[words.key, 'tag key-tag'], [projectChip(card), 'tag'], [t(`board.lane.${card.lane}`), `tag tone-${toneOf(card)}`], + [t(`board.column.${card.column}`), 'tag'], [card.chip, 'tag'], [ageOf(card, now), 'tag']]; + $('panel-tags').replaceChildren(...tags.filter(([text]) => text).map(([text, className]) => el('span', className, text))); + + // What the human is asked, from the brief's At a glance when there is one. + const sent = card.members.find(member => member.status !== 'blocked' && statusOf(member).kind === 'handoff'); + $('panel-sent').hidden = !sent; + if (sent) $('panel-sent').textContent = t('board.sentWhat', { text: lastReply(sent) || '…' }); + const fields = glance?.fields || {}; + const label = { you: 'panel.ask', blocked: 'panel.problem', others: 'panel.waitingOn', agent: 'panel.state', done: 'panel.state' }[statusOf(item).actor]; + $('panel-ask-label').textContent = t(label); + const question = questionOf(card, item, status, fields, now); + const ask = $('panel-question'); + ask.textContent = loading ? '' : question; + ask.classList.toggle('skeleton', loading); + const pick = plain(str(fields['ai pick'])).replace(/^AI\s*(?:권장|pick)\s*[::]\s*/i, ''); + $('panel-ai').hidden = !pick; + $('panel-ai-text').textContent = pick; + for (const [id, name] of [['panel-background', 'background'], ['panel-why', 'why']]) { + const value = plain(fields[name]); + $(id).hidden = !value; + $(id).replaceChildren(el('span', 'muted-label', t(`panel.${name}`)), document.createTextNode(value)); + } + const target = $('panel-target'); + target.hidden = card.members.length < 2 || item.done; + target.textContent = t('panel.target', { title: item.title }); + + renderChoices(card, item); + renderGate(item, doc, status); + renderProblem(item, status); + $('panel-reply').hidden = item.done; + for (const control of $('panel-reply').elements) control.disabled = sending; + const url = card.link?.url; + $('panel-ticket').hidden = !isHttp(url); + renderDetails(card, item, doc); +} +// The brief's "your call" when it asks something; otherwise the item's own words for whoever acts next. +function questionOf(card, item, status, fields, now) { + const yourCall = plain(fields['your call']); + if (yourCall && yourCall.toLowerCase() !== 'none') return yourCall; + if (status.actor === 'you') return plain(status.gate ? t(`next.${status.kind}`) : item.waiting || item.sdlc?.action || t(`next.${status.kind}`)); + if (status.actor === 'blocked') return plain(item.error || item.sdlc?.action) || t('field.unknown'); + if (status.actor === 'others') return plain(item.others || str(card.entry?.waitingText)) || statusLabel(t, item, now); + return [statusLabel(t, item, now), plain(str(card.entry?.waitingText))].filter(Boolean).join(' · '); +} +function renderChoices(card, item) { + const box = $('panel-choices'), labels = item.done ? [] : item.choices || []; + box.hidden = !labels.length; + box.replaceChildren(...labels.map((label, index) => { + const recommended = item.pick ? item.pick === index + 1 : item.suggest === label; + const button = el('button', recommended ? 'choice primary' : 'choice secondary'); + button.type = 'button'; + button.disabled = sending; + button.append(el('span', 'choice-number', String(index + 1)), el('span', 'choice-label', label)); + if (recommended) button.append(el('span', 'ai-badge', t('panel.ai'))); + button.addEventListener('click', () => answer(card, item, label)); + return button; + })); +} +function renderGate(item, doc, status) { + const box = $('panel-gate'); + box.hidden = !status.gate; + if (!status.gate) return; + const approve = $('panel-approve'); + approve.textContent = t(`decide.approve-${status.gate}`); + const glance = $('panel-glance'); + if (!doc || doc.pending) { + glance.replaceChildren(el('p', 'hint', t('artifact.loading'))); + approve.disabled = true; + return; + } + if (doc.error) { + glance.replaceChildren(el('p', 'field-error', t('artifact.failed', { message: doc.error }))); + approve.disabled = true; + return; + } + approve.disabled = sending || doc.gate !== status.gate; + const section = glanceOf(doc.markdown); + if (!section?.markdown) { glance.replaceChildren(el('p', 'hint', t('panel.noGlance'))); return; } + import('./markdown.js').then(({ renderMarkdown }) => { + if (panelTarget?.id !== item.id) return; + // renderMarkdown escapes all HTML first, as on the list's work document. + glance.innerHTML = renderMarkdown(section.markdown); + }); +} +function renderProblem(item, status) { + const box = $('panel-fix'); + box.hidden = !(status.actor === 'blocked' && !item.error); + box.disabled = sending; +} +let showDetails = false; +function renderDetails(card, item, doc) { + $('panel-more').setAttribute('aria-expanded', String(showDetails)); + $('panel-more').textContent = t(showDetails ? 'panel.less' : 'panel.more'); + $('panel-details').hidden = !showDetails; + if (!showDetails) return; + const dl = $('panel-fields'); + dl.replaceChildren(); + const field = (name, value) => { if (!value) return; dl.append(el('dt', '', name), el('dd', '', value)); }; + field(t('field.status'), statusLabel(t, item)); + field(t('field.project'), item.project); + const repos = [...new Set(card.members.flatMap(member => member.repos || []))]; + if (repos.length) field(t('field.repos'), repos.join(', ')); + if (card.work) field(t('field.work'), `${card.work.sdlc.slug} · ${phaseLabel(t, card.work.sdlc.phase)} · ${card.work.sdlc.state}`); + field(t('panel.nextStep'), str(card.entry?.nextStep)); + if (!item.done && item.run) field(t('field.run'), item.run); + const members = $('panel-members'); + $('panel-members-box').hidden = card.members.length < 2; + members.replaceChildren(...card.members.map(member => { + const li = el('li', member.id === item.id ? 'member current' : 'member'); + li.append(el('span', `tag tone-${toneOf({ lane: statusOf(member).actor, working: statusOf(member).kind === 'working' })}`, statusLabel(t, member)), el('span', '', member.title)); + return li; + })); + const box = $('panel-doc'); + if (!doc) box.replaceChildren(el('p', 'hint', t('panel.noDocument'))); + else if (doc.pending) box.replaceChildren(el('p', 'hint', t('artifact.loading'))); + else if (doc.error) box.replaceChildren(el('p', 'field-error', t('artifact.failed', { message: doc.error }))); + else import('./markdown.js').then(({ renderMarkdown }) => { if (panelTarget?.id === item.id) box.innerHTML = renderMarkdown(doc.markdown); }); + const history = $('panel-history'); + const events = card.members.flatMap(member => member.events.map(event => ({ ...event, member }))).sort((a, b) => b.at.localeCompare(a.at)).slice(0, 40); + history.replaceChildren(...events.map(event => { + const li = el('li'); + li.append(el('time', '', event.at), document.createTextNode(` · ${event.who} · ${event.what}`)); + return li; + })); + if (!events.length) history.append(el('li', 'hint', t('history.empty'))); + const notes = card.members.flatMap(member => member.notes || []).map(note => note.trim()).filter(Boolean); + $('panel-notes-box').hidden = !notes.length; + $('panel-notes').textContent = notes.join('\n'); +} +$('panel-more').addEventListener('click', () => { showDetails = !showDetails; panelSig = ''; renderPanel(Date.now()); }); + +// ---------- answering ---------- +let toastTimer; +function toast(text) { + const box = $('toast'); + box.textContent = text; + box.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { box.hidden = true; }, 4000); +} +async function send(path, body, done) { + sending = true; + panelSig = ''; + renderPanel(Date.now()); + $('panel-error').hidden = true; + try { + const data = await page.api(path, body); + if (data.items) page.apply(data); + page.announce(done); + toast(done); + return data; + } catch (error) { + const message = page.say(page.sourceOf(error)); + $('panel-error').textContent = message; + $('panel-error').hidden = false; + page.showError(page.sourceOf(error)); + throw error; + } finally { + sending = false; + panelSig = ''; + renderPanel(Date.now()); + } +} +// The same request the list's choice buttons and reply box send: an ordinary reply, never an approval. +async function answer(card, item, text) { + try { + await send('/api/item', { id: item.id, version: item.version, op: 'reply', text }, t('board.sentToast')); + drafts.delete(item.id); + if (panelTarget?.id === item.id || card.target.id === item.id) $('panel-reply-text').value = ''; + } catch { /* shown */ } +} +$('panel-reply').addEventListener('submit', event => { + event.preventDefault(); + const text = page.oneLine($('panel-reply-text').value); + if (!text) { $('panel-error').textContent = t('reply.empty'); $('panel-error').hidden = false; $('panel-reply-text').focus(); return; } + if (panelCard && panelTarget) answer(panelCard, panelTarget, text); +}); +$('panel-reply-text').addEventListener('input', () => { if (panelTarget) drafts.set(panelTarget.id, $('panel-reply-text').value); }); +$('panel-reply-text').addEventListener('keydown', event => { + if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { event.preventDefault(); $('panel-reply').requestSubmit(); } +}); +$('panel-approve').addEventListener('click', async () => { + const item = panelTarget, doc = item && documents.get(docKey(item)); + if (!item || !doc?.sha || !doc.gate) return; + const words = page.oneLine($('panel-note').value); + if (words.length > 500) { $('panel-error').textContent = t('decide.length'); $('panel-error').hidden = false; return; } + try { + await send('/api/approve', { id: item.id, version: doc.version, gate: doc.gate, sha: doc.sha, words }, t('announce.approved')); + $('panel-note').value = ''; + } catch (error) { + // A changed document cannot be approved as shown: fetch it again. + if (error.status === 409) { documents.delete(docKey(item)); panelSig = ''; renderPanel(Date.now()); } + } +}); +$('panel-fix').addEventListener('click', async () => { + const item = panelTarget; + if (!item) return; + try { + const data = await send('/api/item', { id: item.id, version: item.version, op: 'fix' }, t('fix.queued')); + const launch = data.launch || 'queued'; + if (launch.startsWith('failed: ')) page.showError(t('fix.failed', { reason: launch.slice(8) })); + else if (launch === 'started') toast(t('fix.started')); + } catch { /* shown */ } +}); + +// ---------- ticket window ---------- +// Ticket sites refuse frames, so the ticket opens in one named popup docked to the screen's right edge, and that +// window follows the selection. Trade-off (decided 2026-11-19): following needs the opener link, because Chromium +// lets a page with a cut opener neither navigate nor close its popup. So a hostile http(s) ticket page could redirect +// this board window. It gains nothing: the token lives only in this page's URL fragment and memory, a redirected +// window loses both, and another origin can never read them, so a fake page cannot approve or answer anything. +let ticketWindow = null, ticketUrl = ''; +function openTicket(url) { + if (!isHttp(url)) return; + if (ticketWindow && !ticketWindow.closed) { + if (url !== ticketUrl) { ticketWindow.location.href = url; ticketUrl = url; } + ticketWindow.focus(); + return; + } + const width = Math.round(screen.availWidth * 0.45), height = screen.availHeight; + const left = (screen.availLeft || 0) + screen.availWidth - width, top = screen.availTop || 0; + const opened = window.open(url, 'sdlc-ticket', `popup=yes,width=${width},height=${height},left=${left},top=${top}`); + if (!opened) { page.showError({ key: 'panel.popupBlocked' }); return; } + ticketWindow = opened; + ticketUrl = url; + opened.focus(); +} +// Only a person's selection (a click or ←/→/j/k) moves the ticket window; live updates never call select(). +function followTicket(card) { + const url = card?.link?.url; + if (!ticketWindow || ticketWindow.closed || !isHttp(url) || url === ticketUrl) return; + ticketWindow.location.href = url; + ticketUrl = url; +} +$('panel-ticket').addEventListener('click', () => openTicket(panelCard?.link?.url)); + +// ---------- runs ---------- +let runsDay = ''; +const dayKey = ms => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }; +function runsOf() { + return list(page.feed?.runs).map(record).filter(Boolean).map(run => ({ + key: str(run.key), label: str(run.label), start: timeOf(str(run.startedAt)), end: timeOf(str(run.endedAt)), + outcome: ['ok', 'fail'].includes(run.outcome) ? run.outcome : 'unknown' + })).filter(run => Number.isFinite(run.start)); +} +function renderRuns(now) { + const runs = runsOf(), today = dayKey(now); + if (!runsDay) runsDay = today; + const days = Array.from({ length: 7 }, (_, i) => dayKey(now - (6 - i) * DAY_MS)); + const dayLabel = key => new Intl.DateTimeFormat(page.lang, { month: '2-digit', day: '2-digit', weekday: 'short' }).format(new Date(`${key}T12:00`)); + $('runs-days').replaceChildren(...days.map(key => { + const here = runs.filter(run => dayKey(run.start) === key), fails = here.filter(run => run.outcome === 'fail').length; + const button = el('button', 'day'); + button.type = 'button'; + button.dataset.day = key; + button.setAttribute('aria-pressed', String(key === runsDay)); + button.append(el('span', 'day-name', key === today ? `${dayLabel(key)} · ${t('runs.today')}` : dayLabel(key)), + el('b', 'day-count', String(here.length)), el('span', fails ? 'day-fail bad' : 'day-fail', t('runs.failCount', { count: fails }))); + return button; + })); + const here = runs.filter(run => dayKey(run.start) === runsDay).sort((a, b) => a.start - b.start); + const counts = { ok: 0, fail: 0, unknown: 0 }; + for (const run of here) counts[run.outcome]++; + $('runs-title').textContent = t('runs.title', { date: dayLabel(runsDay), count: here.length }); + $('runs-summary').textContent = t('runs.summary', counts); + // 08:00–19:00; runs outside the axis are clamped to its edge. + const base = new Date(`${runsDay}T08:00`).getTime(), span = 11 * 3600000; + const axis = $('runs-axis'); + axis.replaceChildren(...Array.from({ length: 12 }, (_, i) => { + const tick = el('span', 'tick', `${String(8 + i).padStart(2, '0')}:00`); + tick.style.left = `${(i / 11) * 100}%`; + return tick; + })); + const rows = [], bars = here.map(run => { + const end = Number.isFinite(run.end) ? run.end : Math.min(now, run.start + 60000); + const left = Math.min(100, Math.max(0, (run.start - base) / span * 100)); + const width = Math.max(0.6, Math.min(100 - left, (end - run.start) / span * 100)); + // Greedy rows; a label needs about 9% of the axis beyond its bar. + let row = rows.findIndex(edge => edge <= left); + if (row < 0) { rows.push(0); row = rows.length - 1; } + rows[row] = left + width + 9; + const bar = el('div', `run ${run.outcome}`); + bar.style.left = `${left}%`; + bar.style.width = `${width}%`; + bar.style.top = `${row * 1.9}rem`; + bar.append(el('span', 'run-bar'), el('span', 'run-label', [run.key, run.label].filter(Boolean).join(' · '))); + bar.title = `${clock(run.start)}${Number.isFinite(run.end) ? `–${clock(run.end)}` : ''} · ${t(`runs.${run.outcome}`)}`; + return bar; + }); + const track = $('runs-track'); + track.style.height = `${Math.max(1, rows.length) * 1.9 + 0.6}rem`; + track.replaceChildren(...bars); + $('runs-empty').hidden = here.length > 0; + $('runs-empty').textContent = t('runs.empty'); +} +$('runs-days').addEventListener('click', event => { + const button = event.target.closest('[data-day]'); + if (!button) return; + runsDay = button.dataset.day; + renderRuns(Date.now()); +}); + +// ---------- health ---------- +function renderHealth() { + const feed = record(page.feed); + const alerts = feedAlerts(feed); + $('health-alerts').hidden = !alerts.length; + $('health-alert-list').replaceChildren(...alerts.map(alert => { + const li = el('li', `alert-row ${alertLevel(alert)}`); + li.append(el('span', 'dot'), el('span', '', alert.text)); + const since = timeOf(str(alert.since)); + if (Number.isFinite(since)) li.append(el('span', 'muted', dateTime(since))); + return li; + })); + const sections = list(feed?.health).map(record).filter(Boolean); + $('health-sections').replaceChildren(...sections.map(section => { + const box = el('section', 'health-card'); + box.append(el('h3', '', str(section.title))); + const dl = el('dl', 'health-rows'); + for (const row of list(section.rows).map(record).filter(Boolean)) { + const dd = el('dd', `level-${['ok', 'warn', 'bad'].includes(row.level) ? row.level : 'none'}`); + dd.append(el('span', 'dot'), el('span', '', str(row.value))); + dl.append(el('dt', '', str(row.label)), dd); + } + box.append(dl); + return box; + })); + const generated = timeOf(str(feed?.generatedAt)); + $('health-generated').textContent = Number.isFinite(generated) ? t('feed.generated', { time: dateTime(generated) }) : ''; + $('health-empty').hidden = sections.length > 0 || alerts.length > 0; +} + +// A page with an unsent answer or a request in flight is never closed for a newer window. +page.addBusyCheck(() => sending || [...drafts.values()].some(draft => draft.trim()) || !!$('panel-note').value.trim()); +page.subscribe(() => { loaded = true; render(); }); +render(); +// Event times turn into "N days" and the clock moves on without a snapshot. +setInterval(() => { if (loaded) render(); }, 60000); diff --git a/todo/page/index.html b/todo/page/index.html index 0c5bc59..cbb34b8 100644 --- a/todo/page/index.html +++ b/todo/page/index.html @@ -5,29 +5,125 @@ -To-do +To-do board + - -
+ +
+
+

+ +
+
+ + Connecting + + + +
+ + + + +
+
+
+ + +
+
+

Loading the board…

+ + +
+ +
+ +
+
+

+
+
+
+ +
+

Done + Failed + No result

+
+ +
+ +
+

The feed has no health information.

+

+
+ + + +
diff --git a/todo/status.mjs b/todo/status.mjs index 3c12530..abff601 100644 --- a/todo/status.mjs +++ b/todo/status.mjs @@ -50,3 +50,86 @@ export function ticketGroups(items) { } return entries; } + +// ---------- board ---------- +// The board shows each sdlc phase as a column and who acts next as a lane. Open items that share one ticket +// link are one card. An optional feed (untrusted, written by an outside tool) may move a card that waits on an +// agent or on others; it never hides a turn of the human's or a block that comes from the to-do file. +export const boardColumns = ['intent', 'plan', 'build', 'evidence', 'deliver']; +export const boardLanes = ['you', 'others', 'blocked', 'agent']; +const urgency = ['you', 'blocked', 'others', 'agent']; +export const DAY_MS = 86400000, STALE_DAYS = 14, DONE_DAYS = 7; +// Event times are local "YYYY-MM-DD HH:MM"; feed times are ISO. Anything else is NaN. +export const timeOf = value => typeof value !== 'string' || !value ? NaN : + Date.parse(/^\d{4}-\d{2}-\d{2} \d/.test(value) ? value.replace(' ', 'T') : value); +export function lastEventAt(items) { + let last = NaN; + for (const item of items) for (const event of item.events || []) { + const at = timeOf(event.at); + if (Number.isFinite(at) && !(at <= last)) last = at; + } + return last; +} +export function doneAtOf(item) { + const events = item.events || []; + return timeOf(([...events].reverse().find(event => /^(done|DONE)\b/.test(event.what)) || events.at(-1))?.at); +} +const isEntry = value => !!value && typeof value === 'object' && !Array.isArray(value); +// A feed entry matches a card by its ticket label (A20-1531), else by a member's sdlc slug (as key or `slug`). +export function feedEntryOf(feed, members) { + const entries = isEntry(feed) && isEntry(feed.items) ? feed.items : null; + if (!entries) return null; + const entry = key => typeof key === 'string' && key && Object.hasOwn(entries, key) && isEntry(entries[key]) ? entries[key] : null; + const slugs = members.map(member => member.sdlc?.slug).filter(Boolean); + return members.map(member => entry(member.link?.label)).find(Boolean) || slugs.map(entry).find(Boolean) || + Object.values(entries).find(value => isEntry(value) && typeof value.slug === 'string' && slugs.includes(value.slug)) || null; +} +// Who an answer goes to on a card: the human's turn, preferring offered choices, then a gate, then an item outside sdlc. +export function targetOf(members) { + const yours = members.filter(member => statusOf(member).actor === 'you'); + if (yours.length) return yours.find(member => member.choices?.length) || yours.find(member => statusOf(member).gate) || + yours.find(member => !member.sdlc) || yours[0]; + return members.find(member => statusOf(member).actor === 'blocked') || members.find(member => member.sdlc) || members[0]; +} +const own = (entry, name) => entry && typeof entry[name] === 'string' ? entry[name] : ''; +// Cards in item order: open items grouped by link, then items done in the last DONE_DAYS days, one card each. +export function boardCards(items, feed = null, now = Date.now()) { + const groups = new Map(), sets = []; + for (const item of items) { + if (item.done) continue; + const url = item.link?.url; + if (url && groups.has(url)) { groups.get(url).push(item); continue; } + const members = [item]; + if (url) groups.set(url, members); + sets.push(members); + } + const cards = sets.map(members => { + const work = members.find(member => member.sdlc) || null, entry = feedEntryOf(feed, members); + const actor = urgency.find(name => members.some(member => statusOf(member).actor === name)); + const lane = ['agent', 'others'].includes(actor) && boardLanes.includes(entry?.turn) ? entry.turn : actor; + const phase = work?.sdlc?.phase; + const needsHuman = actor === 'you' || actor === 'blocked'; + // The feed may move a card between work columns, never one the human must act on, and never an open card to Done. + const column = !needsHuman && boardColumns.includes(entry?.column) ? entry.column : + [...boardColumns, 'done', 'legacy'].includes(phase) ? phase : 'general'; + const times = [lastEventAt(members), timeOf(own(entry, 'updatedAt'))].filter(Number.isFinite); + const last = times.length ? Math.max(...times) : NaN, pinned = members.some(member => member.pin); + return { + key: members[0].link?.url ? `link:${members[0].link.url}` : `item:${members[0].id}`, + members, target: targetOf(members), work, link: members.find(member => member.link)?.link || null, + column, lane, actor, entry, chip: own(entry, 'chip'), last, pinned, needsHuman, + working: members.some(member => statusOf(member).kind === 'working'), + // A reply waits for an agent to read it: the human already answered this card. + sent: members.some(member => member.status !== 'blocked' && statusOf(member).kind === 'handoff'), + stale: !needsHuman && !pinned && Number.isFinite(last) && now - last > STALE_DAYS * DAY_MS + }; + }); + for (const item of items) { + const at = item.done ? doneAtOf(item) : NaN; + if (!Number.isFinite(at) || now - at > DONE_DAYS * DAY_MS) continue; + cards.push({ key: `done:${item.id}`, members: [item], target: item, work: item.sdlc ? item : null, link: item.link || null, + column: 'done', lane: 'done', actor: 'done', entry: null, chip: '', last: at, pinned: false, needsHuman: false, + working: false, sent: false, stale: false }); + } + return cards; +} diff --git a/todo/todo.mjs b/todo/todo.mjs index d0f4171..00804fb 100644 --- a/todo/todo.mjs +++ b/todo/todo.mjs @@ -24,6 +24,8 @@ const usage = `Usage: node ${path.join(kit, 'todo', 'todo.mjs')} 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). + The app sits in the tray with the Needs-you count and opens the board on launch and on a click; + SDLC_TODO_BACKGROUND=1 (e.g. for a login item) starts it in the tray alone. 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')} serve keeps a web server for the app; launches share it through ${core.sessionPath()}. --lang ${languages.join('|')} sets the UI language; default SDLC_TODO_LANG, else ${defaultLanguage}.`; diff --git a/todo/web.mjs b/todo/web.mjs index 5414f44..1e25e2f 100644 --- a/todo/web.mjs +++ b/todo/web.mjs @@ -20,6 +20,7 @@ const assets = new Map([ ['/app.js', ['page/app.js', js]], ['/app.css', ['page/app.css', 'text/css; charset=utf-8']], ['/markdown.js', ['page/markdown.js', js]], + ['/board.js', ['page/board.js', js]], ['/i18n.mjs', ['i18n.mjs', js]], ['/status.mjs', ['status.mjs', js]], ...languages.map(language => [`/locales/${language}.mjs`, [`locales/${language}.mjs`, js]]) @@ -78,6 +79,21 @@ function briefDocument(item) { catch (error) { fail(error.code === 'ENOENT' ? 404 : 409, `brief not readable: ${item.brief}`); } return { gate: '', file: item.brief, markdown: bytes.toString('utf8'), sha: createHash('sha256').update(bytes).digest('hex') }; } +// The board's optional feed: JSON another tool writes. It is untrusted text; a missing file is no feed, and an +// unreadable or invalid one says so instead of keeping stale data. +const feedLimit = 1024 * 1024; +// Beside the list, like todo-working.json: ~/.sdlc/todo-feed.json for the default list. +export const feedPath = (file = core.todoPath()) => process.env.SDLC_TODO_FEED || path.join(path.dirname(file), 'todo-feed.json'); +export function readFeed(file) { + let bytes; + try { bytes = fs.readFileSync(file); } + catch (error) { return error.code === 'ENOENT' || error.code === 'ENOTDIR' ? { feed: null, error: '' } : { feed: null, error: 'feed not readable' }; } + if (bytes.length > feedLimit) return { feed: null, error: 'feed too large' }; + try { + const feed = JSON.parse(bytes.toString('utf8')); + return feed && typeof feed === 'object' && !Array.isArray(feed) ? { feed, error: '' } : { feed: null, error: 'feed is not a JSON object' }; + } catch { return { feed: null, error: 'feed is not valid JSON' }; } +} function readBody(req) { return new Promise((resolve, reject) => { let size = 0, tooLarge = false; @@ -137,17 +153,19 @@ export async function liveSession(file = core.sessionPath()) { } catch { return null; } } -export async function startWeb({ file = core.todoPath(), kit = defaultKit, port = 0, open = false, onUrl, statusRunner = execute, lang = defaultLanguage, session = '' } = {}) { +export async function startWeb({ file = core.todoPath(), kit = defaultKit, port = 0, open = false, onUrl, statusRunner = execute, lang = defaultLanguage, session = '', feed = feedPath(file) } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('invalid port'); if (!isLanguage(lang)) throw new Error(`invalid language: ${lang}`); if (!onUrl && !open && !process.stdout.isTTY) throw new Error('web requires a terminal or --open'); const token = randomBytes(16).toString('hex'), expected = Buffer.from(token); const authorized = value => typeof value === 'string' && Buffer.byteLength(value) === expected.length && timingSafeEqual(Buffer.from(value), expected); const clients = new Set(); + let feedState = readFeed(feed); const payload = () => { const model = core.load(file); // 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 }; + return { items: core.withWorking(model.items, file).map((item, i) => ({ ...item, version: core.itemVersion(model.items[i], model), turn: statusOf(item) })), file, lang, + feed: feedState.feed, ...(feedState.error ? { feedError: feedState.error } : {}) }; }; const sendEvent = (res, value, event = '') => res.write(`${event ? `event: ${event}\n` : ''}data: ${JSON.stringify(value)}\n\n`); const broadcast = () => { @@ -187,6 +205,8 @@ export async function startWeb({ file = core.todoPath(), kit = defaultKit, port } else if (url.pathname === '/api/live') { // Liveness only: /api/items syncs every sdlc item and can take seconds on a long list. json(200, { ok: true }); + } else if (url.pathname === '/api/feed') { + json(200, feedState); } else if (url.pathname === '/api/items') { await synced(); json(200, payload()); @@ -262,12 +282,14 @@ 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), stopWorking = core.watchWorking(file, broadcast); + // Polling stat survives a feed that does not exist yet and one replaced by rename. + const stopFeed = core.watch(feed, () => { feedState = readFeed(feed); broadcast(); }); const keepalive = setInterval(() => { for (const res of clients) res.write(': keepalive\n\n'); }, 15000); keepalive.unref(); let closing; const close = () => { if (!closing) { - stopWatch(); stopWorking(); + stopWatch(); stopWorking(); stopFeed(); clearInterval(keepalive); if (session && readSession(session)?.token === token) fs.rmSync(session, { force: true }); for (const res of clients) res.end(); From 7caf914b9de95f201bbad6bad03091ebfe30fc0b Mon Sep 17 00:00:00 2001 From: cskwork <76669236+cskwork@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:23:53 +0900 Subject: [PATCH 2/2] =?UTF-8?q?release:=20v3.0.0=20=EB=B3=80=EA=B2=BD=20?= =?UTF-8?q?=EA=B8=B0=EB=A1=9D=20=EA=B2=80=EC=A6=9D=20=EC=A4=84=EC=97=90=20?= =?UTF-8?q?CI=20=ED=86=B5=EA=B3=BC=20=EA=B2=B0=EA=B3=BC=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- log/changelog-v3.0.0.md | 1 + 1 file changed, 1 insertion(+) diff --git a/log/changelog-v3.0.0.md b/log/changelog-v3.0.0.md index 366406c..9f88096 100644 --- a/log/changelog-v3.0.0.md +++ b/log/changelog-v3.0.0.md @@ -17,6 +17,7 @@ This release is major because the default screen changed: the page opens on the ## Verification +- CI selftest passed on ubuntu, macos and windows (PR #95). - `node --test tests/*.test.mjs`: 232 tests, 226 pass, 6 fail, all timing failures under machine load (`HTTP request timed out`, `timed out waiting for TUI state`, `timed out waiting for lock`). Rerun alone, 5 of the 6 pass. The sixth, "S14: twenty parallel CLI writers…", also fails on the previous release commit 518a1d6, and this release does not touch the lock code. - New tests cover board card grouping, lane and column with and without a feed, a feed that must not hide a card needing the human or move an open card to done, feed endpoint auth, a missing or invalid feed, the single-window rule, and test helpers that never read the real feed. `tests/todo-board.test.mjs`, `tests/todo-page.test.mjs` and `tests/todo-web.test.mjs` pass. - `todo/app`: `cargo build --release` passes, and `cargo test --release --offline` passes 8 tests.