GlanceFlow: see what Claude is doing, at a glance. Hides tool rows and shows one plain-English checklist above the prompt, with progress, helpers, history, a…

See what Claude is doing, at a glance. A calm checklist above the prompt: the plan, the step Claude is on, how far along it is, and a clear signal when Claude needs you.

<sub>A scripted job: the checklist is drawn by GlanceFlow 0.24.6 itself; the window and the notice around it are illustrative.</sub>
You need:
claude plugin test in any folder: "served off" means they aren't on yet.Then run:
claude plugin marketplace add Antreas-Strb/glanceflow
claude plugin install glanceflow@claude-mods
Then open a new chat. The first time, three short welcome cards above the prompt show what the checklist is, what Needs you means and where Settings and History are. Press Next ▶ or Skip; /glanceflow tour shows them again.
Update: claude plugin marketplace update claude-mods, then claude plugin update glanceflow@claude-mods, then open a new chat.
Coming from Glance? GlanceFlow is its new name. Uninstall the old one first (claude plugin uninstall glance@claude-mods), then install glanceflow@claude-mods. Your settings and history come along on the first chat; the command is now /glanceflow.
Remove: claude plugin uninstall glanceflow@claude-mods.
The button above the prompt cycles Simple → Details → Off; in the Desktop app it is the View menu at the top right, with Simple, Detailed and Off. The view and on/off are remembered after a restart.
62% 1m 52s · ~1m left in the terminal, or under a minute left in the Desktop app; finished steps show how long they tookExplore · Haiku 4.5 · low effort3k new · 45k cached; Claude's final answer counts in the job's total onlyPlan usage: 5-hour 42% · weekly 18% · chat 34% full (Usage: in the Desktop app)$0.42, where Claude Code keeps a cost (pay-as-you-go API use); the History panel shows it per job and per day
<sub>Drawn by GlanceFlow 0.24.6 itself, as the Desktop app shows it, for a sample job. The tool rows in the chat above the checklist are not shown here.</sub>
Working · Build my landing page · 2 of 4 done · about 2m left). When the band is narrow, a header leaves out whole pieces rather than cut a word, and its bold words get shorter but stay whole (In the background, then Background). A screen reader reads each thing once: a line under a step starts in empty room, and an icon's label never repeats the words beside it (the current step's icon says Now, a warning's says Notice). The current step has a blue mark and the only bar; finished steps get a green ringed check; amber always means Claude needs you. The colour sits in the icon, and the words keep the app's text colour, so they read on a light window too. Every control is the app's own button. The View menu (Simple, Detailed or Off) sits at the top right; under the checklist the places to go (Plan, History, Settings) sit on the left, and everything that acts sits together on the right: Where we left off after a tidy-up, Tidy up now, Fresh chat, then Pause, Continue, or Aim higher and Start, the main one last. Another mod that draws only buttons (Replay, say) has them join that group. The welcome cards and the empty band keep the same layout. Fresh chat shows once the job has stopped or finished; while a stopped job's chat is full, Tidy up now takes its place. At a usage limit the button reads Check again. Settings are rows with a menu each, as on a Mac. The panels have no extra Close buttons, since the app's own × closes them. The terminal keeps its one-cell symbols: where this README writes ▤ Plan, ≣ History, ⚙ Settings, ‖ Pause or ▶ Continue, the Desktop app shows the same button by its name alone.Done when: …, and the Team report lists it under each finished job./glanceflow approve on, and Claude shows its plan and waits. Press ▶ Start, or tell Claude what to change and it lays out a new plan./glanceflow ship on. In a project that pushes to GitHub, a finished job offers ⇡ Ship it. Press it twice and Claude tidies the changes, commits, opens a pull request, waits for the checks and asks you to approve the exact commit before it squash-merges. If a check fails it stops and shows why. With the Desktop app's auto-archive on, the merged pull request archives the chat, so finished chats don't pile up.taking longer instead of a guess, and the total waits until it can be estimated again. A plan of more than five steps folds its finished steps, and the steps after the next one, into a line each; ▤ Plan shows them all.Now: Check the page on a phone screen, otherwise a short phrase like Reading files (3) or Running the tests. No file names or commands. In the terminal it sits under the current step; in the Desktop app it follows the step's bar.For you: … until the next job, so it doesn't get lost in a long reply. Choices Claude made that neither the plan nor you settled are noted too. ▤ Plan lists both, and the Team report puts the first under "Needs attention" and the second under each job as Decided: ….OK to build and publish the package? It deletes files and publishes a package. The risks it names: deleting files, rewriting git history, publishing a package, uploading your changes, deploying, installing packages, admin rights and running code from the internet.tested, not tested or tests failed in its header (✓ All done · Fix the sign-up form · tested · took 3m), ▤ Plan says it beside each step, and the Team report beside each job. An edit after the tests passed makes it not tested again. Changes to text files like a README need no test./glanceflow goal keep sign-ups working on every phone sets the outcome beyond any one task. Claude plans each job toward it and says how the job moves it forward; ▤ Plan shows it, and the Team report adds a line per goal: how many tasks, how many finished and how many were tested. /glanceflow goal says what it is; /glanceflow goal off clears it.Added contact.html · changed styles.css and index.html), helpers' edits included, and ≣ History shows them under each job. Names only; the folder shows where two files share a name./glanceflow sound on plays a short chime when Claude needs you, gets stuck, or finishes a job that took over a minute, so you can look away. /glanceflow sound voice also says it ("Claude needs you"). Off by default (turn it on in ⚙ Settings). Works on macOS, Windows and Linux; on Linux it uses the sound player the computer has (PipeWire, PulseAudio or ALSA) and, for the words, speech-dispatcher or eSpeak./glanceflow notify on shows a notice from your computer when Claude needs you, gets stuck, or finishes a job that took over a minute, with the reason in it. You see it even while you work in another app. It goes through Claude Code first, so a Notification hook you set up (a phone push, ntfy, Slack) gets it too, as plugin_notification, and you hear about it away from your desk; where Claude Code shows no text (the Desktop app, a bare bell), your computer shows it. Off by default (turn it on in ⚙ Settings). Works on macOS, Windows and Linux./glanceflow language el (or Language in ⚙ Settings) shows all of GlanceFlow in Greek: the band, the Plan, History, Settings, notices and the Team report. Claude then writes the steps, what each got done and the For you items in Greek too, and a Greek request keeps its own words as the job's title. /glanceflow language en goes back to English, the default./glanceflow calm on stops everything that moves (the sweeping bar, the helper spinners) and shows statuses in bold.?, or ; in Greek) shows Needs you and chimes, instead of All done. When Claude ends on a question, the Needs you line shows the question itself, in Claude's own last sentence (Which colour should the buttons be?), so you don't have to look through the chat for it. The status line and the desktop notice say the same: one plain line of up to 160 characters, with keys and passwords masked. Claude waiting for its own helpers is never Needs you.no news for 3 minutes and tells you that Esc stops Claude. With sounds or desktop notices on, you hear or see it too. It clears by itself as soon as Claude moves again.GlanceFlow 0.26.0). Press Check for updates and it fetches the marketplace you installed it from; when a newer version is out, the button becomes Update to 0.27.0, which installs it. Open a new chat to use it. A copy that runs from a folder (a checkout, say) updates where it lives, so it gets no button. Nothing is checked until you press./glanceflow guard off if it gets in your way.resets at 18:40); with desktop notices on, you get a notice too. A "Tidy it up" button ("Tidy up now" in the Desktop app) appears when the chat is half full (pick the point in ⚙ Settings). Tidying up first has Claude save a checkpoint of the work (goal, what is done and left, decisions, the next step); the compaction keeps it, and Claude keeps reading it for the rest of the chat, so nothing important is forgotten. Afterwards the checklist offers Where we left off, which shows you that checkpoint in a side panel (also in ⚙ Settings, or /glanceflow checkpoint).
<sub>Drawn by GlanceFlow 0.24.6 itself, as the Desktop app shows each header, for a sample job; the line under each says what it means.</sub>
Under the checklist, ‖ Pause stops Claude while it works, and ▶ Continue picks the same job up again, with nothing to type. Continue also shows after Esc, when Claude got stuck, or when it is waiting with steps left; in the Desktop app, after Claude got stuck it reads Try again, or Check again at a usage limit. The header says ‖ Paused after Pause and ■ Stopped after Esc. /glanceflow pause and /glanceflow continue do the same, and so does typing "continue" (or "συνέχισε") after Esc: the same job picks up, plan and all.
The checklist also survives closing Claude Code: resume the chat (claude --resume, or reopen it in the Desktop app) and it comes back as you left it. Work that was under way shows as ‖ Paused, so ▶ Continue picks it up; a plan waiting for Start still waits. GlanceFlow keeps the last 20 chats this way.
▤ Plan under the checklist (or /glanceflow plan) opens the whole plan in a side panel, with what the checklist has no room for: when the job started and about when it will be done, every step however long the plan, with long names shown whole, what each finished step got done and how long it took, about how long each step still to come should take, what Claude is doing now in its own words, and every helper. In Details it adds the command or file Claude is working on, tokens per step, the job's cost and plan usage. It stays live while Claude works, so the checklist above the prompt can stay short.

<sub>Drawn by GlanceFlow 0.24.6 itself, as the Desktop app shows it, for a sample job.</sub>
⚙ Settings under the checklist (or /glanceflow settings) puts every choice in one panel. Each shows what is picked and a line on what that choice does: the view (Simple, Details or Off), sounds (with ▶ Play it to hear them), desktop notices, other chats (the band names another chat on this computer that needs you, from any project; turn it off before you share your screen, or use /glanceflow others off), calm mode, whether to approve the plan first, the password guard, and when to tidy up the chat (never, or at 40, 50, 60 or 75% full), with a Tidy up now button. Changes apply right away and stay for your next chats.

<sub>Drawn by GlanceFlow 0.24.6 itself, as the Desktop app shows it, for a sample job.</sub>
≣ History under the checklist (or /glanceflow history) opens a side panel with today's jobs in this project: when each started, how it ended (done, stopped or stuck), steps done, how long it took and its tokens, the files it added or changed, with the day's totals at the bottom.

<sub>Drawn by GlanceFlow 0.24.6 itself, as the Desktop app shows it, for a sample job.</sub>
In the panel, ◀ Earlier, the day drop-down, Later ▶ and Today move between days (Previous day and Next day in the Desktop app) (or type /glanceflow history yesterday, /glanceflow history 2026-10-06). The history stays on this computer and keeps 30 days.
Team report turns the day into a short update in plain words for the team, a manager or a CEO, and copies it to paste into Slack, Teams or an email: what got done (step by step, in Claude's words), what is still open and what is next, what needs a decision, and the time spent. This week switches it to the 7 days up to the day picked, for a weekly update or a retro. In the Desktop app the buttons read Day report and Week report. No tokens, models or file names, and quick questions are left out.

<sub>Drawn by GlanceFlow 0.24.6 itself, as the Desktop app shows it, for a sample job.</sub>
Your week (or /glanceflow week; All projects this week in the Desktop app) is a short summary just for you, across every project: how many steps Claude checked off in how many tasks, the time at work, your busiest day and the biggest tasks. It covers the 7 days up to the day picked and is copied, ready to keep or share.
Your week with Claude · 30 Sept 2026 to 6 Oct 2026
Claude checked off 23 steps in 9 tasks, and finished 7 of them.
Time at work: 4 h 10 min, across 3 projects.
Busiest day: Tuesday, with 4 tasks.
Biggest tasks
• Build the pricing page (6 steps)
• Write the welcome email (4 steps)
• Fix the contact form (3 steps)
↻ Fresh chat under the checklist (or /glanceflow handoff), shown once the chat has some work in it (in the Desktop app, once the job has stopped or finished; while a stopped job's chat is full, Tidy up now takes its place), moves the work to a fresh chat: when a chat is too long, close to its limits, or whenever you want a clean start. Press it twice (the first press asks to confirm). Claude writes a short handoff note (goal, what is done, what is left, decisions, the next step), the chat is cleared, and the note is sent as the fresh chat's first message. The note is also saved: /glanceflow handoff note puts the last one back in the prompt box.
⇡ Ship it shows once a job is done, when Finish on GitHub is on and the project pushes to GitHub (or use /glanceflow ship). The first press arms it, and a second press within 8 seconds sends Claude the close-out:
gh sign-in.gh pr checks --watch. Passing checks are not permission to merge: Claude shows the pull request link, the checks and the full head SHA, and asks you to reply exactly Approve merge <SHA>. Any other reply leaves the pull request open.gh pr merge --squash --delete-branch --match-head-commit <SHA>. If the head changed, Claude asks again. It never merges with --admin or --auto or gets around branch protection: if the merge is blocked, Claude says why and stops. While Ship it runs, GlanceFlow blocks direct merge commands it can inspect unless they use the exact SHA you approved and run on their own, so a failed merge can't pass for a successful one. A merge run through a wrapper such as env, sudo, eval or ( … ) is always blocked, and so is a gh api, curl or wget call that merges a pull request or branch, turns on auto-merge or adds the pull request to a merge queue. An MCP tool that does any of those, such as the GitHub MCP server's merge_pull_request, is blocked too. For Bash, GlanceFlow reads only the literal shell words written in the command it is given: it rebuilds quotes, escapes, $'…' and continued lines, and refuses a gh alias or extension, a gh pr flag placed before its subcommand, and gh command words that are not written out. It doesn't run or fully parse the shell, so a merge that a variable, file, script, shell alias, interpreter or another program puts together or passes on at runtime is not guaranteed to be caught, and your repository's branch protection remains the backstop.The steps follow the finish flow of Ponytail, pstack and Cursor's thermo-nuclear code quality review. In the Desktop app, Settings → Claude Code → Auto-archive sessions when their pull request closes then archives the chat.
| Command | What it does |
|---|---|
/glanceflow | Turns GlanceFlow on or off |
/glanceflow on, /glanceflow off | Turns it on or off |
/glanceflow details | Switches between Simple and Details |
| /glanceflow details on, /glanceflow details off | Picks Details or Simpl
hooks/register.tsx 8 lines1import type { Register } from 'claude-code'
2
3import { registerGlance } from './glance'
4
5export const register: Register = on => {
6 registerGlance(on)
7}
8hooks/glance.tsx 4363 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, RenderChildren, RenderElement, RenderInput, RenderSurface, Timer } from 'claude-code'
3
4import type {
5 GlanceFile,
6 GlanceChecklist,
7 GlanceHelper,
8 GlanceHistoryEntry,
9 GlanceHistoryView,
10 GlancePhase,
11 GlanceTask,
12 GlanceUpdate,
13 GlanceUsage,
14} from '../types'
15import {
16 HISTORY_PREFIX,
17 WEEK_DAYS,
18 clockTime,
19 dayEntries,
20 dayFromArgument,
21 dayKey,
22 entryFiles,
23 entryFromChecklist,
24 expiredHistoryKeys,
25 filesNote,
26 historyDay,
27 historyKey,
28 longDay,
29 mergedEntries,
30 projectName,
31 shiftDay,
32 weekSummary,
33 paceFromHistory,
34 plainDuration,
35 sharedDayKeys,
36 upsertEntry,
37} from './history'
38import { findSecrets, maskPrivate } from './privacy'
39import { currentLang, setLang, tr } from './words'
40import type { Lang } from './words'
41import {
42 MAX_DETAIL,
43 CHECK_WORDS,
44 MAX_NAME,
45 NATIVE_PLAN,
46 NATIVE_WRAP_UP,
47 isNativeCall,
48 nativeAsk,
49 nativePlan,
50 PLUGIN,
51 QUESTION,
52 RESUME_PREFIX,
53 WAITING,
54 activityOf,
55 activityTarget,
56 apiErrorSentence,
57 applyCheck,
58 applyProgress,
59 askedMergeSha,
60 asksQuestion,
61 carryTokens,
62 checkResult,
63 cleanName,
64 currentStepId,
65 durationWords,
66 formatCost,
67 formatDuration,
68 formatLeft,
69 formatTokens,
70 hasUnfinishedWork,
71 headerDetails,
72 isBusy,
73 isContinueWords,
74 isFinished,
75 isLatinText,
76 isMcpMergeAction,
77 isNewerVersion,
78 isStartWords,
79 jobCheck,
80 jobCost,
81 leftLabel,
82 liftButtons,
83 localTimes,
84 needsCheck,
85 needsText,
86 noticeBody,
87 otherChats,
88 otherChatsWords,
89 overallProgress,
90 ownWords,
91 permissionWords,
92 prettyModel,
93 projectPath,
94 questionOf,
95 reconcileBackground,
96 reportOf,
97 resetTime,
98 runsCheck,
99 sentenceCase,
100 sizeOf,
101 stampTimes,
102 staleResumeKeys,
103 stepEstimate,
104 timeLeft,
105 todosToTasks,
106 tokenNote,
107 tourNeeds,
108 wholePieces,
109 widthOf,
110 fit,
111 settle,
112 task,
113 toggled,
114 runsPowerShellMerge,
115 runsPrMerge,
116 unsafeMerge,
117 unsafePowerShellMerge,
118} from './logic'
119
120import type { SavedChecklist } from './logic'
121import { kitOf } from './kit'
122import { GLYPH } from './look'
123import type { IconName } from './look'
124
125export { activityOf, asksQuestion, carryTokens, cleanName, fit, formatCost, formatTokens, headerDetails, isButtonsOnly, isContinueWords, isLatinText, isStartWords, liftButtons, localTimes, ownWords, prettyModel, questionOf, resetTime, sentenceCase, tokenNote, wholePieces } from './logic'
126const PLAN_TOOL = `mcp__${PLUGIN}__plan_steps`
127const PROGRESS_TOOL = `mcp__${PLUGIN}__report_progress`
128const ALWAYS_ALLOWED = new Set([
129 'ToolSearch',
130 'TodoWrite',
131 'TaskCreate',
132 'TaskUpdate',
133 'AskUserQuestion',
134 // Claude Code's own plan approval, in plan mode.
135 'ExitPlanMode',
136 // Claude Desktop's own task list is a plan too, and its end-of-turn box closes one.
137 NATIVE_PLAN,
138 NATIVE_WRAP_UP,
139 PLAN_TOOL,
140 PROGRESS_TOOL,
141])
142const STORE_KEY = 'glanceEnabled'
143const DETAIL_KEY = 'glanceDetail'
144const SOUND_KEY = 'glanceSound'
145const CALM_KEY = 'glanceCalm'
146const LANGUAGE_KEY = 'glanceLanguage'
147const GUARD_KEY = 'glanceGuard'
148const APPROVE_KEY = 'glanceApprove'
149const SHIP_KEY = 'glanceShip'
150const NOTICE_KEY = 'glanceNotice'
151// Whether the band names the other chats that need the person; on unless turned off.
152const OTHERS_KEY = 'glanceOthers'
153const TOUR_KEY = 'glanceTour'
154/**
155 * The welcome, three short cards the first time: what the checklist is, what Needs you means, where the rest lives.
156 * Elsewhere than the terminal the words keep the text colour and the yellow is the bell beside them.
157 */
158const tourCards = (isVector: boolean) => [
159 tr('A checklist shows here when you ask Claude for something with a few steps: each step, how far along it is, and about how long is left.'),
160 tourNeeds(isVector ? tr('beside a yellow bell') : tr('in yellow')),
161 tr('Settings, below, holds every choice. History shows your past jobs and Your week. To see this welcome again, type /glanceflow tour.'),
162]
163const TOUR_CARDS = 3
164const HANDOFF_KEY = 'lastHandoff'
165// Below this width the mode button drops the name; below METER_MIN_COLUMNS the bars go, so step names keep their room.
166const NARROW = 60
167const METER_MIN_COLUMNS = 50
168// Longer plans fold finished and later steps into one line each; the Plan panel has them all.
169const COMPACT_AFTER = 5
170const MAX_SUMMARY = 100
171/** The most each of a job's For you and Decided on its own lists keeps. */
172const MAX_NOTES = 8
173const METER = 10
174const LABEL_WIDTH = 7
175const TICK_MS = 250
176// Calm mode redraws only to keep times current.
177const CALM_TICK_MS = 5000
178// A job shorter than this finishes without a sound.
179const LONG_JOB_MS = 60_000
180const COLLAPSE_MS = 5000
181const RESEND_WINDOW_MS = 2 * 60 * 1000
182const LIMIT_WARN = 80
183const LIMIT_ALERT = 95
184// How full the chat gets before the band offers to tidy it up, unless the person picks another point.
185const TIDY_AT_DEFAULT = 50
186const TIDY_CHOICES = [0, 40, 50, 60, 75] as const
187const TIDY_KEY = 'glanceTidyAt'
188const CHECKPOINT_KEY = 'lastCheckpoint'
189// The person's standing goal for a project (/glanceflow goal), under this prefix and the project's folder.
190const GOAL_PREFIX = 'goal:'
191const MAX_GOAL = 80
192// Up to 0.24 every chat's checklist sat under this one key; now each has its own (RESUME_PREFIX).
193const OLD_RESUME_KEY = 'glanceResume'
194// The recent chats whose checklists are kept, so a resumed chat picks up where it was.
195const RESUME_KEEP = 20
196const LIMIT_LABEL: Record<string, string> = { five_hour: '5-hour', seven_day: 'weekly', spend_limit: 'spending' }
197
198const DENIED = 'you said no to a step, so Claude paused'
199const PLAN_MODE_WAIT = `Plan mode: write the plan and hand it over for approval first. Once the person approves it, call ${PLAN_TOOL} with that plan's own steps, then do the work.`
200const FAILING = 'a step keeps failing, Claude is trying another way'
201const STALLED = 'no news for 3 minutes. Press Esc to stop Claude, or give it a little longer'
202// No sign of life from Claude (a piece of its reply, a tool starting or ending) for this long while it works.
203const STALL_MS = 3 * 60_000
204const PERMISSION = "Answer Claude's request in the chat"
205// What a mark beside a state's own bold word says: the word follows, so a screen reader hears it once, not twice.
206const STATUS = () => tr('Status')
207// What a mark beside a notice says: a usage limit, a full chat, a tidy-up, a panel with nothing in it yet. The words
208// beside it say which; a panel's own name is its title's, read just before.
209const NOTICE = () => tr('Notice')
210const APPROVE = 'Read the plan, then press Start or tell Claude what to change'
211
212const enabledAtom = atom({ plugin: 'glanceflow', key: 'glanceEnabled' } as const, true)
213const detailAtom = atom({ plugin: 'glanceflow', key: 'detailLevel' } as const, 'simple')
214const checklistAtom = atom({ plugin: 'glanceflow', key: 'checklist' } as const, null)
215const tickAtom = atom({ plugin: 'glanceflow', key: 'tick' } as const, 0)
216const NO_USAGE: GlanceUsage = { limits: [], limitPercent: null, limitLabel: null, limitResetsAt: null, contextPercent: null, costUsd: null }
217const usageAtom = atom({ plugin: 'glanceflow', key: 'usage' } as const, NO_USAGE)
218const soundAtom = atom({ plugin: 'glanceflow', key: 'soundMode' } as const, 'off')
219const calmAtom = atom({ plugin: 'glanceflow', key: 'isCalm' } as const, false)
220/** The language GlanceFlow speaks; every view reads it, so a change shows at once. */
221const languageAtom = atom({ plugin: 'glanceflow', key: 'language' } as const, 'en')
222const guardAtom = atom({ plugin: 'glanceflow', key: 'isGuarded' } as const, true)
223const approveAtom = atom({ plugin: 'glanceflow', key: 'approvePlan' } as const, false)
224const shipOnGithubAtom = atom({ plugin: 'glanceflow', key: 'shipsOnGithub' } as const, false)
225const hasGithubAtom = atom({ plugin: 'glanceflow', key: 'hasGithub' } as const, false)
226const armedAtom = atom({ plugin: 'glanceflow', key: 'armedButton' } as const, null)
227const noticeAtom = atom({ plugin: 'glanceflow', key: 'isNoticing' } as const, false)
228const tourAtom = atom({ plugin: 'glanceflow', key: 'tourStep' } as const, null)
229const tidyAtAtom = atom({ plugin: 'glanceflow', key: 'tidyAt' } as const, TIDY_AT_DEFAULT)
230const checkpointAtom = atom({ plugin: 'glanceflow', key: 'checkpointAt' } as const, null)
231const recapAtom = atom({ plugin: 'glanceflow', key: 'isRecapShown' } as const, false)
232const othersAtom = atom({ plugin: 'glanceflow', key: 'otherChats' } as const, [])
233const showsOthersAtom = atom({ plugin: 'glanceflow', key: 'showsOthers' } as const, true)
234// shortcut: each read of the store parses its whole file, one per other chat; fine for 20 chats every 20 s, a single
235// shared key would read once but brings back the race of two chats saving at once.
236const OTHERS_EVERY_MS = 20_000
237const historyAtom = atom({ plugin: 'glanceflow', key: 'historyView' } as const, null)
238const HISTORY_PANE = 'glanceflow-history'
239const PLAN_PANE = 'glanceflow-plan'
240const RECAP_PANE = 'glanceflow-recap'
241const SETTINGS_PANE = 'glanceflow-settings'
242const CHECKLIST_PANE = 'glanceflow-checklist'
243const handoffAtom = atom({ plugin: 'glanceflow', key: 'handoffState' } as const, 'idle')
244const updateAtom = atom({ plugin: 'glanceflow', key: 'update' } as const, { state: 'idle', latest: null, id: null } as GlanceUpdate)
245const HANDOFF_CONFIRM_MS = 8000
246// What the Continue button sends, as the person's own words; turn.start knows it and keeps the job going.
247const CONTINUE_TEXT = 'Please continue where you left off.'
248// What the Start button sends when the person approves the plan.
249const START_TEXT = 'The plan looks good. Please start.'
250// What Aim higher sends while a plan waits: a deeper job, not a bigger one, from Felix Rieseberg's depth prompt.
251// Not start words, so the job stays and the new plan waits for Start again.
252const AIM_TEXT =
253 'Aim higher: I want a deeper version of this job, not a bigger one. Before you change the plan, say briefly ' +
254 '(1) what a top professional in this field would do here that I didn\'t ask for; (2) the rawest material they would ' +
255 'start from instead of what has already been digested; (3) the methods and tools they would use; (4) what, other ' +
256 'than you or me, would show the result is right. Then lay out the new plan with plan_steps, with done_when naming that check.'
257const HANDOFF_PROMPT = `Write a handoff note so a brand-new chat can carry on this work without this conversation.
258Cover, briefly: the goal; what is already done; what is left, in order; decisions made and why; the files, commands
259or links that matter; and the very next step. Under 300 words, no preamble.
260Start with exactly: "Continuing from an earlier chat. Here is where things stand:"`
261
262// What Ship it sends, as the person's own words: the close-out a finished job needs on GitHub, so the chat archives.
263const SHIP_PROMPT = `The work is finished. Ship it on GitHub, in order, and stop at the first step that fails:
2641. Run \`git status\` and \`gh auth status\`. If this is not a GitHub repo or gh is not signed in, stop and tell me what to do.
265 If the branch has no changes against its base branch, committed or not, and no open pull request, say there is
266 nothing to ship and stop.
2672. Quick cleanup of everything this branch changes against its base branch, committed or not. Use an installed review
268 skill (ponytail-review or simplify) if there is one; otherwise look yourself for dead code, needless comments,
269 pass-through wrappers and AI-sounding wording. Fix only clear wins, then run the project's tests if it has any.
2703. Commit with a Conventional Commits title, type(scope): subject. If on the base branch, make a new branch first.
271 Push the branch, never the base branch.
2724. Open a ready pull request with gh pr create, or reuse the branch's open one. Body: ## Why, ## What changed,
273 ## Verification, readable in under a minute.
2745. Wait with gh pr checks --watch. If a check fails or the merge conflicts, do not merge: show what failed and stop.
2756. Passing checks, or no checks, are not permission to merge. Read the head commit with gh pr view --json headRefOid,
276 then end your turn by showing the pull request link, the checks and the full head SHA, then these two lines:
277 Reply exactly: Approve merge <full SHA>
278 Anything else leaves the pull request open.
2797. Only after I reply exactly "Approve merge <that SHA>", read the head commit again. If it changed, ask again. If it
280 matches, run gh pr merge --squash --delete-branch --match-head-commit <full SHA> as a command of its own, with
281 nothing chained before or after it. Any other reply: leave the pull request open.
282 Never merge with --admin or --auto, or bypass branch protection in any other way; if the merge is blocked, say why and stop.
2838. End with the pull request link and one line on the result.`
284
285const CHECKPOINT_PROMPT = `This chat is about to be compacted to free up room. Write a checkpoint so the work carries on
286without losing anything that matters. Cover, briefly: the goal; what is already done; what is left, in order; decisions
287made and why; what the person asked for or ruled out; the files, commands or links that matter; open questions; and the
288very next step. Under 300 words, no preamble. Start with exactly: "Checkpoint:"`
289
290const PROMPT_SECTION = `# GlanceFlow (progress checklist)
291The person follows your work on a checklist above the prompt, in plain English.
292- A question you can answer straight away, with no tools, needs no plan: just answer.
293- Before you use any other tool, call plan_steps (tool ${PLAN_TOOL}) with 2 to 8 steps in order. If it is deferred, load it with ToolSearch first. If this session has TodoWrite or TaskCreate you may use that to-do list as the plan instead. If it has Claude's own task list (tool ${NATIVE_PLAN}), use that as the plan and do not call plan_steps; report_progress still takes its step names.
294- In plan mode, skip plan_steps while you look around and write the plan. Once the person approves it, call plan_steps with that plan's own steps, then do the work.
295- Give each step a size in plan_steps' sizes list, in the same order: S (a few minutes), M, or L (the biggest pieces of work).
296- Then call report_progress (tool ${PROGRESS_TOOL}) as real progress happens, and with percent 100 the moment a step finishes. With percent 100, add a summary: one short plain-English sentence on what the step got done, like "Added a pricing table with three plans".
297- Write every step name in plain English a non-technical person understands, under 40 characters, starting with a verb, like "Build the pricing section".
298- Never put file paths, file names, commands, code or tool names in a step name.
299- When something only the person can do or decide comes up, put it in report_progress' for_you; when you choose something neither the plan nor the person settled, put it in decided. One short line each.
300- Fill in plan_steps' done_when: what will be true when the job is done, and what other than you will show it. Make the last step that check. When the job changes code, run the project's tests, build or type check rather than saying it passed. The checklist shows whether changed code was tested.`
301
302const GREEK_SECTION = `# GlanceFlow language
303The person reads GlanceFlow in Greek. Write plan_steps' steps and done_when, report_progress' summary, for_you and
304decided, and the one-line description of each tool call in plain everyday Greek, not English. Every rule above about
305plain words applies to that Greek: short, a verb first in step names, no file names, commands or code.`
306
307const SPINNER = ['◐', '◓', '◑', '◒']
308// How many of the day's jobs ended each way, for the History's total line.
309const OUTCOME_COUNT: Record<GlanceHistoryEntry['outcome'], (count: number) => string> = {
310 done: count => tr('{0} done', count),
311 stopped: count => tr('{0} stopped', count),
312 stuck: count => tr('{0} stuck', count),
313 waiting: count => tr('{0} waiting', count),
314 background: count => tr('{0} background', count),
315 working: count => tr('{0} working', count),
316}
317const HELPERS_PER_STEP = 3
318
319// The tools that write files, and the field each names the file in.
320const FILE_TOOLS: Record<string, 'file_path' | 'notebook_path'> = { Write: 'file_path', Edit: 'file_path', MultiEdit: 'file_path', NotebookEdit: 'notebook_path' }
321// What a tool call's error says when the person said no at the permission dialog.
322const REJECTED = /doesn't want to proceed|user (has )?(rejected|denied|declined)/i
323
324type $ = EngineInterface
325/** Where the checklist band draws: above the prompt, or in VS Code its pane. */
326type BandEvent = RenderInput<'AbovePrompt' | 'Pane'>
327
328// Module state: a reload starts these over (session.start restarts the ticker).
329let ticker: Timer | undefined
330let collapse: Timer | undefined
331let saveTimer: Timer | undefined
332// The save under way, so the chat's end waits for it rather than have it land after.
333let saving: Promise<void> = Promise.resolve()
334let othersTimer: Timer | undefined
335// Set when the chat ends: anything still saved after that (a late job name, say) keeps it marked closed.
336let hasEnded = false
337let isRefreshing = false
338let failuresInARow = 0
339// A message held back for a password: memory only, never stored, and only to let the same one through on a resend.
340let heldMessage: { text: string; at: number } | null = null
341let limitLevel = 0
342// The press that armed the button now waiting: a timer left from an earlier press must not disarm a later one.
343let armedPress = 0
344// Ship it in this chat: the head commit Claude last asked to merge, and the one the person then said yes to.
345let isShipping = false
346let askedSha: string | null = null
347let approvedSha: string | null = null
348// Ship it's own prompt is still to start its turn; a merge Ship it allowed failed, so the next try needs a fresh yes;
349// the running turn answers a merge request with anything but the exact approval, so Ship it ends with it.
350let isShipTurnNext = false
351let hasFailedMerge = false
352let isDeclining = false
353// Plan mode: Claude writes a plan for the person to approve in Claude Code. Once they approve it, that plan is the
354// checklist, with no second approval.
355let isPlanMode = false
356let isPlanApproved = false
357// The question Claude Desktop's end-of-turn box asked the person this turn (wrap_up's `ask`): Claude's answer may not repeat it.
358let wrapUpAsk: string | null = null
359
360/** Ship it is over in this chat: its merge guard no longer applies. */
361const endShipping = () => {
362 isShipping = false
363 askedSha = null
364 approvedSha = null
365 isShipTurnNext = false
366 hasFailedMerge = false
367 isDeclining = false
368}
369
370/** After a merge Ship it allowed: a merge that worked ends Ship it; a failed one keeps it guarded. */
371const noteMerge = (ran: { deny?: string; isError?: boolean }) => {
372 if (ran.deny === undefined && !ran.isError) endShipping()
373 else hasFailedMerge = true
374}
375// The main loop's running turn, for the Pause button; and whether a pause asked for its end.
376let runningTurn: string | undefined
377let isPausing = false
378// Mirrors the calm setting for the ticker, which runs outside any hook.
379let isCalmMode = false
380/** The computer this runs on, asked when the session starts; null until known, and Claude Code plays the sounds itself. */
381let platform: 'mac' | 'windows' | 'linux' | null = null
382let tickerEvery = 0
383// Signs of life: set as Claude's reply streams or a tool starts or ends, stamped by the ticker, which runs while Claude works.
384let hasSign = false
385let lastSignAt = 0
386let isStalled = false
387
388const now = ($: $) => $.clock.now()
389
390const syncTicker = ($: $, list: GlanceChecklist | null) => {
391 const isAnimated = list !== null && (list.phase === 'working' || list.phase === 'needsYou' || list.phase === 'background')
392 // Calm mode: nothing moves, so the clock only ticks to keep the times current.
393 const every = isCalmMode ? CALM_TICK_MS : TICK_MS
394 if (ticker !== undefined && (!isAnimated || tickerEvery !== every)) {
395 ticker.cancel()
396 ticker = undefined
397 }
398 if (isAnimated && ticker === undefined) {
399 tickerEvery = every
400 ticker = $.clock.every(every, () => {
401 void update($, tickAtom, tick => (tick ?? 0) + 1)
402 // A tick runs 4 times a second: a failure here must not repeat as an unhandled error.
403 void checkStall($).catch(() => undefined)
404 })
405 }
406}
407
408/** Claude showed a sign of life; a job that looked stalled is working again. */
409const noteSign = ($: $) => {
410 hasSign = true
411 if (isStalled) {
412 isStalled = false
413 void setWorking($)
414 }
415}
416
417/** On each tick: a running turn with no sign of life for 3 minutes may be stuck. */
418const checkStall = async ($: $) => {
419 const at = await now($)
420 if (hasSign || runningTurn === undefined) {
421 hasSign = false
422 lastSignAt = at
423 return
424 }
425 if (isStalled || at - lastSignAt < STALL_MS || !(await read($, enabledAtom))) return
426 if ((await read($, checklistAtom))?.phase !== 'working') return
427 isStalled = true
428 await setStuck($, STALLED)
429}
430
431const ALERTS: Partial<Record<GlancePhase, { asset: string; words: string }>> = {
432 needsYou: { asset: 'sounds/needs-you.wav', words: 'Claude needs you' },
433 stuck: { asset: 'sounds/stuck.wav', words: 'Claude is stuck' },
434 done: { asset: 'sounds/done.wav', words: 'All done' },
435}
436
437const findPlatform = async ($: $) => {
438 if ((await $.env.get('OS')) === 'Windows_NT') return 'windows' as const
439 const { stdout } = await $.process.run(['uname', '-s']).catch(() => ({ stdout: '' }))
440 const name = stdout.trim()
441
442 return name === 'Darwin' ? ('mac' as const) : name ? ('linux' as const) : null
443}
444
445/** Runs the first of these commands that this computer has; rejects when it has none. */
446const runFirst = async ($: $, commands: readonly (readonly string[])[]) => {
447 for (const argv of commands) {
448 try {
449 const { exitCode } = await $.process.run(argv)
450 if (exitCode === 0) return
451 } catch {
452 // Not installed here: try the next one.
453 }
454 }
455 throw new Error('No sound player on this computer')
456}
457
458/** Plays one of GlanceFlow's sounds: Claude Code's own player on a Mac, the computer's own player on Windows and Linux. */
459const playSound = async ($: $, asset: string) => {
460 if (platform === 'windows') {
461 const file = `${$.plugin.root}\\${asset.replaceAll('/', '\\')}`.replaceAll("'", "''")
462 return runFirst($, [['powershell', '-NoProfile', '-Command', `(New-Object Media.SoundPlayer '${file}').PlaySync()`]])
463 }
464 if (platform !== 'linux') return $.audio.play({ asset })
465 const file = `${$.plugin.root}/${asset}`
466 return runFirst($, [['paplay', file], ['pw-play', file], ['aplay', '-q', file]])
467}
468
469/** Says a few words: the platform's own voice, or on Windows and Linux the speech tools they come with. */
470const sayWords = async ($: $, words: string) => {
471 try {
472 await $.audio.speak(words)
473 } catch (error) {
474 if (platform !== 'windows' && platform !== 'linux') throw error
475 const quoted = words.replaceAll("'", "''")
476 await runFirst(
477 $,
478 platform === 'windows'
479 ? [['powershell', '-NoProfile', '-Command', `Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${quoted}')`]]
480 : [['spd-say', '-w', words], ['espeak-ng', words], ['espeak', words]],
481 )
482 }
483}
484
485/** Windows' own toast, shown as Windows PowerShell's; the text comes in through the environment, never as script. */
486const WINDOWS_TOAST = [
487 '[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null',
488 '$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)',
489 "$text = $xml.GetElementsByTagName('text')",
490 '$text.Item(0).AppendChild($xml.CreateTextNode($env:GLANCEFLOW_TITLE)) | Out-Null',
491 '$text.Item(1).AppendChild($xml.CreateTextNode($env:GLANCEFLOW_BODY)) | Out-Null',
492 "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show([Windows.UI.Notifications.ToastNotification]::new($xml))",
493].join('; ')
494
495/**
496 * A notice, first through Claude Code: the person's own Notification hooks read it (a phone, ntfy, Slack), then their
497 * terminal shows it. Where that shows no text (the Desktop app, no channel, only a bell), the computer's own notifications
498 * show it: Windows, macOS or Linux. The text goes in as arguments or variables, never as script.
499 */
500const showNotice = async ($: $, title: string, body: string) => {
501 const sent = await $.ui.notify(body, { title }).catch(() => null)
502 if (sent?.isSent && sent.channel !== 'terminal_bell') return
503 if (platform === 'windows') {
504 await $.process
505 .run(['powershell', '-NoProfile', '-Command', WINDOWS_TOAST], { env: { GLANCEFLOW_TITLE: title, GLANCEFLOW_BODY: body } })
506 .catch(() => undefined)
507 return
508 }
509 const script = ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run']
510 try {
511 await $.process.run(['osascript', ...script, title, body])
512 } catch {
513 // No osascript: not a Mac. notify-send is Linux's; elsewhere the band still shows it.
514 await $.process.run(['notify-send', '--app-name=Claude Code', title, body]).catch(() => undefined)
515 }
516}
517
518/** A desktop notice when Claude needs you, gets stuck or finishes a long job, as for the sounds. */
519const noticeFor = async ($: $, list: GlanceChecklist) => {
520 const alert = ALERTS[list.phase]
521 if (!alert || !(await read($, noticeAtom)) || !(await read($, enabledAtom))) return
522 if (list.phase === 'done' && (isBusy(list) || (list.finishedAt ?? (await now($))) - list.startedAt < LONG_JOB_MS)) return
523 await showNotice($, tr(alert.words), noticeBody(list))
524}
525
526/** A short sound (and, in voice mode, a few words) when Claude needs you, gets stuck or finishes a long job. */
527const alertFor = async ($: $, list: GlanceChecklist) => {
528 const alert = ALERTS[list.phase]
529 const mode = await read($, soundAtom)
530 if (!alert || mode === 'off' || !(await read($, enabledAtom))) return
531 // A quick answer needs no sound, and a job whose helpers still run is not finished yet.
532 if (list.phase === 'done' && (isBusy(list) || (list.finishedAt ?? (await now($))) - list.startedAt < LONG_JOB_MS)) return
533 try {
534 await playSound($, alert.asset)
535 if (mode === 'voice') await sayWords($, tr(alert.words))
536 } catch {
537 // No player or voice on this computer: the band still shows it.
538 }
539}
540
541/** Keeps this chat's checklist, a second after it changes, for when the chat is resumed. */
542const saveSoon = ($: $) => {
543 if (saveTimer !== undefined) return
544 saveTimer = $.clock.after(1000, () => {
545 saveTimer = undefined
546 saving = saveChecklist($).catch(() => undefined)
547 })
548}
549
550/** Saves this chat's checklist under its own key; `isOpen` false once the chat has ended, so the others stop naming it. */
551const saveChecklist = async ($: $, isOpen = !hasEnded, id?: string) => {
552 const key = `${RESUME_PREFIX}${id ?? (await $.session.id())}`
553 const list = await read($, checklistAtom)
554 if (list === null) await $.store.delete(key)
555 else await $.store.set(key, { at: await now($), list, isOpen } satisfies SavedChecklist)
556}
557
558/** Reads what the other chats saved and keeps those worth a word; writes only on a change, so the band redraws then. */
559const refreshOthers = async ($: $) => {
560 // One read at a time: a slow one that finished after a newer one would bring back what has changed since.
561 if (isRefreshing) return
562 isRefreshing = true
563 try {
564 // Off says nothing, and turning back on starts from a fresh read rather than an old list.
565 if (!(await read($, enabledAtom)) || !(await read($, showsOthersAtom))) {
566 await update($, othersAtom, () => [])
567 return
568 }
569 const mine = `${RESUME_PREFIX}${await $.session.id()}`
570 const saved: (SavedChecklist | undefined)[] = []
571 for (const key of await $.store.keys()) {
572 if (key.startsWith(RESUME_PREFIX) && key !== mine) saved.push((await $.store.get(key)) as SavedChecklist | undefined)
573 }
574 const others = otherChats(saved, await now($))
575 if (JSON.stringify(await read($, othersAtom)) !== JSON.stringify(others)) await update($, othersAtom, () => others)
576 } catch {
577 // A store that can't be read says nothing, rather than keep naming chats that may have moved on.
578 await update($, othersAtom, () => [])
579 } finally {
580 isRefreshing = false
581 }
582}
583
584/**
585 * Moves the one shared key of older versions to a key per chat, then keeps only the most recent chats, never this one.
586 * Moved checklists aren't marked open: those chats are named again only once they save, so a closed one never is.
587 */
588const tidySavedChecklists = async ($: $) => {
589 const mine = `${RESUME_PREFIX}${await $.session.id()}`
590 const old = await $.store.get(OLD_RESUME_KEY)
591 if (old !== undefined) {
592 for (const [id, saved] of Object.entries((old ?? {}) as Record<string, SavedChecklist>)) {
593 // shortcut: the store has no write-if-unchanged, so a chat that saves between this check and the set loses that
594 // save until its next one; checking right before the set keeps that window as small as it can be.
595 if ((await $.store.get(`${RESUME_PREFIX}${id}`)) === undefined) await $.store.set(`${RESUME_PREFIX}${id}`, saved)
596 }
597 await $.store.delete(OLD_RESUME_KEY)
598 }
599 const saved: [string, number][] = []
600 for (const key of (await $.store.keys()).filter(one => one.startsWith(RESUME_PREFIX) && one !== mine)) {
601 saved.push([key, ((await $.store.get(key)) as SavedChecklist | undefined)?.at ?? 0])
602 }
603 const stale = new Set(staleResumeKeys(saved, RESUME_KEEP - 1))
604 for (const [key, at] of saved) {
605 // A chat that saved since it was read is in use again: it stays.
606 if (stale.has(key) && (at === 0 || ((await $.store.get(key)) as SavedChecklist | undefined)?.at === at)) await $.store.delete(key)
607 }
608}
609
610/** A resumed chat gets its checklist back; work that was under way shows as paused, with Continue. */
611const restoreChecklist = async ($: $) => {
612 const id = await $.session.id().catch(() => null)
613 const saved = id === null ? undefined : ((await $.store.get(`${RESUME_PREFIX}${id}`)) as SavedChecklist | undefined)
614 if (saved === undefined || isFinished(saved.list)) return
615 const list = saved.list
616 // Still true after a restart: a plan waiting for Start, or Claude waiting for a reply. Anything else was cut off.
617 const holds = list.phase === 'stopped' || (list.phase === 'needsYou' && (list.needsYouReason === APPROVE || list.needsYouReason === WAITING))
618 const restored: GlanceChecklist = {
619 ...list,
620 activity: null,
621 isCollapsed: false,
622 helpers: list.helpers.filter(one => one.status !== 'running'),
623 ...(holds ? {} : { phase: 'stopped' as const, stopKind: 'pause' as const, needsYouReason: null, stuckReason: null, finishedAt: saved.at }),
624 }
625 await update($, checklistAtom, () => restored)
626 syncTicker($, restored)
627 // Saved again as open, so the other chats see it as it is now.
628 saveSoon($)
629}
630
631const change = async ($: $, fn: (list: GlanceChecklist) => GlanceChecklist | null) => {
632 const at = await now($)
633 const before: { phase: GlancePhase | null } = { phase: null }
634 const next = await update($, checklistAtom, list => {
635 before.phase = list?.phase ?? null
636 const changed = list ? fn(list) : list
637 return changed ? { ...changed, tasks: stampTimes(changed.tasks, at) } : changed
638 })
639 syncTicker($, next)
640 saveSoon($)
641 if (next !== null && next.phase !== before.phase) {
642 void alertFor($, next)
643 void noticeFor($, next)
644 }
645
646 return next
647}
648
649/** Every chat's jobs on these days (all kept days when none are named), each once, oldest first. */
650const readHistory = async ($: $, days?: readonly string[]): Promise<GlanceHistoryEntry[]> => {
651 const stored: unknown[] = []
652 for (const key of await $.store.keys()) {
653 if (key.startsWith(HISTORY_PREFIX) && (days === undefined || days.includes(historyDay(key)))) stored.push(await $.store.get(key))
654 }
655
656 return mergedEntries(stored)
657}
658
659// This project's pace, kept between jobs: reading every chat's 30 days of history held up each new job, about 20 ms
660// for every 1,000 saved jobs. A job this chat records clears it.
661// shortcut: jobs other chats finish count from this chat's next session; refresh it on a timer if that matters.
662let pace: { project: string; ms: number | null } | undefined
663
664/** This project's pace from the History of the last 30 days; null when it isn't known yet. */
665const learnPace = async ($: $): Promise<number | null> => {
666 try {
667 const project = await $.session.cwd()
668 if (pace?.project !== project) pace = { project, ms: paceFromHistory(await readHistory($), project) }
669 return pace.ms
670 } catch {
671 return null
672 }
673}
674
675/** The pace already learned for this project, at once; undefined until it is. */
676const knownPace = async ($: $): Promise<number | null | undefined> => {
677 const project = await $.session.cwd().catch(() => null)
678 return pace !== undefined && pace.project === project ? pace.ms : undefined
679}
680
681/** The person's standing goal for this project; null when none is set or the store can't be read. */
682const readGoal = async ($: $): Promise<string | null> => {
683 try {
684 const goal = await $.store.get(`${GOAL_PREFIX}${await $.session.cwd()}`)
685 return typeof goal === 'string' && goal ? goal : null
686 } catch {
687 return null
688 }
689}
690
691const startJob = async ($: $, text: string, jobId: string) => {
692 const previous = await read($, checklistAtom)
693 const known = await knownPace($)
694 const list: GlanceChecklist = {
695 // Until Haiku names it, a request in a language GlanceFlow doesn't speak shows a neutral title.
696 title:
697 isLatinText(text.split('\n')[0] ?? '') || currentLang() === 'el' ? cleanName(text.split('\n')[0]) : tr('Working on your request'),
698 phase: 'working',
699 tasks: stampTimes([task(tr('Understand your request'), 'active'), task(tr('Plan the steps'), 'upcoming')], await now($)),
700 needsYouReason: null,
701 stuckReason: null,
702 startedAt: await now($),
703 finishedAt: null,
704 isCollapsed: false,
705 hasPlan: false,
706 jobId,
707 planAt: null,
708 plannedCount: 0,
709 extraTokens: 0,
710 extraCachedTokens: 0,
711 stopKind: null,
712 activity: null,
713 approval: 'none',
714 costAtStart: (await read($, usageAtom)).costUsd,
715 paceMs: known ?? null,
716 doneWhen: null,
717 goal: await readGoal($),
718 // Work still running from the last job stays in view.
719 helpers: (previous?.helpers ?? []).filter(one => one.status === 'running'),
720 }
721 failuresInARow = 0
722 collapse?.cancel()
723 await update($, checklistAtom, () => list)
724 syncTicker($, list)
725 saveSoon($)
726 // Not learned yet: the checklist shows now, and gets the pace once History is read.
727 if (known === undefined) {
728 void learnPace($)
729 .then(ms => (ms === null ? null : change($, one => (one.jobId === jobId && one.paceMs === null ? { ...one, paceMs: ms } : one))))
730 .catch(() => undefined)
731 }
732 // Name the job in the background; a newer job wins.
733 $.clock.after(0, () => void nameJob($, text, jobId))
734}
735
736const nameJob = async ($: $, text: string, jobId: string) => {
737 try {
738 const answer = await $.model.complete({
739 model: 'haiku',
740 effort: 'low',
741 timeoutMs: 15000,
742 prompt:
743 (currentLang() === 'el'
744 ? 'Name this request in 2 to 6 plain everyday Greek words that start with a verb, ' +
745 'like "Φτιάξε τη σελίδα μου", in sentence case: only the first word and names get a capital. ' +
746 'Always in Greek, even when the request is in another language. '
747 : 'Name this request in 2 to 6 plain English words that start with a verb, ' +
748 'like "Build my landing page", in sentence case: only the first word and names get a capital. ' +
749 'Always in English, even when the request is in another language. ') +
750 'No file names, code, quotes or punctuation. ' +
751 // Masked like everything GlanceFlow shows: keys and personal details stay out of the naming request.
752 `Reply with the name only.\n\nRequest:\n${maskPrivate(text).slice(0, 2000)}`,
753 })
754 if (!answer.isAnswered) {
755 return
756 }
757 const title = sentenceCase(cleanName((answer.text.split('\n')[0] ?? '').replace(/["'.]/g, '')))
758 await change($, list => (list.jobId === jobId ? { ...list, title } : list))
759 } catch {
760 // The placeholder title stays.
761 }
762}
763
764// A plan waiting for Start stays on Needs you while Claude finishes laying it out.
765const setWorking = ($: $) =>
766 change($, list =>
767 list.approval !== 'waiting' && (list.phase === 'needsYou' || list.phase === 'stuck')
768 ? { ...list, phase: 'working', needsYouReason: null, question: null, stuckReason: null }
769 : list,
770 )
771
772const setNeedsYou = ($: $, reason: string) =>
773 change($, list =>
774 list.phase === 'done' || list.phase === 'stopped' ? list : { ...list, phase: 'needsYou', needsYouReason: reason, question: null },
775 )
776
777/** Claude wrote or edited a file: the current step keeps it, created or changed, once. A code change is untested again. */
778const noteFile = async ($: $, path: string, isNew: boolean) => {
779 const file: GlanceFile = { path: projectPath(path, await $.session.cwd().catch(() => '')), isNew }
780 await change($, list => {
781 const stepId = currentStepId(list)
782 return {
783 ...list,
784 tasks: list.tasks.map(one => {
785 if (one.id !== stepId) return one
786 const files = (one.files ?? []).some(known => known.path === file.path) ? one.files : [...(one.files ?? []), file]
787 return needsCheck(path) ? { ...one, files, check: 'unchecked' } : { ...one, files }
788 }),
789 }
790 })
791}
792
793// A test, build or type check Claude ran: its result marks the steps that changed code. A run the person rejected or
794// interrupted says nothing about the code.
795const noteCheck = async ($: $, tool: string, input: { command?: unknown }, ran: { deny?: string; isError?: boolean; text?: unknown }) => {
796 if ((tool !== 'Bash' && tool !== 'PowerShell') || ran.deny || !runsCheck(String(input.command ?? ''))) return
797 const text = String(ran.text ?? '')
798 if (ran.isError && (REJECTED.test(text) || /\binterrupted\b/i.test(text))) return
799 await change($, list => ({ ...list, tasks: applyCheck(list.tasks, checkResult(ran.isError === true, text)) }))
800}
801
802const setStuck = ($: $, reason: string) =>
803 change($, list => ({ ...list, phase: 'stuck', stuckReason: reason, needsYouReason: null }))
804
805/** Stops Claude's running turn; Continue picks it up again. */
806const pauseJob = async ($: $) => {
807 if (runningTurn === undefined) {
808 $.ui.toast(tr('Nothing is running right now.'))
809 return
810 }
811 isPausing = true
812 try {
813 await $.turn.abort({ turnId: runningTurn })
814 $.ui.toast(tr('Paused. Press Continue to pick up where Claude stopped.'))
815 } catch {
816 isPausing = false
817 $.ui.toast(tr("Couldn't pause right now. Press Esc to stop instead."))
818 }
819}
820
821/** Sends words as the person's own message; true when sent, otherwise onFail says what to do instead. */
822const sendAsUser = async ($: $, text: string, onFail: () => unknown) => {
823 try {
824 await $.prompt.submit({ text, asUser: true })
825 return true
826 } catch {
827 await onFail()
828 return false
829 }
830}
831
832/** Sends "continue" for the person: the same job goes on, nothing to type. */
833const continueJob = ($: $) => sendAsUser($, CONTINUE_TEXT, () => $.ui.toast(tr("Couldn't continue right now. Type: continue")))
834
835/** Loads one day of this project's history into the pane, and opens the pane when asked. */
836const showHistory = async ($: $, day: string, isOpening: boolean) => {
837 const project = await $.session.cwd()
838 // Entries saved before the report fields existed get empty ones.
839 const filled = (one: GlanceHistoryEntry) => ({ ...one, doneSteps: one.doneSteps ?? [], openSteps: one.openSteps ?? [], isQuickAnswer: one.isQuickAnswer ?? false })
840 const entries = (await readHistory($, [day]))
841 .filter(one => one.project === project)
842 .map(filled)
843 const today = dayKey(await now($))
844 const saved = (await $.store.keys()).filter(key => key.startsWith(HISTORY_PREFIX)).map(historyDay)
845 const days = [...new Set([today, day, ...saved])].sort().reverse()
846 const myWeek = await readHistory($, Array.from({ length: WEEK_DAYS }, (_, back) => shiftDay(day, -back)))
847 await update($, historyAtom, (view): GlanceHistoryView => ({
848 day,
849 project,
850 entries,
851 days,
852 isReportShown: false,
853 reportSpan: view?.reportSpan === 'week' ? 'week' : 'day',
854 weekEntries: myWeek.filter(one => one.project === project).map(filled),
855 myWeekEntries: myWeek.map(filled),
856 }))
857
858 return isOpening ? $.ui.open({ id: HISTORY_PANE, title: tr('History · {0}', projectName(project)), closeOnEscape: true }) : null
859}
860
861/** Opens the whole plan in a side panel: every step, what each got done, its time and helpers. */
862const showPlan = ($: $) => $.ui.open({ id: PLAN_PANE, title: tr('Plan'), closeOnEscape: true })
863
864/** Where we left off: the checkpoint Claude saved before the chat was tidied up, in a side panel. */
865const showRecap = async ($: $) => {
866 await update($, recapAtom, () => false)
867 return $.ui.open({ id: RECAP_PANE, title: tr('Where we left off'), closeOnEscape: true })
868}
869
870/** Shows the team report for the day or the week, or your own week across projects, and copies it. */
871const showReportSpan = async ($: $, span: GlanceHistoryView['reportSpan'], surface?: RenderSurface) => {
872 await update($, historyAtom, view => (view ? { ...view, reportSpan: span } : view))
873 const view = await read($, historyAtom)
874 if (view !== null) await showReport($, true, reportOf(view), surface)
875}
876
877const showReport = async ($: $, isShown: boolean, text: string, surface?: RenderSurface) => {
878 await update($, historyAtom, view => (view ? { ...view, isReportShown: isShown } : view))
879 if (!isShown) return
880 const copied = await $.ui.copy({ text, surface })
881 const isMine = (await read($, historyAtom))?.reportSpan === 'mine'
882 $.ui.toast(
883 !copied.isCopied
884 ? tr('The report is in the panel: select it there to copy it.')
885 : isMine
886 ? tr('Your week copied: paste it wherever you like.')
887 : tr('Team report copied: paste it into Slack, Teams or an email.'),
888 )
889}
890
891/** First press arms a button that ends or sends something; a second press within 8 seconds runs it. One waits at a time. */
892const pressTwice = async ($: $, key: 'handoff' | 'ship', run: () => Promise<unknown>) => {
893 if ((await read($, armedAtom)) === key) {
894 await update($, armedAtom, () => null)
895 await run()
896 return
897 }
898 const press = ++armedPress
899 await update($, armedAtom, () => key)
900 $.clock.after(HANDOFF_CONFIRM_MS, () => {
901 if (press === armedPress) void update($, armedAtom, () => null)
902 })
903}
904
905/** Fresh chat asks for a second press; while the handoff note is being written, presses wait. */
906const pressHandoff = async ($: $) => {
907 if ((await read($, handoffAtom)) === 'working') return
908 await pressTwice($, 'handoff', () => startFreshChat($))
909}
910
911/** Writes a handoff note over this chat, clears it, and sends the note as the fresh chat's first message. */
912const startFreshChat = async ($: $) => {
913 await update($, handoffAtom, () => 'working')
914 try {
915 $.ui.toast(tr('Writing a handoff note for the fresh chat…'))
916 const reply = await $.model.fork({ prompt: HANDOFF_PROMPT })
917 if (!reply.isAnswered || !reply.text.trim()) {
918 $.ui.toast(reply.isAnswered ? tr("Couldn't write the handoff note. Nothing was cleared.") : tr("Couldn't write the handoff note ({0}). Nothing was cleared.", reply.reason))
919 return
920 }
921 const note = reply.text.trim()
922 // Kept in case anything below fails: /glanceflow handoff note puts it back in the prompt box.
923 await $.store.set(HANDOFF_KEY, { at: await now($), note })
924 try {
925 await $.command.run({ command: 'clear', args: '' })
926 } catch {
927 $.ui.toast(tr("Couldn't clear the chat. Type /glanceflow handoff note to get the handoff note."))
928 return
929 }
930 const isSent = await sendAsUser($, note, async () => {
931 await $.prompt.fill({ text: note })
932 $.ui.toast(tr('Chat cleared. The handoff note is in the prompt box: press Enter to send it.'))
933 })
934 if (isSent) $.ui.toast(tr('Fresh chat started from a handoff note.'))
935 } finally {
936 await update($, handoffAtom, () => 'idle')
937 }
938}
939
940/** Saves the job to the day's history (this computer only) and refreshes an open history pane. */
941const recordJob = async ($: $) => {
942 try {
943 const list = await read($, checklistAtom)
944 if (list === null) return
945 const project = await $.session.cwd()
946 const day = dayKey(list.startedAt)
947 // This chat's own key only: the store locks one set at a time, so a shared key could lose another chat's job.
948 const key = historyKey(day, await $.session.id())
949 const entry = entryFromChecklist(list, project, jobCost(list, await read($, usageAtom)))
950 await $.store.set(key, upsertEntry(await $.store.get(key), entry))
951 // A finished job with timed steps changes the pace: the next job learns it again, in the background.
952 if (entry.outcome === 'done' && (entry.doneUnits ?? 0) > 0) pace = undefined
953 const view = await read($, historyAtom)
954 if (view !== null && view.day === day && view.project === project) {
955 const entries = await readHistory($, [day])
956 await update($, historyAtom, () => ({ ...view, entries: entries.filter(one => one.project === project) }))
957 }
958 } catch {
959 // The history is a convenience: a failed save never gets in the way of the work.
960 }
961}
962
963/** Once Claude has answered: done, or still working in the background while helpers run. */
964const settleFinished = async ($: $, at: number, isNewAnswer: boolean) => {
965 let changed = isNewAnswer
966 const list = await change($, current => {
967 if (current.phase !== 'done' && current.phase !== 'background') return current
968 const phase = isBusy(current) ? ('background' as const) : ('done' as const)
969 if (phase === current.phase && !isNewAnswer) return current
970 changed = true
971 return { ...current, phase, finishedAt: phase === 'done' ? at : null, isCollapsed: false }
972 })
973 if (!changed || list === null) return
974 await recordJob($)
975 collapse?.cancel()
976 if (list.phase === 'done') {
977 const jobId = list.jobId
978 collapse = $.clock.after(COLLAPSE_MS, () => {
979 void change($, current =>
980 current.jobId === jobId && current.phase === 'done' ? { ...current, isCollapsed: true } : current,
981 )
982 })
983 }
984}
985
986const addHelper = ($: $, helper: Omit<GlanceHelper, 'stepId'>) =>
987 change($, current => ({
988 ...current,
989 helpers: [...current.helpers.filter(one => one.id !== helper.id), { ...helper, stepId: currentStepId(current) }],
990 }))
991
992const noteHelperStep = async ($: $, agentId: string, model: string, effort: unknown) => {
993 const list = await read($, checklistAtom)
994 const helper = list?.helpers.find(one => one.id === agentId)
995 const named = prettyModel(model)
996 const level = effort === undefined || effort === null ? null : String(effort)
997 if (!helper || (helper.model === named && helper.effort === level)) return
998 await change($, current => ({
999 ...current,
1000 helpers: current.helpers.map(one => (one.id === agentId ? { ...one, model: named, effort: level } : one)),
1001 }))
1002}
1003
1004type StepUsage = {
1005 input_tokens: number
1006 output_tokens: number
1007 cache_read_input_tokens: number
1008 cache_creation_input_tokens: number
1009}
1010
1011/** One model request's tokens: to the step it worked for, and to the helper that made it. */
1012const addTokens = ($: $, agentId: string | undefined, usage: StepUsage) => {
1013 const total =
1014 usage.input_tokens + usage.output_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
1015 if (total <= 0) return Promise.resolve(null)
1016
1017 const cached = usage.cache_read_input_tokens
1018
1019 return change($, current => {
1020 const helper = agentId === undefined ? undefined : current.helpers.find(one => one.id === agentId)
1021 const stepId =
1022 helper && current.tasks.some(one => one.id === helper.stepId)
1023 ? helper.stepId
1024 : current.tasks.find(one => one.status === 'active')?.id
1025 // No step is running (Claude writing its final answer): the job's total only.
1026 if (stepId === undefined && !helper) {
1027 return {
1028 ...current,
1029 extraTokens: current.extraTokens + total,
1030 extraCachedTokens: current.extraCachedTokens + cached,
1031 }
1032 }
1033 return {
1034 ...current,
1035 tasks: current.tasks.map(one =>
1036 one.id === stepId
1037 ? { ...one, tokens: one.tokens + total, cachedTokens: one.cachedTokens + usage.cache_read_input_tokens }
1038 : one,
1039 ),
1040 helpers: helper
1041 ? current.helpers.map(one => (one.id === helper.id ? { ...one, tokens: one.tokens + total } : one))
1042 : current.helpers,
1043 }
1044 })
1045}
1046
1047/** Shows a helper's own transcript in the main view, as Claude Code's tasks list does. */
1048const openHelper = async ($: $, agentId: string) => {
1049 try {
1050 const shown = await $.ui.view({ agentId })
1051 if ('deny' in shown && shown.deny) $.ui.toast(tr("Couldn't open that helper: {0}", shown.deny))
1052 } catch (error) {
1053 // A Claude Code older than the view has no $.ui.view to call.
1054 $.ui.toast(tr("Couldn't open that helper: {0}", error instanceof TypeError ? tr('this needs a newer Claude Code') : String(error)))
1055 }
1056}
1057
1058/** Stops one helper or task working in the background, with Claude Code's own TaskStop; Claude carries on. */
1059const stopHelper = async ($: $, helper: GlanceHelper) => {
1060 const taskId = helper.kind === 'background' ? helper.id.replace(/^bg:/, '') : helper.id
1061 // The tool table is too wide for TypeScript to check a call against: typed loosely, as the tests call tools.
1062 const failed = await ($.tool.call as unknown as (input: unknown) => Promise<{ deny?: string; isError?: boolean; text?: string }>)({
1063 tool: 'TaskStop',
1064 task_id: taskId,
1065 }).catch((error: unknown) => ({ deny: String(error), isError: true, text: '' }))
1066 if (failed.deny !== undefined || failed.isError) $.ui.toast(tr("Couldn't stop it: {0}", failed.deny ?? failed.text ?? tr('Claude Code said no')))
1067}
1068
1069const finishHelper = async ($: $, agentId: string, status: 'done' | 'failed') => {
1070 const list = await change($, current => ({
1071 ...current,
1072 helpers: current.helpers.map(one => (one.id === agentId && one.status === 'running' ? { ...one, status } : one)),
1073 }))
1074 if (list?.phase === 'background') await settleFinished($, await now($), false)
1075}
1076
1077/**
1078 * Tidies the chat up without forgetting: Claude first writes a checkpoint of the work, the compaction is told to keep
1079 * it, and it stays in Claude's instructions for the rest of this chat. Uses /compact itself when the engine refuses.
1080 */
1081const tidyUp = async ($: $) => {
1082 $.ui.toast(tr('Saving a checkpoint, then tidying up the chat…'))
1083 let note: string | null = null
1084 try {
1085 const reply = await $.model.fork({ prompt: CHECKPOINT_PROMPT })
1086 if (reply.isAnswered && reply.text.trim()) note = reply.text.trim()
1087 } catch {
1088 // Tidying up still helps without a checkpoint.
1089 }
1090 if (note !== null) {
1091 const at = await now($)
1092 await $.store.set(CHECKPOINT_KEY, { sessionId: await $.session.id(), at, note })
1093 await update($, checkpointAtom, () => at)
1094 } else {
1095 $.ui.toast(tr("Couldn't save a checkpoint; tidying up anyway."))
1096 }
1097 const instructions = note === null ? '' : `Keep everything in this checkpoint; it is what the work needs to carry on.\n\n${note}`
1098 try {
1099 const done = await $.session.compact(note === null ? undefined : { instructions })
1100 if (done.skip !== undefined) $.ui.toast(tr('The chat was not tidied up: {0}', done.skip))
1101 else if (note !== null) await update($, recapAtom, () => true)
1102 return
1103 } catch (refused) {
1104 $.ui.log(`glanceflow: compaction refused: ${refused instanceof Error ? refused.message : String(refused)}`, { to: 'debug' })
1105 }
1106 try {
1107 await $.command.run({ command: 'compact', args: instructions })
1108 } catch (failed) {
1109 const reason = failed instanceof Error ? failed.message : String(failed)
1110 $.ui.toast(tr("Couldn't tidy up the chat ({0}). Type /compact to try again.", reason.slice(0, 80)))
1111 }
1112}
1113
1114/** The checkpoint saved before this chat was last tidied up; null in another chat or when there is none. */
1115const checkpointOf = async ($: $): Promise<string | null> => {
1116 const saved = (await $.store.get(CHECKPOINT_KEY)) as { sessionId?: string; note?: string } | undefined
1117 return saved?.note && saved.sessionId === (await $.session.id()) ? saved.note : null
1118}
1119
1120const setTidyAt = async ($: $, percent: number) => {
1121 await update($, tidyAtAtom, () => percent)
1122 await $.store.set(TIDY_KEY, percent)
1123}
1124
1125const holdSecretMessage = async ($: $, text: string, kinds: string[]) => {
1126 heldMessage = { text, at: await now($) }
1127 // Put it back in the box so nothing is lost.
1128 $.clock.after(50, () => void $.prompt.fill({ text }).catch(() => undefined))
1129 $.ui.toast(
1130 tr(
1131 'This message looks like it has {0} in it, so it was not sent. Press Enter again to send it anyway, or take it out first.',
1132 kinds.map(kind => tr(kind)).reduce((all, kind) => tr('{0} and {1}', all, kind)),
1133 ),
1134 )
1135}
1136
1137const measureUsage = async ($: $, usage: GlanceUsage) => {
1138 await update($, usageAtom, () => usage)
1139 const level = usage.limitPercent === null ? 0 : usage.limitPercent >= LIMIT_ALERT ? 2 : usage.limitPercent >= LIMIT_WARN ? 1 : 0
1140 if (level > limitLevel && usage.limitPercent !== null) {
1141 const reset = resetTime(usage.limitResetsAt, await now($))
1142 const words = tr("You've used {0}% of your {1} limit", Math.round(usage.limitPercent), tr(usage.limitLabel ?? 'plan'))
1143 const message = reset === null ? words : tr('{0}. It resets {1}.', words, reset)
1144 $.ui.toast(message)
1145 if ((await read($, noticeAtom)) && (await read($, enabledAtom))) {
1146 await showNotice($, tr('Plan limit'), message)
1147 }
1148 }
1149 limitLevel = level
1150}
1151
1152const setEnabled = async ($: $, isEnabled: boolean) => {
1153 await update($, enabledAtom, () => isEnabled)
1154 await $.store.set(STORE_KEY, isEnabled)
1155 $.ui.toast(isEnabled ? tr('GlanceFlow is on: tool details are hidden') : tr('GlanceFlow is off: showing everything'))
1156}
1157
1158/** Sounds: off, a chime, or a chime and a few words. A chime plays at once so the person hears what they picked. */
1159const setSound = async ($: $, mode: 'off' | 'chime' | 'voice') => {
1160 await update($, soundAtom, () => mode)
1161 await $.store.set(SOUND_KEY, mode)
1162 if (mode !== 'off') void playSound($, 'sounds/needs-you.wav').catch(() => undefined)
1163}
1164
1165/** Picks GlanceFlow's language: its own words, and the words it asks Claude to put on the checklist. */
1166const setLanguage = async ($: $, next: Lang) => {
1167 setLang(next)
1168 await update($, languageAtom, () => next)
1169 await $.store.set(LANGUAGE_KEY, next)
1170}
1171
1172/** Calm mode: nothing moves, statuses in bold; the band redraws only to keep times current. */
1173const setCalm = async ($: $, isOn: boolean) => {
1174 isCalmMode = isOn
1175 await update($, calmAtom, () => isOn)
1176 await $.store.set(CALM_KEY, isOn)
1177 syncTicker($, await read($, checklistAtom))
1178}
1179
1180/** Moves the welcome on a card, or ends it for good. */
1181const stepTour = async ($: $, step: number | null) => {
1182 await update($, tourAtom, () => (step === null || step >= TOUR_CARDS ? null : step))
1183 if (step === null || step >= TOUR_CARDS) await $.store.set(TOUR_KEY, true)
1184}
1185
1186/** Desktop notices: on shows one when Claude needs you, gets stuck or finishes a long job. A sample shows at once. */
1187const setNotice = async ($: $, isOn: boolean) => {
1188 await update($, noticeAtom, () => isOn)
1189 await $.store.set(NOTICE_KEY, isOn)
1190 if (isOn) void showNotice($, tr('Claude needs you'), tr('This is how GlanceFlow will tell you.'))
1191}
1192
1193/** The line naming the other chats that need the person: off before sharing the screen, say. */
1194const setOthers = async ($: $, isOn: boolean) => {
1195 await update($, showsOthersAtom, () => isOn)
1196 await $.store.set(OTHERS_KEY, isOn)
1197 if (isOn) await refreshOthers($).catch(() => undefined)
1198}
1199
1200/** The password guard: on holds back a message that looks like it has a password or key in it. */hooks/history.ts 342 lines1// The day's history of jobs, for a retro: pure functions, no engine calls.
2
3import type { GlanceCheck, GlanceChecklist, GlanceFile, GlanceHistoryEntry, GlanceOutcome, GlanceTask, GlanceTaskSize } from '../types'
4import { currentLang, tr } from './words'
5
6export const HISTORY_PREFIX = 'history:'
7export const HISTORY_DAYS = 30
8/** How much each step size counts toward progress and pace. */
9export const SIZE_WEIGHT: Record<GlanceTaskSize, number> = { S: 1, M: 2, L: 3 }
10// The project's pace is trusted once its finished jobs hold this many size units: about three medium steps.
11const MIN_PACE_UNITS = 6
12const DAY_MS = 24 * 60 * 60 * 1000
13
14function pad(value: number): string {
15 return String(value).padStart(2, '0')
16}
17
18/** A moment's local day, YYYY-MM-DD: the store key's suffix. */
19export function dayKey(at: number): string {
20 const date = new Date(at)
21
22 return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
23}
24
25/** A moment's local time of day, HH:MM. */
26export function clockTime(at: number): string {
27 const date = new Date(at)
28
29 return `${pad(date.getHours())}:${pad(date.getMinutes())}`
30}
31
32/** The day a /glanceflow history argument names: today, yesterday, or YYYY-MM-DD. Null when it names none. */
33export function dayFromArgument(argument: string, now: number): string | null {
34 const word = argument.trim().toLowerCase()
35 if (word === '' || word === 'today') return dayKey(now)
36 if (word === 'yesterday') return dayKey(now - DAY_MS)
37
38 return /^\d{4}-\d{2}-\d{2}$/.test(word) ? word : null
39}
40
41const OUTCOME: Record<GlanceChecklist['phase'], GlanceOutcome> = {
42 working: 'working',
43 needsYou: 'waiting',
44 stuck: 'stuck',
45 stopped: 'stopped',
46 background: 'background',
47 done: 'done',
48}
49
50/** "Added contact.html · changed styles.css and app.js": file names only, with the folder where two share a name. */
51export function filesNote(files: readonly GlanceFile[], most = 4): string {
52 const base = (path: string) => path.split(/[\\/]/).pop() ?? path
53 const counts = new Map<string, number>()
54 for (const one of files) counts.set(base(one.path), (counts.get(base(one.path)) ?? 0) + 1)
55 const label = (path: string) => ((counts.get(base(path)) ?? 0) > 1 ? path.split(/[\\/]/).slice(-2).join('/') : base(path))
56 const group = (isAdded: boolean, names: string[]) => {
57 if (names.length === 0) return null
58 const shown = names.slice(0, most)
59 const more = names.length - shown.length
60 const last = more > 0 ? tr('{0} more', more) : shown.pop()!
61 const all = shown.length > 0 ? tr('{0} and {1}', shown.join(', '), last) : last
62 return isAdded ? tr('added {0}', all) : tr('changed {0}', all)
63 }
64 const text = [
65 group(true, files.filter(one => one.isNew).map(one => label(one.path))),
66 group(false, files.filter(one => !one.isNew).map(one => label(one.path))),
67 ]
68 .filter(Boolean)
69 .join(' · ')
70
71 return text.charAt(0).toUpperCase() + text.slice(1)
72}
73
74/** A History entry's files, as a step's are kept. */
75export function entryFiles(entry: GlanceHistoryEntry): GlanceFile[] {
76 return [...(entry.filesAdded ?? []).map(path => ({ path, isNew: true })), ...(entry.filesChanged ?? []).map(path => ({ path, isNew: false }))]
77}
78
79/** The job's check: the worst of its steps' (failed, then unchecked, then passed); null when no step changed code. */
80export function jobCheck(tasks: readonly GlanceTask[]): GlanceCheck | null {
81 const checks = tasks.map(one => one.check)
82 return (['failed', 'unchecked', 'passed'] as const).find(check => checks.includes(check)) ?? null
83}
84
85export const CHECK_WORDS: Record<GlanceCheck, string> = { passed: 'tested', failed: 'tests failed', unchecked: 'not tested' }
86
87/** One job as the history keeps it; `costUsd` is what it cost, where the host keeps a ledger. */
88export function entryFromChecklist(list: GlanceChecklist, project: string, costUsd: number | null = null): GlanceHistoryEntry {
89 const files = list.tasks.flatMap(one => one.files ?? [])
90 const added = [...new Set(files.filter(one => one.isNew).map(one => one.path))]
91 const tokens = list.tasks.reduce((sum, one) => sum + one.tokens, list.extraTokens)
92 const cached = list.tasks.reduce((sum, one) => sum + one.cachedTokens, list.extraCachedTokens)
93 const timed = list.hasPlan
94 ? list.tasks.filter(one => one.status === 'done' && one.startedAt !== null && one.finishedAt !== null && one.finishedAt > one.startedAt)
95 : []
96
97 return {
98 jobId: list.jobId,
99 project,
100 startedAt: list.startedAt,
101 finishedAt: list.finishedAt,
102 title: list.title,
103 // A job that finished with a question for the person is still a finished job.
104 outcome: list.phase === 'needsYou' && list.finishedAt !== null ? 'done' : OUTCOME[list.phase],
105 stepsDone: list.tasks.filter(one => one.status === 'done').length,
106 stepsTotal: list.tasks.length,
107 newTokens: tokens - cached,
108 cachedTokens: cached,
109 doneSteps: list.hasPlan ? list.tasks.filter(one => one.status === 'done').map(one => one.name) : [],
110 doneNotes: list.hasPlan ? list.tasks.filter(one => one.status === 'done').map(one => one.summary ?? '') : [],
111 openSteps: list.hasPlan ? list.tasks.filter(one => one.status !== 'done').map(one => one.name) : [],
112 filesAdded: added,
113 filesChanged: [...new Set(files.filter(one => !one.isNew && !added.includes(one.path)).map(one => one.path))],
114 isQuickAnswer: !list.hasPlan,
115 costUsd,
116 doneUnits: timed.reduce((sum, one) => sum + SIZE_WEIGHT[one.size], 0),
117 doneMs: timed.reduce((sum, one) => sum + (one.finishedAt! - one.startedAt!), 0),
118 check: jobCheck(list.tasks),
119 doneWhen: list.doneWhen ?? null,
120 goal: list.goal ?? null,
121 forYou: list.forYou ?? [],
122 decided: list.decided ?? [],
123 }
124}
125
126/** How long one unit of step size takes in this project, from its finished jobs; null until there is enough to go on. */
127export function paceFromHistory(entries: readonly GlanceHistoryEntry[], project: string): number | null {
128 let units = 0
129 let ms = 0
130 for (const one of entries) {
131 if (one.project === project && one.outcome === 'done' && (one.doneUnits ?? 0) > 0 && (one.doneMs ?? 0) > 0) {
132 units += one.doneUnits!
133 ms += one.doneMs!
134 }
135 }
136
137 return units >= MIN_PACE_UNITS ? Math.round(ms / units) : null
138}
139
140/** A stored day's entries; a missing or wrong value reads as none. */
141export function dayEntries(stored: unknown): GlanceHistoryEntry[] {
142 return Array.isArray(stored) ? (stored as GlanceHistoryEntry[]) : []
143}
144
145/** The store key of one chat's jobs on a day: each chat rewrites only its own, so two chats never lose each other's. */
146export function historyKey(day: string, sessionId: string): string {
147 return `${HISTORY_PREFIX}${day}:${sessionId}`
148}
149
150/** The day a history key is for. */
151export function historyDay(key: string): string {
152 return key.slice(HISTORY_PREFIX.length, HISTORY_PREFIX.length + 'YYYY-MM-DD'.length)
153}
154
155/** Keys from before 0.25, when every chat's jobs of a day shared one key. */
156export function sharedDayKeys(keys: readonly string[]): string[] {
157 return keys.filter(key => key.startsWith(HISTORY_PREFIX) && key.length === HISTORY_PREFIX.length + 'YYYY-MM-DD'.length)
158}
159
160/** The jobs of several stored lists, each once (the later list's copy wins), oldest first. */
161export function mergedEntries(stored: readonly unknown[]): GlanceHistoryEntry[] {
162 const byJob = new Map<string, GlanceHistoryEntry>()
163 for (const one of stored.flatMap(dayEntries)) byJob.set(one.jobId, one)
164
165 return [...byJob.values()].sort((a, b) => a.startedAt - b.startedAt)
166}
167
168/** The day's entries with this one added, or replacing its earlier self. */
169export function upsertEntry(entries: unknown, entry: GlanceHistoryEntry): GlanceHistoryEntry[] {
170 return [...dayEntries(entries).filter(one => one.jobId !== entry.jobId), entry].sort((a, b) => a.startedAt - b.startedAt)
171}
172
173/** Store keys of days older than the history keeps. */
174export function expiredHistoryKeys(keys: readonly string[], now: number): string[] {
175 const oldest = dayKey(now - HISTORY_DAYS * DAY_MS)
176
177 return keys.filter(key => key.startsWith(HISTORY_PREFIX) && key.slice(HISTORY_PREFIX.length) < oldest)
178}
179
180/** The folder name people know a project by. */
181export function projectName(project: string): string {
182 return project.split(/[\\/]/).filter(Boolean).pop() ?? project
183}
184
185/** The day before or after a YYYY-MM-DD day. */
186export function shiftDay(day: string, by: number): string {
187 const [year, month, date] = day.split('-').map(Number)
188
189 return dayKey(new Date(year!, month! - 1, date! + by, 12).getTime())
190}
191
192/** The days the weekly report covers: the day picked and the 6 before it. */
193export const WEEK_DAYS = 7
194
195function dateLabel(day: string, options: Intl.DateTimeFormatOptions): string {
196 const [year, month, date] = day.split('-').map(Number)
197 try {
198 return new Date(year!, month! - 1, date!, 12).toLocaleDateString(currentLang() === 'el' ? 'el-GR' : 'en-GB', options)
199 } catch {
200 return day
201 }
202}
203
204/** YYYY-MM-DD as "30 Sep 2026"; left as it is where the runtime has no date names. */
205export const shortDay = (day: string) => dateLabel(day, { day: 'numeric', month: 'short', year: 'numeric' })
206
207/** "Tuesday 6 October 2026". */
208export const longDay = (day: string) => dateLabel(day, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })
209
210/** Time as a manager would say it: "under a minute", "12 min", "1 h 5 min". */
211export function plainDuration(ms: number): string {
212 const minutes = Math.round(ms / 60_000)
213 if (minutes < 1) return tr('under a minute')
214 if (minutes < 60) return tr('{0} min', minutes)
215
216 return minutes % 60 ? tr('{0} h {1} min', Math.floor(minutes / 60), minutes % 60) : tr('{0} h', Math.floor(minutes / 60))
217}
218
219/**
220 * A short daily update for the team, a manager or a CEO: what got done, what is still open, and the time
221 * spent. Plain words only: no tokens, models or file names, and quick questions are left out.
222 */
223export function teamReport(
224 view: { day: string; project: string; entries: GlanceHistoryEntry[] },
225 span: 'day' | 'week' = 'day',
226): string {
227 const jobs = view.entries.filter(one => !one.isQuickAnswer)
228 const took = (one: GlanceHistoryEntry) =>
229 one.finishedAt === null ? '' : ` (${plainDuration(one.finishedAt - one.startedAt)})`
230 const heading =
231 span === 'week'
232 ? tr('Weekly update · {0} · {1} to {2}', projectName(view.project), shortDay(shiftDay(view.day, -(WEEK_DAYS - 1))), shortDay(view.day))
233 : tr('Daily update · {0} · {1}', projectName(view.project), longDay(view.day))
234 // Each standing goal the jobs worked toward, and how they did.
235 const goals = [...new Set(jobs.map(one => one.goal).filter(Boolean))].map(goal => {
236 const toward = jobs.filter(one => one.goal === goal)
237 const finished = toward.filter(one => one.outcome === 'done').length
238 const tested = toward.filter(one => one.check === 'passed').length
239 return toward.length === 1
240 ? tr('Goal: {0} · 1 task, {1} finished, {2} tested', goal!, finished, tested)
241 : tr('Goal: {0} · {1} tasks, {2} finished, {3} tested', goal!, toward.length, finished, tested)
242 })
243 const lines = [heading, ...goals, '']
244
245 if (jobs.length === 0) {
246 return [...lines, span === 'week' ? tr('No planned work was recorded this week.') : tr('No planned work was recorded on this day.')].join('\n')
247 }
248
249 const done = jobs.filter(one => one.outcome === 'done')
250 const open = jobs.filter(one => one.outcome !== 'done' && one.outcome !== 'stuck')
251 const blocked = jobs.filter(one => one.outcome === 'stuck')
252
253 if (done.length > 0) {
254 lines.push(tr('Done'))
255 for (const one of done) {
256 lines.push(`• ${one.title}${took(one)}${one.check ? ` · ${tr(CHECK_WORDS[one.check])}` : ''}`)
257 if (one.doneWhen) lines.push(` ${tr('Done when: {0}', one.doneWhen)}`)
258 for (const item of one.decided ?? []) lines.push(` ${tr('Decided: {0}', item)}`)
259 const notes = one.doneNotes ?? []
260 if (notes.some(Boolean)) {
261 // What each step got done, in Claude's words where it gave them.
262 one.doneSteps.forEach((name, at) => lines.push(` ✓ ${notes[at] || name}`))
263 } else if (one.doneSteps.length > 1) {
264 lines.push(` ${one.doneSteps.join(' · ')}`)
265 }
266 }
267 lines.push('')
268 }
269 if (open.length > 0) {
270 // "Open", not "in progress": a stopped job is here too, and nobody may be on it right now.
271 lines.push(tr('Still open'))
272 for (const one of open) {
273 const next = one.openSteps[0] ? `${one.openSteps[0].charAt(0).toLowerCase()}${one.openSteps[0].slice(1)}` : ''
274 lines.push(
275 `• ${
276 next
277 ? tr('{0}: {1} of {2} steps done; next: {3}', one.title, one.doneSteps.length, one.stepsTotal, next)
278 : tr('{0}: {1} of {2} steps done', one.title, one.doneSteps.length, one.stepsTotal)
279 }`,
280 )
281 for (const item of one.decided ?? []) lines.push(` ${tr('Decided: {0}', item)}`)
282 }
283 lines.push('')
284 }
285 // What only the person can do or decide, from any job, and the jobs that got stuck.
286 const forYou = jobs.flatMap(one => (one.forYou ?? []).map(item => `• ${one.title}: ${item}`))
287 if (blocked.length > 0 || forYou.length > 0) {
288 lines.push(tr('Needs attention'))
289 for (const one of blocked) lines.push(`• ${tr('{0}: it got stuck and needs a decision', one.title)}`)
290 lines.push(...forYou)
291 lines.push('')
292 }
293
294 const time = jobs.reduce((sum, one) => sum + (one.finishedAt === null ? 0 : one.finishedAt - one.startedAt), 0)
295 lines.push(
296 jobs.length === 1
297 ? tr('{0} of 1 task finished · {1} of work', done.length, plainDuration(time))
298 : tr('{0} of {1} tasks finished · {2} of work', done.length, jobs.length, plainDuration(time)),
299 )
300
301 return lines.join('\n')
302}
303
304const weekday = (day: string) => dateLabel(day, { weekday: 'long' })
305
306/**
307 * A personal summary of the 7 days up to `day`, across every project: how many steps Claude checked off,
308 * in how many tasks, the time, the busiest day and the biggest tasks. Plain words, made to share.
309 */
310export function weekSummary(entries: readonly GlanceHistoryEntry[], day: string): string {
311 const jobs = entries.filter(one => !one.isQuickAnswer)
312 const heading = tr('Your week with Claude · {0} to {1}', shortDay(shiftDay(day, -(WEEK_DAYS - 1))), shortDay(day))
313 if (jobs.length === 0) {
314 return `${heading}\n\n${tr('No planned work was recorded this week. Ask Claude for something with a few steps, and it shows here.')}`
315 }
316
317 const steps_ = (count: number) => (count === 1 ? tr('1 step') : tr('{0} steps', count))
318 const tasks_ = (count: number) => (count === 1 ? tr('1 task') : tr('{0} tasks', count))
319 const steps = jobs.reduce((sum, one) => sum + one.doneSteps.length, 0)
320 const finished = jobs.filter(one => one.outcome === 'done').length
321 const time = jobs.reduce((sum, one) => sum + (one.finishedAt === null ? 0 : one.finishedAt - one.startedAt), 0)
322 const projects = new Set(jobs.map(one => one.project))
323 const perDay = new Map<string, number>()
324 for (const one of jobs) perDay.set(dayKey(one.startedAt), (perDay.get(dayKey(one.startedAt)) ?? 0) + 1)
325 const [busiest, busiestCount] = [...perDay].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]!
326 const biggest = [...jobs].filter(one => one.doneSteps.length > 0).sort((a, b) => b.doneSteps.length - a.doneSteps.length).slice(0, 3)
327
328 const lines = [
329 heading,
330 '',
331 tr('Claude checked off {0} in {1}, and finished {2} of them.', steps_(steps), tasks_(jobs.length), finished),
332 projects.size > 1 ? tr('Time at work: {0}, across {1} projects.', plainDuration(time), projects.size) : tr('Time at work: {0}.', plainDuration(time)),
333 ]
334 if (perDay.size > 1) lines.push(tr('Busiest day: {0}, with {1}.', weekday(busiest), tasks_(busiestCount)))
335 if (biggest.length > 0) {
336 lines.push('', tr('Biggest tasks'))
337 for (const one of biggest) lines.push(`• ${one.title} (${steps_(one.doneSteps.length)})`)
338 }
339
340 return lines.join('\n')
341}
342hooks/privacy.ts 96 lines1// Finds and masks secrets and personal details.
2// Patterns adapted from Nate Herk's Recording Mode (MIT licence):
3// https://github.com/nateherkai/claude-code-mods
4
5const DOTS = '••••••••'
6
7const SECRET_PATTERNS = [
8 /sk-ant-[A-Za-z0-9_-]{16,}/g,
9 /\bsk-(?:proj-|live-|test-|svcacct-)?[A-Za-z0-9_-]{20,}/g,
10 /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
11 /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
12 /\bxox[abprs]-[A-Za-z0-9-]{10,}/g,
13 /\bAIza[0-9A-Za-z_-]{30,}/g,
14 /\bAKIA[0-9A-Z]{16}\b/g,
15 /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
16 /\b(?:hf|r8|pk_live|sk_live|rk_live|whsec|pat|key)_[A-Za-z0-9]{20,}/g,
17 /\bBearer\s+[A-Za-z0-9._~+/-]{20,}=*/gi,
18 /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
19]
20
21// NAME=value or "name": "value" where the name looks like a credential.
22// The keyword ends the name or meets a separator, so "author:" and "tokens:" are not credentials.
23const ASSIGNMENT =
24 /\b([A-Za-z0-9_.-]*(?:API[_-]?KEY|AUTH[_-]?TOKEN|ACCESS[_-]?TOKEN|CLIENT[_-]?SECRET|PRIVATE[_-]?KEY|ACCESS[_-]?KEY|SECRET|TOKEN|PASSWORD|PASSWD|AUTH)(?:[_.-][A-Za-z0-9_.-]*)?)(["']?\s*[=:]\s*["']?)([^\s"'`,;}{]{6,})/gi
25
26// "my password is X", "ο κωδικός μου είναι X"
27const PHRASE =
28 /(?<!\p{L})((?:password|passcode|passphrase|pin|κωδικ[όο]ς(?: πρόσβασης)?|συνθηματικ[όο])(?:\s+(?:μου|is|my))?\s*(?:is|είναι|ειναι|=|:)\s*["']?)([^\s"']{4,})/giu
29
30/** A plain word after "auth:" or "OAuth:" is a setting; a key has a digit, a symbol or length. */
31const isCredential = (name: string, value: string) =>
32 /pass|secret/i.test(name) || /[^\p{L}_-]/u.test(value) || value.length >= 16
33
34/** "PIN: optional" and "ο κωδικός: γράψε" are prose: a PIN is digits, a bare κωδικός (code) needs more than letters. */
35const isPhraseSecret = (head: string, value: string) => {
36 const word = head.toLowerCase()
37 if (/^pin(?!\p{L})/u.test(word)) return /^\d{4,}$/.test(value)
38 if (/^κωδικ/u.test(word) && !/πρόσβασης|μου/u.test(word)) return /[^\p{L}]/u.test(value)
39 return true
40}
41
42const matches = (re: RegExp, text: string) => [...text.matchAll(new RegExp(re.source, re.flags))]
43
44const CARD = /(?<![\w-])(?:4\d{3}|5[1-5]\d{2}|2[2-7]\d{2}|3[47]\d{2}|6(?:011|5\d{2}))(?:[ -]?\d{2,4}){3,4}(?![\w-])/g
45const IBAN = /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){3,7}(?: ?[A-Z0-9]{1,3})?\b/g
46const EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g
47const PHONE = /(?<![\w.])(?:\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}(?![\w.])/g
48const PHONE_INTL = /(?<![\w.])\+\d{1,3}[\s.-]?\(?\d{1,4}\)?(?:[\s.-]?\d{2,4}){2,4}(?![\w.])/g
49
50function luhn(digits: string): boolean {
51 let sum = 0
52 for (let i = 0; i < digits.length; i += 1) {
53 let d = Number(digits[digits.length - 1 - i])
54 if (i % 2 === 1) {
55 d *= 2
56 if (d > 9) d -= 9
57 }
58 sum += d
59 }
60 return sum % 10 === 0
61}
62
63function isCard(match: string): boolean {
64 const digits = match.replace(/\D/g, '')
65 return digits.length >= 13 && digits.length <= 19 && luhn(digits)
66}
67
68/** What kinds of secret a message holds: passwords, keys, card or bank numbers. */
69export function findSecrets(text: string): string[] {
70 const kinds = new Set<string>()
71 if (SECRET_PATTERNS.some(re => new RegExp(re.source, re.flags).test(text))) kinds.add('a key or token')
72 if (matches(ASSIGNMENT, text).some(m => isCredential(m[1]!, m[3]!))) kinds.add('a password or key')
73 if (matches(PHRASE, text).some(m => isPhraseSecret(m[1]!, m[2]!))) kinds.add('a password')
74 if ((text.match(CARD) ?? []).some(isCard)) kinds.add('a card number')
75 if (new RegExp(IBAN.source, IBAN.flags).test(text)) kinds.add('a bank account number')
76
77 return [...kinds]
78}
79
80/** Masks secrets and personal details for the screen; what Claude reads is unchanged. */
81export function maskPrivate(text: string): string {
82 let out = text
83 for (const re of SECRET_PATTERNS) out = out.replace(re, DOTS)
84 out = out.replace(ASSIGNMENT, (match, name: string, sep: string, value: string) =>
85 isCredential(name, value) ? name + sep + DOTS : match,
86 )
87 out = out.replace(PHRASE, (match, head: string, value: string) => (isPhraseSecret(head, value) ? head + DOTS : match))
88 out = out.replace(CARD, match => (isCard(match) ? '•••• •••• •••• ••••' : match))
89 out = out.replace(IBAN, '•••')
90 out = out.replace(EMAIL, '•••@•••')
91 out = out.replace(PHONE, '•••-•••-••••')
92 out = out.replace(PHONE_INTL, '+•• •••')
93
94 return out
95}
96hooks/words.ts 485 lines1/** The languages GlanceFlow speaks: its own words, and the words it asks Claude to use on the checklist. */
2export type Lang = 'en' | 'el'
3
4let lang: Lang = 'en'
5
6/** Sets the language every later `tr` speaks; the language setting and session start call it. */
7export const setLang = (next: Lang) => {
8 lang = next
9}
10
11export const currentLang = (): Lang => lang
12
13/**
14 * GlanceFlow's own words in the person's language. The English is the key, so a line with no translation yet stays
15 * English rather than breaking. `{0}`, `{1}` … stand for the values that follow, in either language. A key may end in
16 * `#context` when one English line needs two translations; the English never shows it.
17 */
18export function tr(key: string, ...values: readonly (string | number)[]): string {
19 const english = key.split('#')[0]!
20 const text = lang === 'el' ? (GREEK[key] ?? english) : english
21 return values.reduce<string>((out, value, at) => out.replaceAll(`{${at}}`, String(value)), text)
22}
23
24/**
25 * Greek for each English line GlanceFlow shows: everyday words, "εσύ" throughout. Product names and /glanceflow commands
26 * stay as they are. Plan → Πλάνο, History → Ιστορικό, Settings → Ρυθμίσεις, Needs you → Σε χρειάζεται.
27 */
28export const GREEK: Readonly<Record<string, string>> = {
29 // The band: where a job stands
30 'Needs you': 'Σε χρειάζεται',
31 'Stuck': 'Κόλλησε',
32 'Stuck: {0}': 'Κόλλησε: {0}',
33 'Working': 'Δουλεύει',
34 'All done': 'Έτοιμο',
35 'Done': 'Έγινε',
36 'done': 'έγινε',
37 'Waiting': 'Περιμένει',
38 'Paused': 'Σε παύση',
39 'Stopped': 'Σταμάτησε',
40 'Next': 'Επόμενο',
41 'Later': 'Αργότερα',
42 'Now': 'Τώρα',
43 'Now: {0}': 'Τώρα: {0}',
44 '({0}, {1} in a row)': '({0}, {1} στη σειρά)',
45 'Plan ready': 'Πλάνο έτοιμο',
46 'Background': 'Παρασκήνιο',
47 'In the background': 'Στο παρασκήνιο',
48 'in the background': 'στο παρασκήνιο',
49 'Still working in the background': 'Δουλεύει ακόμα στο παρασκήνιο',
50 '{0} in background': '{0} στο παρασκήνιο',
51 'Claude answered': 'Το Claude απάντησε',
52 'helpers still run in the background': 'βοηθοί δουλεύουν ακόμα στο παρασκήνιο',
53 'press Continue to pick up': 'πάτα Συνέχεια για να συνεχίσει',
54 'you pressed Esc': 'πάτησες Esc',
55 'Usage limit reached': 'Έφτασες το όριο χρήσης',
56 'try again later': 'δοκίμασε ξανά αργότερα',
57 'resets {0}': 'μηδενίζεται {0}',
58 '{0} of {1} done': 'έγιναν {0} από {1}',
59 '{0} so far': '{0} μέχρι τώρα',
60 'took {0}': 'χρειάστηκε {0}',
61 '{0} left': 'απομένουν {0}',
62 'plan grew {0} → {1}': 'το πλάνο μεγάλωσε {0} → {1}',
63 '{0} steps done': '{0} βήματα έγιναν',
64 '{0} more steps in Plan': '{0} ακόμα βήματα στο Πλάνο',
65 "{0} more in Claude's task list": '{0} ακόμα στη λίστα εργασιών του Claude',
66 '{0} more steps': '{0} ακόμα βήματα',
67 '1 more step': '1 ακόμα βήμα',
68 '{0} earlier': '{0} νωρίτερα',
69 'For you': 'Για σένα',
70 'For you: {0}': 'Για σένα: {0}',
71 'For you: {0} · {1} more in Plan': 'Για σένα: {0} · {1} ακόμα στο Πλάνο',
72 'Decided on its own': 'Αποφάσισε μόνο του',
73 'helper': 'βοηθός',
74 '{0} effort': 'προσπάθεια {0}',
75 'Working on it': 'Το δουλεύει',
76 'Working on your request': 'Δουλεύει το αίτημά σου',
77 'Understand your request': 'Κατανόηση του αιτήματός σου',
78 'Plan the steps': 'Σχεδιασμός των βημάτων',
79 'Answer your question': 'Απάντηση στην ερώτησή σου',
80 'Ask Claude for something, and its plan shows here': 'Ζήτα κάτι από το Claude, και το πλάνο του φαίνεται εδώ',
81 'Ask Claude for something: its plan shows here': 'Ζήτα κάτι από το Claude: το πλάνο του φαίνεται εδώ',
82 'GlanceFlow is off: Claude Code shows everything as usual': 'Το GlanceFlow είναι ανενεργό: το Claude Code δείχνει τα πάντα όπως συνήθως',
83 'No plan yet': 'Κανένα πλάνο ακόμα',
84 'Chat tidied up. Claude kept a checkpoint of the work.': 'Η συζήτηση τακτοποιήθηκε. Το Claude κράτησε ένα σημείο ελέγχου της δουλειάς.',
85
86 // Marks a screen reader says
87 'Status': 'Κατάσταση',
88 'Notice': 'Ειδοποίηση',
89 'Setting': 'Ρύθμιση',
90 'Folded': 'Συμπτυγμένα',
91 'Running': 'Τρέχει',
92 'Failed': 'Απέτυχε',
93 'Files': 'Αρχεία',
94 'Runs': 'Εντολή',
95 'To do': 'Εκκρεμεί',
96 '{0}% done': '{0}% έτοιμο',
97 'Card {0} of {1}': 'Κάρτα {0} από {1}',
98
99 // Buttons and the view
100 'Plan': 'Πλάνο',
101 'History': 'Ιστορικό',
102 'Settings': 'Ρυθμίσεις',
103 'Pause': 'Παύση',
104 'Continue': 'Συνέχεια',
105 'Start': 'Έναρξη',
106 'Try again': 'Δοκίμασε ξανά',
107 'Check again': 'Έλεγξε ξανά',
108 'Aim higher': 'Πιο φιλόδοξα',
109 'Fresh chat': 'Νέα συζήτηση',
110 'Fresh': 'Νέα',
111 'Press again to start a fresh chat': 'Πάτα ξανά για νέα συζήτηση',
112 'Writing a handoff note…': 'Γράφει σημείωμα μετάβασης…',
113 'Ship it': 'Ανέβασέ το',
114 'Press again to ship': 'Πάτα ξανά για ανέβασμα',
115 'Tidy it up': 'Τακτοποίηση',
116 'Tidy up now': 'Τακτοποίηση τώρα',
117 'Where we left off': 'Πού μείναμε',
118 'OK': 'Εντάξει',
119 'Close': 'Κλείσιμο',
120 'Open': 'Άνοιγμα',
121 'Stop': 'Διακοπή',
122 'Skip': 'Παράλειψη',
123 'Got it': 'Κατάλαβα',
124 'View': 'Προβολή',
125 'View: {0}': 'Προβολή: {0}',
126 'Simple': 'Απλή',
127 'Detailed': 'Αναλυτική',
128 'Details': 'Αναλυτικά',
129 'Off': 'Ανενεργό',
130 'On': 'Ενεργό',
131
132 // Usage, limits and a full chat
133 "You've used {0}% of your {1} limit": 'Έχεις χρησιμοποιήσει το {0}% του ορίου {1}',
134 '{0}. It resets {1}.': '{0}. Μηδενίζεται {1}.',
135 'plan': 'της συνδρομής',
136 '5-hour': '5 ωρών',
137 'weekly': 'της εβδομάδας',
138 'spending': 'δαπανών',
139 '{0} {1}%': 'όριο {0} {1}%',
140 'Plan limit': 'Όριο συνδρομής',
141 'Usage: {0}': 'Χρήση: {0}',
142 'Plan usage: {0}': 'Χρήση συνδρομής: {0}',
143 'chat {0}% full': 'συζήτηση {0}% γεμάτη',
144 'This chat is {0}% full': 'Η συζήτηση είναι {0}% γεμάτη',
145 'This chat is {0}% full.': 'Η συζήτηση είναι {0}% γεμάτη.',
146 'This chat is {0}% full. Claude saves a checkpoint before tidying up.': 'Η συζήτηση είναι {0}% γεμάτη. Το Claude κρατά ένα σημείο ελέγχου πριν την τακτοποιήσει.',
147 'tidying up keeps a checkpoint first': 'η τακτοποίηση κρατά πρώτα ένα σημείο ελέγχου',
148
149 // Times
150 'at {0}': 'στις {0}',
151 'on {0} at {1}': 'την {0} στις {1}',
152 '{0}s': '{0}δ',
153 '{0}m': '{0}λ',
154 '{0}m {1}s': '{0}λ {1}δ',
155 '{0}h {1}m': '{0}ώ {1}λ',
156 'taking longer': 'αργεί λίγο',
157 'under a minute left': 'λιγότερο από ένα λεπτό ακόμα',
158 'about {0} left': 'περίπου {0} ακόμα',
159 '<1m left': '<1λ ακόμα',
160 '~{0} left': '~{0} ακόμα',
161 'under a minute': 'λιγότερο από ένα λεπτό',
162 'about {0}': 'περίπου {0}',
163 '{0} min': '{0} λεπ.',
164 '{0} h': '{0} ώρ.',
165 '{0} h {1} min': '{0} ώρ. {1} λεπ.',
166 '{0} tokens': '{0} tokens',
167 '{0} new · {1} cached': '{0} νέα · {1} από μνήμη',
168
169 // What Claude is doing, and permission requests
170 'Reading files': 'Διαβάζει αρχεία',
171 'Searching the project': 'Ψάχνει στο έργο',
172 'Editing files': 'Αλλάζει αρχεία',
173 'Writing files': 'Γράφει αρχεία',
174 'Reading a web page': 'Διαβάζει μια σελίδα',
175 'Searching the web': 'Ψάχνει στο διαδίκτυο',
176 'Following a skill': 'Ακολουθεί μια δεξιότητα',
177 'Using a connected app': 'Χρησιμοποιεί μια συνδεδεμένη εφαρμογή',
178 'Running the tests': 'Τρέχει τα τεστ',
179 'Installing packages': 'Εγκαθιστά πακέτα',
180 'Working with git': 'Δουλεύει με το git',
181 'Building the project': 'Χτίζει το έργο',
182 'Running a command': 'Τρέχει μια εντολή',
183 'OK to {0}?': 'Εντάξει να {0};',
184 'OK to {0}? It {1}.': 'Εντάξει να {0}; Η εντολή {1}.',
185 // With the description Claude gave the call, which reads as a name in Greek: «Δημοσίευση του site: εντάξει;»
186 'OK to {0}?#detail': '{0}: εντάξει;',
187 'OK to {0}? It {1}.#detail': '{0}: εντάξει; Η εντολή {1}.',
188 'read': 'διαβάσει',
189 'search the project': 'ψάξει στο έργο',
190 'edit': 'αλλάξει',
191 'write': 'γράψει',
192 'read a page on': 'διαβάσει μια σελίδα στο',
193 'search the web': 'ψάξει στο διαδίκτυο',
194 'use a connected app': 'χρησιμοποιήσει μια συνδεδεμένη εφαρμογή',
195 'run the tests': 'τρέξει τα τεστ',
196 'install packages': 'εγκαταστήσει πακέτα',
197 'run a git command': 'τρέξει μια εντολή git',
198 'build the project': 'χτίσει το έργο',
199 'run a command': 'τρέξει μια εντολή',
200 'deletes files': 'σβήνει αρχεία',
201 'rewrites git history': 'ξαναγράφει το ιστορικό του git',
202 'publishes a package': 'δημοσιεύει ένα πακέτο',
203 'uploads your changes': 'ανεβάζει τις αλλαγές σου',
204 'deploys online': 'το βγάζει στο διαδίκτυο',
205 'installs packages': 'εγκαθιστά πακέτα',
206 'uses admin rights': 'χρησιμοποιεί δικαιώματα διαχειριστή',
207 'runs code from the internet': 'τρέχει κώδικα από το διαδίκτυο',
208 '{0} and {1}': '{0} και {1}',
209
210 // Why Claude waits or is stuck
211 "Answer Claude's question in the chat": 'Απάντησε στην ερώτηση του Claude στη συζήτηση',
212 'Reply to Claude in the box below': 'Απάντησε στο Claude στο πλαίσιο από κάτω',
213 "Answer Claude's request in the chat": 'Απάντησε στο αίτημα του Claude στη συζήτηση',
214 'Read the plan, then press Start or tell Claude what to change': 'Διάβασε το πλάνο και πάτα Έναρξη, ή πες στο Claude τι να αλλάξει',
215 'Reply exactly: Approve merge {0}': 'Απάντησε ακριβώς: Approve merge {0}',
216 'you said no to a step, so Claude paused': 'είπες όχι σε ένα βήμα, οπότε το Claude σταμάτησε',
217 'a step keeps failing, Claude is trying another way': 'ένα βήμα αποτυγχάνει ξανά και ξανά, το Claude δοκιμάζει άλλο τρόπο',
218 'no news for 3 minutes. Press Esc to stop Claude, or give it a little longer': 'κανένα νέο για 3 λεπτά. Πάτα Esc για να σταματήσεις το Claude, ή δώσ’ του λίγο ακόμα χρόνο',
219 "Claude couldn't help with that request": 'Το Claude δεν μπόρεσε να βοηθήσει με αυτό το αίτημα',
220 "Claude can't go on right now": 'Το Claude δεν μπορεί να συνεχίσει τώρα',
221 'type /compact and try again': 'γράψε /compact και δοκίμασε ξανά',
222 'you hit your usage limit, try again a little later': 'έφτασες το όριο χρήσης, δοκίμασε ξανά λίγο αργότερα',
223 "Claude's servers are busy, try again in a minute": 'οι διακομιστές του Claude είναι απασχολημένοι, δοκίμασε ξανά σε ένα λεπτό',
224 'type /login': 'γράψε /login',
225 'the internet connection dropped': 'η σύνδεση στο διαδίκτυο χάθηκε',
226
227 // Other chats on this computer
228 '1 other chat at work': '1 ακόμα συζήτηση δουλεύει',
229 '{0} other chats at work': '{0} ακόμα συζητήσεις δουλεύουν',
230 'Another chat needs you: {0}': 'Μια άλλη συζήτηση σε χρειάζεται: {0}',
231 '{0} other chats need you: {1}': '{0} άλλες συζητήσεις σε χρειάζονται: {1}',
232 '{0} more at work': 'δουλεύουν ακόμα {0}',
233
234 // Sounds and notices
235 'Claude needs you': 'Το Claude σε χρειάζεται',
236 'Claude is stuck': 'Το Claude κόλλησε',
237 'This is how GlanceFlow will tell you.': 'Έτσι θα σε ειδοποιεί το GlanceFlow.',
238
239 // The welcome
240 'Welcome to GlanceFlow': 'Καλώς ήρθες στο GlanceFlow',
241 'Welcome': 'Καλώς ήρθες',
242 'Welcome to GlanceFlow · {0} of {1}': 'Καλώς ήρθες στο GlanceFlow · {0} από {1}',
243 'A checklist shows here when you ask Claude for something with a few steps: each step, how far along it is, and about how long is left.':
244 'Εδώ εμφανίζεται μια λίστα όταν ζητάς από το Claude κάτι με λίγα βήματα: κάθε βήμα, πόσο έχει προχωρήσει και περίπου πόσο απομένει.',
245 'When Claude needs you, the checklist says Needs you {0}, and what to do. Turn on sounds or desktop notices in Settings to hear or see it from another app.':
246 'Όταν το Claude σε χρειάζεται, η λίστα γράφει Σε χρειάζεται {0}, και τι να κάνεις. Άνοιξε ήχους ή ειδοποιήσεις στις Ρυθμίσεις για να το ακούς ή να το βλέπεις από άλλη εφαρμογή.',
247 'in yellow': 'με κίτρινο',
248 'beside a yellow bell': 'δίπλα σε ένα κίτρινο καμπανάκι',
249 'Settings, below, holds every choice. History shows your past jobs and Your week. To see this welcome again, type /glanceflow tour.':
250 'Οι Ρυθμίσεις, από κάτω, έχουν κάθε επιλογή. Το Ιστορικό δείχνει τις παλιές σου δουλειές και Η εβδομάδα σου. Για να ξαναδείς αυτό το καλωσόρισμα, γράψε /glanceflow tour.',
251
252 // Messages that pop up
253 'Nothing is running right now.': 'Τίποτα δεν τρέχει αυτή τη στιγμή.',
254 'Paused. Press Continue to pick up where Claude stopped.': 'Σε παύση. Πάτα Συνέχεια για να συνεχίσει από εκεί που σταμάτησε το Claude.',
255 "Couldn't pause right now. Press Esc to stop instead.": 'Δεν έγινε παύση τώρα. Πάτα Esc για να το σταματήσεις.',
256 "Couldn't continue right now. Type: continue": 'Δεν έγινε συνέχεια τώρα. Γράψε: συνέχισε',
257 'The report is in the panel: select it there to copy it.': 'Η αναφορά είναι στο πλαϊνό πάνελ: επίλεξέ την εκεί για να την αντιγράψεις.',
258 'Your week copied: paste it wherever you like.': 'Η εβδομάδα σου αντιγράφηκε: επικόλλησέ την όπου θέλεις.',
259 'Team report copied: paste it into Slack, Teams or an email.': 'Η αναφορά για την ομάδα αντιγράφηκε: επικόλλησέ την στο Slack, στο Teams ή σε ένα email.',
260 'Writing a handoff note for the fresh chat…': 'Γράφει σημείωμα μετάβασης για τη νέα συζήτηση…',
261 "Couldn't write the handoff note. Nothing was cleared.": 'Δεν γράφτηκε το σημείωμα μετάβασης. Δεν σβήστηκε τίποτα.',
262 "Couldn't write the handoff note ({0}). Nothing was cleared.": 'Δεν γράφτηκε το σημείωμα μετάβασης ({0}). Δεν σβήστηκε τίποτα.',
263 "Couldn't clear the chat. Type /glanceflow handoff note to get the handoff note.": 'Η συζήτηση δεν καθάρισε. Γράψε /glanceflow handoff note για να πάρεις το σημείωμα μετάβασης.',
264 'Chat cleared. The handoff note is in the prompt box: press Enter to send it.': 'Η συζήτηση καθάρισε. Το σημείωμα μετάβασης είναι στο πλαίσιο κειμένου: πάτα Enter για να το στείλεις.',
265 'Fresh chat started from a handoff note.': 'Ξεκίνησε νέα συζήτηση από σημείωμα μετάβασης.',
266 "Couldn't open that helper: {0}": 'Δεν άνοιξε αυτός ο βοηθός: {0}',
267 'this needs a newer Claude Code': 'χρειάζεται νεότερο Claude Code',
268 "Couldn't stop it: {0}": 'Δεν σταμάτησε: {0}',
269 'Claude Code said no': 'το Claude Code είπε όχι',
270 'Saving a checkpoint, then tidying up the chat…': 'Κρατά ένα σημείο ελέγχου και μετά τακτοποιεί τη συζήτηση…',
271 "Couldn't save a checkpoint; tidying up anyway.": 'Δεν κρατήθηκε σημείο ελέγχου· η τακτοποίηση γίνεται κανονικά.',
272 'The chat was not tidied up: {0}': 'Η συζήτηση δεν τακτοποιήθηκε: {0}',
273 "Couldn't tidy up the chat ({0}). Type /compact to try again.": 'Η συζήτηση δεν τακτοποιήθηκε ({0}). Γράψε /compact για να ξαναδοκιμάσεις.',
274 'This message looks like it has {0} in it, so it was not sent. Press Enter again to send it anyway, or take it out first.':
275 'Αυτό το μήνυμα μοιάζει να έχει μέσα {0}, γι’ αυτό δεν στάλθηκε. Πάτα ξανά Enter για να σταλεί έτσι κι αλλιώς, ή βγάλ’ το πρώτα.',
276 'a key or token': 'ένα κλειδί ή token',
277 'a password or key': 'έναν κωδικό ή κλειδί',
278 'a password': 'έναν κωδικό',
279 'a card number': 'αριθμό κάρτας',
280 'a bank account number': 'αριθμό τραπεζικού λογαριασμού',
281 'The message looked like it held a password or key, so GlanceFlow held it back.': 'Το μήνυμα έμοιαζε να έχει κωδικό ή κλειδί, οπότε το GlanceFlow το κράτησε πίσω.',
282 'GlanceFlow is on: tool details are hidden': 'Το GlanceFlow είναι ενεργό: οι λεπτομέρειες των εργαλείων κρύβονται',
283 'GlanceFlow is off: showing everything': 'Το GlanceFlow είναι ανενεργό: φαίνονται όλα',
284 'GlanceFlow details: models, time, tokens, cache and plan usage': 'GlanceFlow αναλυτικά: μοντέλα, χρόνος, tokens, μνήμη και χρήση συνδρομής',
285 'GlanceFlow simple: just the steps and progress': 'GlanceFlow απλό: μόνο τα βήματα και η πρόοδος',
286 'Details on: models, tokens, cache and plan usage': 'Αναλυτικά ενεργά: μοντέλα, tokens, μνήμη και χρήση συνδρομής',
287 'Details off: just the steps and progress': 'Αναλυτικά ανενεργά: μόνο τα βήματα και η πρόοδος',
288 'The ship-it steps are in the prompt box: press Enter to send them.': 'Τα βήματα για το ανέβασμα είναι στο πλαίσιο κειμένου: πάτα Enter για να τα στείλεις.',
289 "Couldn't start right now. Type: start": 'Δεν έγινε έναρξη τώρα. Γράψε: ξεκίνα',
290 "Couldn't send that right now. Ask Claude for a deeper plan.": 'Δεν στάλθηκε τώρα. Ζήτα από το Claude ένα πιο βαθύ πλάνο.',
291 'Settings are back to their defaults.': 'Οι ρυθμίσεις γύρισαν στις αρχικές τους.',
292 'GlanceFlow {0} is installed. Open a new chat to use it.': 'Το GlanceFlow {0} εγκαταστάθηκε. Άνοιξε νέα συζήτηση για να το χρησιμοποιήσεις.',
293
294 // Replies to /glanceflow
295 'Sounds are off.': 'Οι ήχοι είναι ανενεργοί.',
296 'Sounds and voice are on: you will hear when Claude needs you, gets stuck or finishes a long job.': 'Οι ήχοι και η φωνή είναι ενεργοί: θα ακούς όταν το Claude σε χρειάζεται, κολλάει ή τελειώνει μια μεγάλη δουλειά.',
297 'Sounds are on: a chime when Claude needs you, gets stuck or finishes a long job.': 'Οι ήχοι είναι ενεργοί: ένα κουδούνισμα όταν το Claude σε χρειάζεται, κολλάει ή τελειώνει μια μεγάλη δουλειά.',
298 'Try /glanceflow language el or /glanceflow language en.': 'Δοκίμασε /glanceflow language el ή /glanceflow language en.',
299 'GlanceFlow speaks English now.': 'Το GlanceFlow μιλάει πλέον Ελληνικά.',
300 'Calm mode is on: nothing moves, statuses are bold.': 'Η ήρεμη λειτουργία είναι ενεργή: τίποτα δεν κινείται, οι καταστάσεις είναι με έντονα.',
301 'Calm mode is off.': 'Η ήρεμη λειτουργία είναι ανενεργή.',
302 'The password guard is on: a message that looks like it has a password or key in it is held back.': 'Η προστασία κωδικών είναι ενεργή: ένα μήνυμα που μοιάζει να έχει κωδικό ή κλειδί κρατιέται πίσω.',
303 'The password guard is off: every message is sent as you write it.': 'Η προστασία κωδικών είναι ανενεργή: κάθε μήνυμα στέλνεται όπως το γράφεις.',
304 'The GlanceFlow checklist is open.': 'Η λίστα του GlanceFlow είναι ανοιχτή.',
305 "Couldn't open the checklist: {0}.": 'Η λίστα δεν άνοιξε: {0}.',
306 'The welcome shows above the prompt: press Next to go through it.': 'Το καλωσόρισμα φαίνεται πάνω από το πλαίσιο κειμένου: πάτα Επόμενο για να το δεις.',
307 'Desktop notices are on: your computer, and any Notification hooks you set up for Claude Code, tell you when Claude needs you, gets stuck or finishes a long job.':
308 'Οι ειδοποιήσεις είναι ενεργές: ο υπολογιστής σου, και όποια Notification hooks έχεις ορίσει στο Claude Code, σου λένε όταν το Claude σε χρειάζεται, κολλάει ή τελειώνει μια μεγάλη δουλειά.',
309 'Desktop notices are off.': 'Οι ειδοποιήσεις είναι ανενεργές.',
310 'The band names another chat on this computer that needs you.': 'Η μπάρα δείχνει μια άλλη συζήτηση σε αυτόν τον υπολογιστή που σε χρειάζεται.',
311 'The band no longer mentions other chats.': 'Η μπάρα δεν αναφέρει πια άλλες συζητήσεις.',
312 'Claude now shows its plan and waits: press Start, or tell Claude what to change.': 'Το Claude τώρα δείχνει το πλάνο του και περιμένει: πάτα Έναρξη, ή πες στο Claude τι να αλλάξει.',
313 'Claude starts right after laying out its plan.': 'Το Claude ξεκινά αμέσως μόλις φτιάξει το πλάνο του.',
314 'Shipping on GitHub…': 'Ανέβασμα στο GitHub…',
315 'A finished job now offers Ship it: commit, pull request, and merge once you approve.': 'Μια δουλειά που τελείωσε προσφέρει τώρα το Ανέβασέ το: commit, pull request και merge μόλις εγκρίνεις.',
316 'Ship it is off. Finished jobs stay on their branch.': 'Το Ανέβασέ το είναι ανενεργό. Οι δουλειές που τελείωσαν μένουν στο branch τους.',
317 'No history yet.': 'Δεν υπάρχει ιστορικό ακόμα.',
318 'Try /glanceflow history, /glanceflow history yesterday or /glanceflow history 2026-10-06.': 'Δοκίμασε /glanceflow history, /glanceflow history yesterday ή /glanceflow history 2026-10-06.',
319 'History for {0}: {1}.': 'Ιστορικό για {0}: {1}.',
320 'History for {0}: {1}. Widen the window to see the panel.': 'Ιστορικό για {0}: {1}. Άνοιξε πιο πολύ το παράθυρο για να δεις το πάνελ.',
321 'Paused.': 'Σε παύση.',
322 'Saving a checkpoint, then tidying up the chat.': 'Κρατά ένα σημείο ελέγχου και μετά τακτοποιεί τη συζήτηση.',
323 'Try /glanceflow tidy, /glanceflow tidy at 50 or /glanceflow tidy off.': 'Δοκίμασε /glanceflow tidy, /glanceflow tidy at 50 ή /glanceflow tidy off.',
324 'GlanceFlow will not offer to tidy up.': 'Το GlanceFlow δεν θα προτείνει τακτοποίηση.',
325 'GlanceFlow offers to tidy up at {0}% full.': 'Το GlanceFlow προτείνει τακτοποίηση όταν η συζήτηση γεμίσει στο {0}%.',
326 'Settings are in the side panel.': 'Οι Ρυθμίσεις είναι στο πλαϊνό πάνελ.',
327 'No checkpoint in this chat yet. Tidy it up saves one.': 'Δεν υπάρχει σημείο ελέγχου σε αυτή τη συζήτηση ακόμα. Η Τακτοποίηση κρατά ένα.',
328 'Where we left off is in the side panel.': 'Το Πού μείναμε είναι στο πλαϊνό πάνελ.',
329 'The plan is in the side panel.': 'Το πλάνο είναι στο πλαϊνό πάνελ.',
330 'Continuing…': 'Συνεχίζει…',
331 'No handoff note saved yet.': 'Δεν έχει κρατηθεί σημείωμα μετάβασης ακόμα.',
332 'The last handoff note is in the prompt box.': 'Το τελευταίο σημείωμα μετάβασης είναι στο πλαίσιο κειμένου.',
333 'Starting a fresh chat from a handoff note…': 'Ξεκινά νέα συζήτηση από σημείωμα μετάβασης…',
334 'The goal for this project is cleared.': 'Ο στόχος για αυτό το έργο σβήστηκε.',
335 'The goal for this project: {0}. Claude plans each job toward it. Clear it with /glanceflow goal off.':
336 'Ο στόχος για αυτό το έργο: {0}. Το Claude σχεδιάζει κάθε δουλειά προς αυτόν. Σβήσ’ τον με /glanceflow goal off.',
337 'No goal for this project yet. Set one with /glanceflow goal and what you want, like: keep sign-ups working.':
338 'Δεν υπάρχει στόχος για αυτό το έργο ακόμα. Βάλε έναν με /glanceflow goal και αυτό που θέλεις, π.χ.: να δουλεύουν οι εγγραφές.',
339 'The goal for this project: {0}. Claude plans each new job toward it.': 'Ο στόχος για αυτό το έργο: {0}. Το Claude σχεδιάζει κάθε νέα δουλειά προς αυτόν.',
340 'GlanceFlow details are on.': 'Τα αναλυτικά του GlanceFlow είναι ενεργά.',
341 'GlanceFlow details are off.': 'Τα αναλυτικά του GlanceFlow είναι ανενεργά.',
342 'GlanceFlow is on.': 'Το GlanceFlow είναι ενεργό.',
343 'GlanceFlow is off.': 'Το GlanceFlow είναι ανενεργό.',
344
345 // Settings
346 'GlanceFlow settings': 'Ρυθμίσεις GlanceFlow',
347 'Changes apply right away and stay for your next chats.': 'Οι αλλαγές ισχύουν αμέσως και μένουν για τις επόμενες συζητήσεις σου.',
348 'The steps and progress in plain words, with tool details out of the way. For everyone.': 'Τα βήματα και η πρόοδος με απλά λόγια, χωρίς λεπτομέρειες εργαλείων. Για όλους.',
349 'Also time, models and tokens per step, with the code in view. For engineers.': 'Επίσης χρόνος, μοντέλα και tokens ανά βήμα, με τον κώδικα σε θέα. Για μηχανικούς.',
350 'Claude Code as usual: no checklist, every tool row shown. The password guard keeps its own setting.':
351 'Το Claude Code όπως πάντα: χωρίς λίστα, με κάθε γραμμή εργαλείου. Η προστασία κωδικών κρατά τη δική της ρύθμιση.',
352 'Sounds': 'Ήχοι',
353 'Chime': 'Κουδούνισμα',
354 'Chime and voice': 'Κουδούνισμα και φωνή',
355 'Play it': 'Άκουσέ το',
356 'No sounds. Turn them on to look away while Claude works.': 'Χωρίς ήχους. Άνοιξέ τους για να κοιτάς αλλού όσο δουλεύει το Claude.',
357 'A short chime when Claude needs you, gets stuck, or finishes a job that took over a minute.': 'Ένα σύντομο κουδούνισμα όταν το Claude σε χρειάζεται, κολλάει ή τελειώνει μια δουλειά που κράτησε πάνω από ένα λεπτό.',
358 'The chime, and a few words like "Claude needs you".': 'Το κουδούνισμα, και λίγες λέξεις όπως «Το Claude σε χρειάζεται».',
359 'Desktop notices': 'Ειδοποιήσεις',
360 'A notice when Claude needs you, gets stuck, or finishes a job that took over a minute: on your computer, and through your Claude Code Notification hooks, such as one that reaches your phone.':
361 'Μια ειδοποίηση όταν το Claude σε χρειάζεται, κολλάει ή τελειώνει μια δουλειά που κράτησε πάνω από ένα λεπτό: στον υπολογιστή σου, και μέσα από τα Notification hooks του Claude Code, όπως ένα που φτάνει στο κινητό σου.',
362 'Turn on to get a notice on your computer, even while you work in another app, or on your phone through your Claude Code Notification hooks.':
363 'Άνοιξέ το για να παίρνεις ειδοποίηση στον υπολογιστή σου, ακόμα κι όταν δουλεύεις σε άλλη εφαρμογή, ή στο κινητό σου μέσα από τα Notification hooks του Claude Code.',
364 'Other chats': 'Άλλες συζητήσεις',
365 'The band names another chat on this computer that needs you, from any project. Turn off before you share your screen.':
366 'Η μπάρα δείχνει μια άλλη συζήτηση σε αυτόν τον υπολογιστή που σε χρειάζεται, από οποιοδήποτε έργο. Κλείσ’ το πριν μοιραστείς την οθόνη σου.',
367 'Turn on to see when another chat on this computer needs you.': 'Άνοιξέ το για να βλέπεις πότε σε χρειάζεται μια άλλη συζήτηση σε αυτόν τον υπολογιστή.',
368 'Language': 'Γλώσσα',
369 "GlanceFlow's own words, and the steps Claude writes on the checklist.": 'Οι λέξεις του GlanceFlow, και τα βήματα που γράφει το Claude στη λίστα.',
370 'Calm mode': 'Ήρεμη λειτουργία',
371 'Nothing on screen moves, and statuses read in bold.': 'Τίποτα στην οθόνη δεν κινείται, και οι καταστάσεις φαίνονται με έντονα.',
372 'Bars and spinners move while Claude works. Turn on for a still screen.': 'Οι μπάρες και οι δείκτες κινούνται όσο δουλεύει το Claude. Άνοιξέ το για ακίνητη οθόνη.',
373 'Approve the plan first': 'Έγκρινε πρώτα το πλάνο',
374 'Claude shows its plan and waits. Press {0}, or tell Claude what to change.': 'Το Claude δείχνει το πλάνο του και περιμένει. Πάτα {0}, ή πες στο Claude τι να αλλάξει.',
375 'Finish on GitHub': 'Ολοκλήρωση στο GitHub',
376 'A finished job offers Ship it: Claude tidies the changes, opens a pull request and merges once you approve.':
377 'Μια δουλειά που τελείωσε προσφέρει το Ανέβασέ το: το Claude τακτοποιεί τις αλλαγές, ανοίγει ένα pull request και κάνει merge μόλις εγκρίνεις.',
378 'Finished jobs stay on their branch. Turn on for a Ship it button in GitHub projects.': 'Οι δουλειές που τελείωσαν μένουν στο branch τους. Άνοιξέ το για κουμπί Ανέβασέ το σε έργα του GitHub.',
379 'Password guard': 'Προστασία κωδικών',
380 'A message that looks like it has a password or key in it is held back. Press Enter again to send it anyway.':
381 'Ένα μήνυμα που μοιάζει να έχει κωδικό ή κλειδί κρατιέται πίσω. Πάτα ξανά Enter για να σταλεί έτσι κι αλλιώς.',
382 'Every message is sent as you write it. Keys and emails are still masked on screen.': 'Κάθε μήνυμα στέλνεται όπως το γράφεις. Κλειδιά και email κρύβονται ακόμα στην οθόνη.',
383 'Tidy up the chat': 'Τακτοποίηση της συζήτησης',
384 'Never': 'Ποτέ',
385 'At {0}% full': 'Όταν γεμίσει στο {0}%',
386 'GlanceFlow never offers to tidy up. Claude Code still compacts on its own when the chat is full.': 'Το GlanceFlow δεν προτείνει ποτέ τακτοποίηση. Το Claude Code συμπτύσσει μόνο του όταν η συζήτηση γεμίσει.',
387 'At {0}% full, the checklist offers to tidy up. Claude first saves a checkpoint of the work (goal, what is done and left, decisions, the next step), so nothing important is lost when the chat is compacted.':
388 'Όταν η συζήτηση γεμίσει στο {0}%, η λίστα προτείνει τακτοποίηση. Το Claude πρώτα κρατά ένα σημείο ελέγχου της δουλειάς (στόχος, τι έγινε και τι μένει, αποφάσεις, το επόμενο βήμα), ώστε να μη χαθεί τίποτα σημαντικό όταν η συζήτηση συμπτυχθεί.',
389 'Last checkpoint saved at {0}.': 'Το τελευταίο σημείο ελέγχου κρατήθηκε στις {0}.',
390 'Version': 'Έκδοση',
391 'Checking fetches the newest GlanceFlow from the marketplace you installed it from.': 'Ο έλεγχος φέρνει το νεότερο GlanceFlow από το marketplace απ’ όπου το εγκατέστησες.',
392 'Checking for a newer version…': 'Ψάχνει για νεότερη έκδοση…',
393 'You have the newest version.': 'Έχεις τη νεότερη έκδοση.',
394 'GlanceFlow {0} is out. Update installs it; a new chat then uses it.': 'Βγήκε το GlanceFlow {0}. Η Ενημέρωση το εγκαθιστά· μια νέα συζήτηση μετά το χρησιμοποιεί.',
395 'Installing GlanceFlow {0}…': 'Εγκαθιστά το GlanceFlow {0}…',
396 'This copy runs from a folder, not a marketplace, so it updates where it lives (with git pull, say).': 'Αυτό το αντίγραφο τρέχει από φάκελο, όχι από marketplace, οπότε ενημερώνεται εκεί που βρίσκεται (με git pull, ας πούμε).',
397 "Couldn't check or update from here. In a terminal, run: {0}": 'Δεν έγινε έλεγχος ή ενημέρωση από εδώ. Σε ένα τερματικό, τρέξε: {0}',
398 'Update to {0}': 'Ενημέρωση σε {0}',
399 'Check for updates': 'Έλεγχος για ενημερώσεις',
400 'Reset to defaults': 'Επαναφορά αρχικών',
401
402 // The Plan
403 'No plan yet. Ask Claude for something and its plan shows here.': 'Κανένα πλάνο ακόμα. Ζήτα κάτι από το Claude και το πλάνο του φαίνεται εδώ.',
404 'Started {0}': 'Ξεκίνησε {0}',
405 'finished {0}': 'τελείωσε {0}',
406 'done around {0}': 'τελειώνει γύρω στις {0}',
407 'about {0} left, done around {1}': 'περίπου {0} ακόμα, τελειώνει γύρω στις {1}',
408 '{0} of {1} steps done': 'έγιναν {0} από {1} βήματα',
409 'Goal: {0}': 'Στόχος: {0}',
410 'Done when: {0}': 'Έτοιμο όταν: {0}',
411 'Helpers: {0}': 'Βοηθοί: {0}',
412 '{0} working': 'δουλεύουν {0}',
413 '{0} finished': 'τελείωσαν {0}',
414 'Time left is based on how long steps took in this project before.': 'Ο χρόνος που απομένει βασίζεται στο πόσο κράτησαν τα βήματα σε αυτό το έργο μέχρι τώρα.',
415 'This job: {0}': 'Αυτή η δουλειά: {0}',
416 'No checkpoint in this chat yet. When Claude tidies the chat up, it saves one first, and it shows here.':
417 'Δεν υπάρχει σημείο ελέγχου σε αυτή τη συζήτηση ακόμα. Όταν το Claude τακτοποιεί τη συζήτηση, κρατά πρώτα ένα, και φαίνεται εδώ.',
418 'Saved before the chat was tidied up. Claude keeps reading it for the rest of this chat.': 'Κρατήθηκε πριν τακτοποιηθεί η συζήτηση. Το Claude το διαβάζει για την υπόλοιπη συζήτηση.',
419 'Saved at {0}, before the chat was tidied up. Claude keeps reading it for the rest of this chat.': 'Κρατήθηκε στις {0}, πριν τακτοποιηθεί η συζήτηση. Το Claude το διαβάζει για την υπόλοιπη συζήτηση.',
420
421 // History
422 'History · {0}': 'Ιστορικό · {0}',
423 "Type /glanceflow history to see today's tasks.": 'Γράψε /glanceflow history για να δεις τις σημερινές εργασίες.',
424 'Today': 'Σήμερα',
425 'Today · {0}': 'Σήμερα · {0}',
426 'Today, {0}': 'Σήμερα, {0}',
427 'Previous day': 'Προηγούμενη μέρα',
428 'Next day': 'Επόμενη μέρα',
429 'Earlier': 'Νωρίτερα',
430 'Day': 'Μέρα',
431 'Copy report': 'Αντιγραφή αναφοράς',
432 "What you'll paste": 'Τι θα επικολλήσεις',
433 'Back to the list': 'Πίσω στη λίστα',
434 'Day report': 'Αναφορά ημέρας',
435 'Week report': 'Αναφορά εβδομάδας',
436 'This day': 'Αυτή η μέρα',
437 'This week': 'Αυτή η εβδομάδα',
438 'Team report': 'Αναφορά για την ομάδα',
439 'Your week': 'Η εβδομάδα σου',
440 'All projects this week': 'Όλα τα έργα αυτή την εβδομάδα',
441 'No tasks saved for this project on that day yet.': 'Δεν υπάρχουν εργασίες για αυτό το έργο εκείνη τη μέρα.',
442 'not finished': 'δεν τελείωσε',
443 '{0} of {1} steps': '{0} από {1} βήματα',
444 '1 task': '1 εργασία',
445 '{0} tasks': '{0} εργασίες',
446 '1 step': '1 βήμα',
447 '{0} steps': '{0} βήματα',
448 '{0} done': 'έγιναν {0}',
449 '{0} stopped': 'σταμάτησαν {0}',
450 '{0} stuck': 'κόλλησαν {0}',
451 '{0} waiting': 'περιμένουν {0}',
452 '{0} background': 'στο παρασκήνιο {0}',
453 'Total: {0}': 'Σύνολο: {0}',
454 '{0} more': '{0} ακόμα',
455 'added {0}': 'πρόσθεσε {0}',
456 'changed {0}': 'άλλαξε {0}',
457 'tested': 'δοκιμάστηκε',
458 'tests failed': 'τα τεστ απέτυχαν',
459 'not tested': 'δεν δοκιμάστηκε',
460
461 // The team report and your week
462 'Weekly update · {0} · {1} to {2}': 'Εβδομαδιαία ενημέρωση · {0} · {1} έως {2}',
463 'Daily update · {0} · {1}': 'Ημερήσια ενημέρωση · {0} · {1}',
464 'Goal: {0} · 1 task, {1} finished, {2} tested': 'Στόχος: {0} · 1 εργασία, τελείωσαν {1}, δοκιμάστηκαν {2}',
465 'Goal: {0} · {1} tasks, {2} finished, {3} tested': 'Στόχος: {0} · {1} εργασίες, τελείωσαν {2}, δοκιμάστηκαν {3}',
466 'No planned work was recorded this week.': 'Δεν καταγράφηκε σχεδιασμένη δουλειά αυτή την εβδομάδα.',
467 'No planned work was recorded on this day.': 'Δεν καταγράφηκε σχεδιασμένη δουλειά αυτή τη μέρα.',
468 'Decided: {0}': 'Αποφασίστηκε: {0}',
469 'Still open': 'Ακόμα ανοιχτά',
470 '{0}: {1} of {2} steps done; next: {3}': '{0}: έγιναν {1} από {2} βήματα· επόμενο: {3}',
471 '{0}: {1} of {2} steps done': '{0}: έγιναν {1} από {2} βήματα',
472 'Needs attention': 'Θέλει προσοχή',
473 '{0}: it got stuck and needs a decision': '{0}: κόλλησε και χρειάζεται απόφαση',
474 '{0} of 1 task finished · {1} of work': 'τελείωσαν {0} από 1 εργασία · {1} δουλειάς',
475 '{0} of {1} tasks finished · {2} of work': 'τελείωσαν {0} από {1} εργασίες · {2} δουλειάς',
476 'Your week with Claude · {0} to {1}': 'Η εβδομάδα σου με το Claude · {0} έως {1}',
477 'No planned work was recorded this week. Ask Claude for something with a few steps, and it shows here.':
478 'Δεν καταγράφηκε σχεδιασμένη δουλειά αυτή την εβδομάδα. Ζήτα από το Claude κάτι με λίγα βήματα, και φαίνεται εδώ.',
479 'Claude checked off {0} in {1}, and finished {2} of them.': 'Το Claude ολοκλήρωσε {0} σε {1}, και τελείωσε {2} από αυτές.',
480 'Time at work: {0}, across {1} projects.': 'Χρόνος δουλειάς: {0}, σε {1} έργα.',
481 'Time at work: {0}.': 'Χρόνος δουλειάς: {0}.',
482 'Busiest day: {0}, with {1}.': 'Πιο γεμάτη μέρα: {0}, με {1}.',
483 'Biggest tasks': 'Οι μεγαλύτερες εργασίες',
484}
485hooks/logic.ts 1366 lines1import type { GlanceCheck, GlanceChecklist, GlanceHelper, GlanceHistoryView, GlanceOtherChat, GlanceTask, GlanceTaskSize, GlanceUsage } from '../types'
2import { SIZE_WEIGHT, teamReport, weekSummary } from './history'
3import { maskPrivate } from './privacy'
4import { currentLang, tr } from './words'
5
6// History reads them too, so they live there.
7export { CHECK_WORDS, jobCheck } from './history'
8
9export const PLUGIN = 'glanceflow'
10// Claude Desktop's own task list and end-of-turn box, from its Code tab's built-in ccd_turn server.
11export const NATIVE_PLAN = 'mcp__ccd_turn__update_plan'
12export const NATIVE_WRAP_UP = 'mcp__ccd_turn__wrap_up'
13
14export const tourNeeds = (mark: string) =>
15 tr('When Claude needs you, the checklist says Needs you {0}, and what to do. Turn on sounds or desktop notices in Settings to hear or see it from another app.', mark)
16
17export const MAX_NAME = 40
18
19export const QUESTION = "Answer Claude's question in the chat"
20
21export const WAITING = 'Reply to Claude in the box below'
22
23// The longest plain sentence Claude's own description of a tool call keeps.
24export const MAX_DETAIL = 90
25
26export const CODE_FILE =
27 /\.(tsx?|jsx?|mjs|cjs|mts|cts|py|rb|go|rs|java|kts?|swift|c|cc|cpp|h|hpp|cs|php|sh|zsh|bash|json|ya?ml|toml|css|scss|sass|less|html?|md|mdx|sql|vue|svelte|lock|env|xml|ini|cfg|conf|txt|csv|log)\W*$/i
28
29export const pad2 = (value: number) => String(value).padStart(2, '0')
30
31/** "10:01:45 UTC" in the person's own time, "13:01:45" in Athens; a time without UTC, GMT or Z is left as written. */
32export function localTimes(text: string, today = new Date()): string {
33 return text.replace(/(?<![\d:])(\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?\s?(?:UTC|GMT|Z)\b/g, (whole, hours, minutes, seconds) => {
34 if (Number(hours) > 23 || Number(minutes) > 59) return whole
35 const at = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), Number(hours), Number(minutes), Number(seconds ?? 0)))
36 return `${pad2(at.getHours())}:${pad2(at.getMinutes())}${seconds === undefined ? '' : `:${pad2(at.getSeconds())}`}`
37 })
38}
39
40/** When a plan window resets, in the person's own time: "at 18:40", or "on Thu at 09:00" when it is more than a day away. */
41export function resetTime(resetsAt: string | null, at: number): string | null {
42 const when = resetsAt ? new Date(resetsAt) : null
43 if (when === null || Number.isNaN(when.getTime())) return null
44 const time = `${pad2(when.getHours())}:${pad2(when.getMinutes())}`
45 if (when.getTime() - at <= 24 * 3_600_000) return tr('at {0}', time)
46 return tr('on {0} at {1}', when.toLocaleDateString(currentLang() === 'el' ? 'el-GR' : 'en-GB', { weekday: 'short' }), time)
47}
48
49/** Turns any step or job name, or a step's summary, into short plain English. */
50export function cleanName(raw: unknown, max = MAX_NAME): string {
51 const words = localTimes(maskPrivate(String(raw ?? '')))
52 .replace(/`[^`]*`/g, ' ')
53 .replace(/`/g, ' ')
54 .split(/\s+/)
55 .filter(word => word && !word.includes('•') && !/[/\\]/.test(word) && !CODE_FILE.test(word))
56 let name = words.join(' ').replace(/\s+/g, ' ').trim()
57 if (!name) {
58 return tr('Working on it')
59 }
60 name = name.charAt(0).toUpperCase() + name.slice(1)
61 if (name.length <= max) {
62 return name
63 }
64 const cut = name.slice(0, max - 1)
65 const space = cut.lastIndexOf(' ')
66
67 return `${(space > 0 ? cut.slice(0, space) : cut).replace(/[\s,;:.\-–]+$/, '')}…`
68}
69
70/**
71 * A name in Title Case ("Copy Mod With Button Choices") in the sentence case the checklist uses everywhere else. A
72 * word with a capital past its first letter (GlanceFlow, PR) keeps its case; a name already in sentence case stays.
73 */
74export function sentenceCase(name: string): string {
75 const words = name.split(' ')
76 if (words.length < 3 || words.some(word => /^\p{Ll}/u.test(word))) return name
77 return words.map((word, index) => (index === 0 || /\p{Lu}/u.test(word.slice(1)) ? word : word.toLowerCase())).join(' ')
78}
79
80export function apiErrorSentence(kind: string, details = ''): string {
81 if (/too long|context (window|length|limit)|max(imum)? context/i.test(details)) {
82 return 'type /compact and try again'
83 }
84 if (kind === 'rate_limit' || kind === 'billing_error') {
85 return 'you hit your usage limit, try again a little later'
86 }
87 if (kind === 'overloaded') {
88 return "Claude's servers are busy, try again in a minute"
89 }
90 if (/authentication|oauth|credential/.test(kind)) {
91 return 'type /login'
92 }
93 if (/network|connect|ECONN|ENOTFOUND|socket|fetch failed|offline/i.test(details)) {
94 return 'the internet connection dropped'
95 }
96
97 return "Claude's servers are busy, try again in a minute"
98}
99
100export function formatDuration(ms: number): string {
101 const seconds = Math.max(0, Math.round(ms / 1000))
102 if (seconds < 60) {
103 return tr('{0}s', seconds)
104 }
105 const minutes = Math.floor(seconds / 60)
106 if (minutes < 60) {
107 return tr('{0}m {1}s', minutes, seconds % 60)
108 }
109
110 return tr('{0}h {1}m', Math.floor(minutes / 60), minutes % 60)
111}
112
113/** A duration where words flow (the desktop): a whole minute drops its seconds, `1m` rather than `1m 0s`. */
114export function durationWords(ms: number): string {
115 const seconds = Math.max(0, Math.round(ms / 1000))
116 return seconds >= 60 && seconds < 3600 && seconds % 60 === 0 ? tr('{0}m', seconds / 60) : formatDuration(ms)
117}
118
119/** Terminal cells a character takes: two for CJK and emoji, none for joiners and accents. */
120export function cellsOf(char: string): number {
121 const code = char.codePointAt(0) ?? 0
122 if (code === 0x200d || (code >= 0x300 && code <= 0x36f) || (code >= 0xfe00 && code <= 0xfe0f)) return 0
123 const isWide =
124 (code >= 0x1100 && code <= 0x115f) ||
125 (code >= 0x2e80 && code <= 0xa4cf) ||
126 (code >= 0xac00 && code <= 0xd7a3) ||
127 (code >= 0xf900 && code <= 0xfaff) ||
128 (code >= 0xfe30 && code <= 0xfe4f) ||
129 (code >= 0xff00 && code <= 0xff60) ||
130 (code >= 0xffe0 && code <= 0xffe6) ||
131 (code >= 0x1f300 && code <= 0x1faff) ||
132 (code >= 0x20000 && code <= 0x3fffd)
133
134 return isWide ? 2 : 1
135}
136
137/** Pads or trims text to exactly `width` terminal cells, so columns line up in any script. */
138export function fit(text: string, width: number): string {
139 if (width <= 0) {
140 return ''
141 }
142 const chars = Array.from(text)
143 const total = chars.reduce((sum, char) => sum + cellsOf(char), 0)
144 if (total <= width) {
145 return text + ' '.repeat(width - total)
146 }
147 let kept = ''
148 let used = 0
149 for (const char of chars) {
150 const size = cellsOf(char)
151 if (used + size > width - 1) break
152 kept += char
153 used += size
154 }
155
156 return `${kept}…${' '.repeat(width - 1 - used)}`
157}
158
159export function task(name: string, status: GlanceTask['status'], id = name, size: GlanceTaskSize = 'M'): GlanceTask {
160 return { id, name, status, percent: status === 'done' ? 100 : 0, hasReported: status === 'done', size, summary: null, tokens: 0, cachedTokens: 0, startedAt: null, finishedAt: null }
161}
162
163/** Token counts move to the new plan's step of the same name; the rest go to its first step, so the job total holds. */
164export function carryTokens(old: GlanceTask[], next: GlanceTask[]): GlanceTask[] {
165 const used = new Set<string>()
166 const carried = next.map(one => {
167 const same = old.find(before => before.name === one.name && !used.has(before.id))
168 if (!same) return one
169 used.add(same.id)
170 return { ...one, tokens: same.tokens, cachedTokens: same.cachedTokens, summary: same.summary, files: same.files, check: same.check }
171 })
172 const leftover = old.filter(before => !used.has(before.id))
173 const [first, ...rest] = carried
174 if (!first) return carried
175
176 return [
177 {
178 ...first,
179 tokens: first.tokens + leftover.reduce((sum, one) => sum + one.tokens, 0),
180 cachedTokens: first.cachedTokens + leftover.reduce((sum, one) => sum + one.cachedTokens, 0),
181 },
182 ...rest,
183 ]
184}
185
186/** 950 → 950, 12_400 → 12.4k, 3_200_000 → 3.2M. */
187export function formatTokens(count: number): string {
188 if (count < 1000) return String(count)
189 if (count < 1_000_000) return `${(count / 1000).toFixed(count < 100_000 ? 1 : 0).replace(/\.0$/, '')}k`
190
191 return `${(count / 1_000_000).toFixed(1)}M`
192}
193
194/** New tokens first (what really counts), then the cheap ones read back from the cache. */
195export function tokenNote(tokens: number, cachedTokens: number): string {
196 if (tokens <= 0) return ''
197 if (cachedTokens <= 0) return tr('{0} tokens', formatTokens(tokens))
198
199 return tr('{0} new · {1} cached', formatTokens(tokens - cachedTokens), formatTokens(cachedTokens))
200}
201
202export function sizeOf(raw: unknown): GlanceTaskSize {
203 const size = String(raw ?? '').trim().toUpperCase()
204
205 return size === 'S' || size === 'L' ? size : 'M'
206}
207
208/** Overall progress: finished work out of the plan, S/M/L counting 1/2/3, the current step in part. */
209export function overallProgress(
210 tasks: GlanceTask[],
211 activePercent?: number,
212): { percent: number; doneCount: number; work: number } {
213 const total = tasks.reduce((sum, one) => sum + SIZE_WEIGHT[one.size], 0)
214 const work = tasks.reduce((sum, one) => {
215 const weight = SIZE_WEIGHT[one.size]
216 if (one.status === 'done') return sum + weight
217 if (one.status === 'active' && activePercent !== undefined) return sum + (weight * activePercent) / 100
218 if (one.status === 'active' && one.hasReported) return sum + (weight * one.percent) / 100
219 return sum
220 }, 0)
221
222 return {
223 percent: total ? Math.round((100 * work) / total) : 0,
224 doneCount: tasks.filter(one => one.status === 'done').length,
225 work: total ? work / total : 0,
226 }
227}
228
229/** Each step's start and end time, stamped as its status changes. */
230export function stampTimes(tasks: GlanceTask[], at: number): GlanceTask[] {
231 return tasks.map(one => {
232 if (one.status === 'upcoming') return one.startedAt === null && one.finishedAt === null ? one : { ...one, startedAt: null, finishedAt: null }
233 if (one.status === 'active') return one.startedAt === null || one.finishedAt !== null ? { ...one, startedAt: one.startedAt ?? at, finishedAt: null } : one
234 return one.finishedAt === null ? { ...one, startedAt: one.startedAt ?? at, finishedAt: at } : one
235 })
236}
237
238// A step of size M is expected to take 3 minutes until this job's or this project's pace is known.
239export const DEFAULT_UNIT_MS = 90_000
240
241// The project's pace from History counts as much as this many units of this job's own finished steps.
242export const PACE_WEIGHT = 2
243
244/**
245 * How far along the current step looks: time spent against the time this job's finished steps took per
246 * unit of size. It fills gradually, stays below 100 until the step is checked off, and never falls below
247 * what Claude reported.
248 *
249 * Time left is null once the step runs past what it should take: the percentage then sits near the top
250 * whatever happens, so time spent against it would keep saying "under a minute". A lower percentage that
251 * Claude reported still gives an estimate.
252 */
253export function stepEstimate(list: GlanceChecklist, one: GlanceTask, at: number) {
254 const done = list.tasks.filter(
255 step => step.status === 'done' && step.startedAt !== null && step.finishedAt !== null && step.finishedAt > step.startedAt,
256 )
257 const units = done.reduce((sum, step) => sum + SIZE_WEIGHT[step.size], 0)
258 const spent = done.reduce((sum, step) => sum + (step.finishedAt! - step.startedAt!), 0)
259 const prior = list.paceMs === null ? 0 : PACE_WEIGHT
260 const unitMs = units + prior > 0 ? (spent + (list.paceMs ?? 0) * prior) / (units + prior) : DEFAULT_UNIT_MS
261 const expected = Math.max(10_000, unitMs * SIZE_WEIGHT[one.size])
262 const elapsedMs = one.startedAt === null ? 0 : Math.max(0, at - one.startedAt)
263 const estimate = Math.min(95, Math.round((100 * elapsedMs) / expected))
264 const reported = one.hasReported && one.percent > 0 && one.percent < LONG_STEP_REPORT ? one.percent : null
265 // Past its expected time, time spent says nothing more: what Claude reported is the better guess.
266 const percent = elapsedMs > expected && reported !== null ? reported : Math.min(99, Math.max(one.hasReported ? one.percent : 0, estimate))
267 const leftMs =
268 elapsedMs <= expected
269 ? percent > 0
270 ? (elapsedMs * (100 - percent)) / percent
271 : expected
272 : reported === null
273 ? null
274 : (elapsedMs * (100 - reported)) / reported
275
276 return { percent, elapsedMs, expectedMs: expected, leftMs }
277}
278
279// Past its expected time, a step's own report below this still says how far along it is.
280export const LONG_STEP_REPORT = 90
281
282/** A step's time left: short for the terminal's columns (`<1m left`), in words where text flows (`under a minute left`). */
283export function leftLabel(ms: number | null, isWords = false): string {
284 if (ms === null) return tr('taking longer')
285 if (isWords) return ms < 60_000 ? tr('under a minute left') : tr('about {0} left', formatLeft(ms))
286 return ms < 60_000 ? tr('<1m left') : tr('~{0} left', formatLeft(ms))
287}
288
289/**
290 * Time left at this job's own pace since the plan once two steps are done. Before that, the steps left at
291 * this project's usual pace from History; nothing when History doesn't know it yet.
292 */
293export function timeLeft(list: GlanceChecklist, at: number, activePercent?: number): number | null {
294 const { doneCount, work } = overallProgress(list.tasks, activePercent)
295 if (list.planAt === null || work >= 1) return null
296 // A step running long makes any total a guess: say nothing rather than something too short.
297 const active = list.tasks.find(one => one.status === 'active')
298 if (active && stepEstimate(list, active, at).leftMs === null) return null
299 if (doneCount >= 2 && work > 0) return Math.round(((at - list.planAt) / work) * (1 - work))
300 if (list.paceMs === null) return null
301
302 return Math.round(
303 list.tasks
304 .filter(one => one.status !== 'done')
305 .reduce((sum, one) => sum + (stepEstimate(list, one, at).leftMs ?? 0), 0),
306 )
307}
308
309/**
310 * Steps still open after Claude answered. The last step alone still open counts as done:
311 * Claude finished but forgot to report 100.
312 */
313export function hasUnfinishedWork(tasks: GlanceTask[]): boolean {
314 const open = tasks.filter(one => one.status !== 'done')
315
316 return open.length > 1 || (open.length === 1 && open[0] !== tasks[tasks.length - 1])
317}
318
319/** Header details in order of importance; the least important drop first so the title stays readable. */
320export function headerDetails(parts: string[], room: number): string {
321 const kept = parts.filter(Boolean)
322 while (kept.length > 1 && kept.map(one => ` · ${one}`).join('').length > room) {
323 kept.pop()
324 }
325
326 return kept.map(one => ` · ${one}`).join('')
327}
328
329/**
330 * The pieces of a line that fit in `room` characters, joined by " · ": whole pieces, in order, leaving out any that
331 * don't fit, so no word is ever cut in half. When none fits, the first keeps the whole words it has room for.
332 */
333export function wholePieces(pieces: string[], room: number): string {
334 const all = pieces.filter(Boolean)
335 const kept: string[] = []
336 let used = 0
337 for (const piece of all) {
338 const size = widthOf(piece) + (kept.length > 0 ? 3 : 0)
339 if (used + size <= room) {
340 kept.push(piece)
341 used += size
342 }
343 }
344 if (kept.length > 0 || all.length === 0) return kept.join(' · ')
345 let cut = ''
346 for (const word of (all[0] ?? '').split(' ')) {
347 const next = cut === '' ? word : `${cut} ${word}`
348 if (widthOf(`${next}…`) > room) break
349 cut = next
350 }
351 return cut === '' ? '' : `${cut.replace(/[\s·,;:]+$/, '')}…`
352}
353
354/** A model id as people say it: claude-haiku-4-5-20251001 → Haiku 4.5. */
355export function prettyModel(model: string | null | undefined): string | null {
356 if (!model) return null
357 const match = /(opus|sonnet|haiku|fable)(?:[-_ ](\d+)(?:[-.](\d{1,2})(?!\d))?)?/i.exec(model)
358 if (!match) return model
359 const name = match[1]!.charAt(0).toUpperCase() + match[1]!.slice(1).toLowerCase()
360
361 return [name, [match[2], match[3]].filter(Boolean).join('.')].filter(Boolean).join(' ')
362}
363
364/** The step new helpers belong to: the current one, or the last one once all are done. */
365export function currentStepId(list: GlanceChecklist): string {
366 return (list.tasks.find(one => one.status === 'active') ?? list.tasks[list.tasks.length - 1])?.id ?? ''
367}
368
369/** A file's path within the project; outside it, just its name. */
370export function projectPath(path: string, project: string): string {
371 const root = project.replace(/[\\/]+$/, '')
372 if (root !== '' && (path.startsWith(`${root}/`) || path.startsWith(`${root}\\`))) return path.slice(root.length + 1)
373
374 return path.split(/[\\/]/).pop() ?? path
375}
376
377export type BackgroundTask = { id: string; type: string; status: string; description: string }
378
379/** Background tasks as the latest list has them: new ones join, ones no longer listed have finished. */
380export function reconcileBackground(list: GlanceChecklist, tasks: readonly BackgroundTask[]): GlanceHelper[] {
381 const listed = new Map(tasks.map(one => [`bg:${one.id}`, one]))
382 const kept = list.helpers.map(helper => {
383 if (helper.kind !== 'background' || helper.status !== 'running') return helper
384 const still = listed.get(helper.id)
385 return still ? helper : { ...helper, status: 'done' as const }
386 })
387 const known = new Set(kept.map(one => one.id))
388 const added = tasks
389 .filter(one => !known.has(`bg:${one.id}`))
390 .map(
391 (one): GlanceHelper => ({
392 id: `bg:${one.id}`,
393 stepId: currentStepId(list),
394 kind: 'background',
395 label: cleanName(one.description, MAX_DETAIL),
396 type: one.type,
397 model: null,
398 effort: null,
399 status: 'running',
400 tokens: 0,
401 }),
402 )
403
404 return [...kept, ...added]
405}
406
407/** What a tool call is doing, in plain words; null for planning tools and helpers, which show elsewhere. */
408export function activityOf(tool: string, input: { command?: unknown }): string | null {
409 if (tool === 'Read' || tool === 'NotebookRead') return 'Reading files'
410 if (tool === 'Grep' || tool === 'Glob' || tool === 'LS') return 'Searching the project'
411 if (tool === 'Edit' || tool === 'MultiEdit' || tool === 'NotebookEdit') return 'Editing files'
412 if (tool === 'Write') return 'Writing files'
413 if (tool === 'WebFetch') return 'Reading a web page'
414 if (tool === 'WebSearch') return 'Searching the web'
415 if (tool === 'Skill') return 'Following a skill'
416 if (tool.startsWith('mcp__') && !tool.startsWith(`mcp__${PLUGIN}__`) && tool !== NATIVE_PLAN && tool !== NATIVE_WRAP_UP) return 'Using a connected app'
417 if (tool === 'Bash' || tool === 'PowerShell') {
418 const command = String(input.command ?? '')
419 if (/\b(test|tests|jest|vitest|pytest|mocha|playwright|rspec)\b/i.test(command)) return 'Running the tests'
420 if (/\b(npm|pnpm|yarn|bun|pip3?|brew|cargo|gem)\s+(install|add|i)\b/i.test(command)) return 'Installing packages'
421 if (/\bgit\s+\w+/.test(command)) return 'Working with git'
422 if (/\b(build|tsc|compile)\b/i.test(command)) return 'Building the project'
423 return 'Running a command'
424 }
425 return null
426}
427
428// What each activity asks to do, as the words after "OK to"; with a file or site, its name follows.
429const ASKS: Record<string, () => string> = {
430 'Reading files': () => tr('read'),
431 'Searching the project': () => tr('search the project'),
432 'Editing files': () => tr('edit'),
433 'Writing files': () => tr('write'),
434 'Reading a web page': () => tr('read a page on'),
435 'Searching the web': () => tr('search the web'),
436 'Using a connected app': () => tr('use a connected app'),
437 'Running the tests': () => tr('run the tests'),
438 'Installing packages': () => tr('install packages'),
439 'Working with git': () => tr('run a git command'),
440 'Building the project': () => tr('build the project'),
441 'Running a command': () => tr('run a command'),
442}
443
444// What a command does that a person should know before saying yes.
445// shortcut: reads the command's first line as text, as the activity keeps it; add a spelling here when a risky one shows up.
446const RISKS: readonly (readonly [RegExp, () => string])[] = [
447 [/\brm\s+-\w*[rf]|\brmdir\b|\bRemove-Item\b|\bgit\s+clean\b/i, () => tr('deletes files')],
448 [/\bgit\s+(?:reset\s+--hard|push\s+(?:-f\b|--force)|rebase\b)/i, () => tr('rewrites git history')],
449 [/\b(?:npm|pnpm|yarn)\s+publish\b|\btwine\s+upload\b|\bgh\s+release\s+create\b/i, () => tr('publishes a package')],
450 [/\bgit\s+push\b|\bgh\s+pr\s+merge\b/i, () => tr('uploads your changes')],
451 [/\bdeploy\b|\bvercel\b.*--prod/i, () => tr('deploys online')],
452 [/\b(?:npm|pnpm|yarn|bun|pip3?|brew|cargo|gem)\s+(?:install|add|i)\b/i, () => tr('installs packages')],
453 [/\bsudo\b/, () => tr('uses admin rights')],
454 [/\b(?:curl|wget)\b[^|]*\|\s*(?:sudo\s+)?(?:ba|z)?sh\b/i, () => tr('runs code from the internet')],
455]
456
457/**
458 * What a permission request asks, in plain words: Claude's own description of the call, else what it does and to
459 * what, then anything risky the command does. Null when nothing is known about the call.
460 */
461export function permissionWords(activity: GlanceChecklist['activity']): string | null {
462 if (activity === null) return null
463 const asks = ASKS[activity.label]?.()
464 const isCommand = activity.label.startsWith('Running') || activity.label === 'Installing packages' || activity.label === 'Working with git' || activity.label === 'Building the project'
465 const said = activity.detail?.replace(/[.!]+$/, '') ?? ''
466 // English reads Claude's description after "OK to", in lower case; Greek keeps it as said, as a name.
467 const what = activity.detail
468 ? currentLang() === 'en'
469 ? `${said.charAt(0).toLowerCase()}${said.slice(1)}`
470 : said
471 : asks === undefined
472 ? null
473 : !isCommand && activity.target
474 ? `${asks} ${activity.target}`
475 : asks
476 if (what === null) return null
477 const risks = isCommand && activity.target ? RISKS.filter(([pattern]) => pattern.test(activity.target!)).map(([, words]) => words()) : []
478 const and = risks.length > 1 ? tr('{0} and {1}', risks.slice(0, -1).join(', '), risks[risks.length - 1]!) : (risks[0] ?? '')
479
480 if (activity.detail) return and ? tr('OK to {0}? It {1}.#detail', what, and) : tr('OK to {0}?#detail', what)
481 return and ? tr('OK to {0}? It {1}.', what, and) : tr('OK to {0}?', what)
482}
483
484// A piece that starts with a test, build, type check or lint command, after any VAR=x assignments. Stricter than
485// activityOf's words: git commit -m "fix test", cat tests/x.ts and npm install jest run no check.
486// shortcut: reads the command as text; a check run through a script, an alias or a wrapper like sh -c is not seen,
487// add its spelling here when one shows up.
488const CHECK_COMMAND = new RegExp(
489 '^\\s*(?:\\w+=\\S*\\s+)*(?:' +
490 [
491 '(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?(?:test|build|check|typecheck|type-check|lint|verify)',
492 '(?:npx|bunx|pnpm\\s+exec|pnpm\\s+dlx)\\s+(?:jest|vitest|mocha|playwright\\s+test|tsc|eslint)',
493 '(?:jest|vitest|mocha|pytest|rspec|phpunit|tsc)',
494 'python3?\\s+-m\\s+(?:pytest|unittest|mypy)',
495 'go\\s+(?:test|build|vet)',
496 'cargo\\s+(?:test|build|check|clippy)',
497 'make\\s+(?:test|check|build)',
498 '(?:\\.\\/gradlew|gradle)\\s+(?:test|build|check)',
499 'mvn\\s+(?:test|verify|package)',
500 '(?:dotnet|swift)\\s+(?:test|build)',
501 'deno\\s+(?:test|check)',
502 'bundle\\s+exec\\s+rspec',
503 'claude\\s+plugin\\s+(?:test|validate)',
504 ].join('|') +
505 ')(?![\\w-])',
506)
507
508/** Whether a shell command runs the project's tests, build, type check or lint: the outside judge for a step's code. */
509export const runsCheck = (command: string) => commandPieces(command).some(piece => CHECK_COMMAND.test(piece))
510
511// Failure counts, a FAIL line, TypeScript errors or a failed build in the output. `npm test 2>&1 | tail` and `|| true`
512// report the last command's exit code, not the tests', so the output is read too.
513// shortcut: heuristic text matching; a runner that prints failures another way passes, add its wording when seen.
514const CHECK_FAILED = /\b[1-9]\d*\s+(?:fail|failed|failing|failures?|errors?)\b|^\s*FAIL\b|\berror TS\d+|\bBUILD FAILED\b/im
515
516/** What a check command's run says about the code: failed when it errored or its output reports failures. */
517export const checkResult = (isError: boolean, output: string): GlanceCheck =>
518 isError || CHECK_FAILED.test(output) ? 'failed' : 'passed'
519
520/** Whether writing a file changes code a check should cover; prose does not. */
521export const needsCheck = (path: string) => !/\.(?:md|mdx|txt|rst)$/i.test(path)
522
523/** A check's result on each step that changed code; a step that passed keeps it when a later check fails. */
524export const applyCheck = (tasks: GlanceTask[], result: GlanceCheck): GlanceTask[] =>
525 tasks.map(one => (one.check === undefined || (one.check === 'passed' && result === 'failed') ? one : { ...one, check: result }))
526
527/** Whether version `latest` (like 0.27.0) comes after `current`; a part that isn't a number counts as 0. */
528export function isNewerVersion(latest: string, current: string): boolean {
529 const a = latest.split('.').map(part => Number.parseInt(part, 10) || 0)
530 const b = current.split('.').map(part => Number.parseInt(part, 10) || 0)
531 for (let at = 0; at < Math.max(a.length, b.length); at++) {
532 if ((a[at] ?? 0) !== (b[at] ?? 0)) return (a[at] ?? 0) > (b[at] ?? 0)
533 }
534 return false
535}
536
537/** A job's cost in plain dollars: "$0.42", or "<$0.01" for less than a cent. */
538export function formatCost(usd: number): string {
539 return usd < 0.01 ? '<$0.01' : `$${usd.toFixed(2)}`
540}
541
542/** What the job has cost so far, from the session's spend; null where the host keeps no ledger. */
543export function jobCost(list: GlanceChecklist, usage: GlanceUsage): number | null {
544 return usage.costUsd === null || list.costAtStart === null ? null : Math.max(0, usage.costUsd - list.costAtStart)
545}
546
547export function isBusy(list: GlanceChecklist): boolean {
548 return list.helpers.some(one => one.status === 'running')
549}
550
551/** A short "carry on" the person typed, in English or Greek: it continues the job instead of starting a new one. */
552export function isContinueWords(text: string): boolean {
553 const words = text.trim().toLowerCase().replace(/[.!…,;:]+$/g, '').replace(/\s+/g, ' ')
554 return (
555 /^(please )?(continue|go on|keep going|resume|carry on|proceed|go ahead)( please)?$/.test(words) ||
556 /^(σε παρακαλώ |παρακαλώ )?(συνέχισε|συνεχισε|συνέχεια|συνεχεια|προχώρα|προχωρα)( σε παρακαλώ| παρακαλώ| παρακαλω)?$/.test(words)
557 )
558}
559
560/** A short "go ahead" the person typed: it approves the plan. */
561export function isStartWords(text: string): boolean {
562 const words = text.trim().toLowerCase().replace(/[.!…,;:]+$/g, '').replace(/\s+/g, ' ')
563 return /^(start|go|go ahead|ok|okay|yes|looks good|approved?|ξεκίνα|ξεκινα|ναι|οκ|εντάξει|ενταξει)( please)?$/.test(words)
564}
565
566/**
567 * Claude's last message ends by asking the person something. Greek writes its question mark as ";", so a ";" counts
568 * in Greek text and nowhere else; a code block never does.
569 */
570export function asksQuestion(answer: string): boolean {
571 const end = answer.trimEnd().replace(/[*_"'”»)\s]+$/g, '')
572 return /[??؟]$/.test(end) || (end.endsWith(';') && /\p{Script=Greek}/u.test(end))
573}
574
575/** The full head SHA Ship it last asked the person to approve ("Reply exactly: Approve merge <SHA>"), or null. */
576export function askedMergeSha(answer: string): string | null {
577 return [...answer.matchAll(/Reply exactly:\s*`?Approve merge ([0-9a-f]{40})`?/g)].pop()?.[1] ?? null
578}
579
580/**
581 * A word as Bash passes it on, and whether Bash builds it at run time: from $…, `…`, a glob, {a,b}, ~ or =. `runs`
582 * holds the code of an unquoted $(…) or `…` in it, which Bash runs first.
583 */
584export type ShellWord = { text: string; isRunTime: boolean; runs?: string[] }
585/** The words of one command, or of one line of a heredoc's body. */
586export type ShellPiece = { words: ShellWord[]; isBody: boolean }
587
588// $'…' escapes every shell spells alike; \u, \U and \c differ between Bash 3.2, newer Bash and zsh.
589const ANSI_C: Record<string, string> = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' }
590// A heredoc's start, <<EOF, <<-EOF, <<'EOF' or <<"EOF"; a delimiter spelled any other way leaves its lines as commands.
591const HEREDOC = /^<<(-?)[ \t]*(['"]?)([^\s'"<>;|&()]+)\2(?=[\s;|&<>()]|$)/
592
593/**
594 * Reads a Bash command into pieces of words the way Bash spells them before it runs anything: \ and a newline go,
595 * \c is c, '…', "…" (with \" \\ \$ \` and \ newline) and $'…' join their neighbours into one word, # starts a
596 * comment, a heredoc's lines are its body, ; | & and newlines end a piece, and ( ) < > stand as words of their own.
597 * shortcut: a bounded lexer, not a parser; it never runs or expands anything. A word built at run time keeps its text
598 * as written and is marked, and $(…) is read to its matching ) past quotes and heredocs only.
599 */
600export function shellPieces(command: string): ShellPiece[] {
601 const pieces: ShellPiece[] = []
602 const heredocs: { delimiter: string; isTabbed: boolean }[] = []
603 let words: ShellWord[] = []
604 let word: ShellWord | null = null
605 // The word's unquoted characters, where globs and brace lists count.
606 let bare = ''
607 const add = (text: string, isQuoted = false): ShellWord => {
608 // ~ and zsh's = expand only at the start of a word, unquoted.
609 word ??= { text: '', isRunTime: !isQuoted && /^[~=]/.test(text) }
610 word.text += text
611 if (!isQuoted) bare += text
612 return word
613 }
614 const runTime = (text: string, runs?: string) => {
615 const one = add(text, true)
616 one.isRunTime = true
617 if (runs !== undefined) (one.runs ??= []).push(runs)
618 }
619 const endWord = () => {
620 if (word !== null) {
621 if (/[*?]|\[[^\]]+\]|\{.*(?:,|\.\.).*\}/.test(bare)) word.isRunTime = true
622 words.push(word)
623 }
624 word = null
625 bare = ''
626 }
627 const endPiece = () => {
628 endWord()
629 pieces.push({ words, isBody: false })
630 words = []
631 }
632 // The index of the next unescaped quote, or the end.
633 const end = (from: number, quote: string): number => {
634 for (let at = from; at < command.length; at++) {
635 if (command[at] === '\\' && quote !== "'") at++
636 else if (command[at] === quote) return at
637 }
638 return command.length
639 }
640 // A heredoc's body lines from `from`, and the index of the newline that ends its delimiter line.
641 const body = (from: number, delimiter: string, isTabbed: boolean) => {
642 const lines: string[] = []
643 for (let at = from; at < command.length; ) {
644 const stop = command.indexOf('\n', at) < 0 ? command.length : command.indexOf('\n', at)
645 const line = command.slice(at, stop)
646 if ((isTabbed ? line.replace(/^\t+/, '') : line) === delimiter) return { lines, next: stop }
647 lines.push(line)
648 at = stop + 1
649 }
650 return { lines, next: command.length }
651 }
652 // The index of the ) of $( or the } of ${, past quotes and heredocs.
653 const closing = (from: number, open: string, close: string): number => {
654 let depth = 0
655 for (let at = from; at < command.length; at++) {
656 const char = command[at]
657 const heredoc = char === '<' ? HEREDOC.exec(command.slice(at)) : null
658 if (char === '\\') at++
659 else if (char === "'" || char === '"' || char === '`') at = end(at + 1, char)
660 else if (heredoc && command.indexOf('\n', at) >= 0) at = body(command.indexOf('\n', at) + 1, heredoc[3], heredoc[1] === '-').next
661 else if (char === open) depth++
662 else if (char === close && --depth === 0) return at
663 }
664 return command.length
665 }
666 // $'…', decoded; returns the index of its closing quote.
667 const ansiC = (from: number): number => {
668 let text = ''
669 let isShellSpecific = false
670 let at = from
671 for (; at < command.length && command[at] !== "'"; at++) {
672 if (command[at] !== '\\') {
673 text += command[at]
674 continue
675 }
676 const code = command[++at] ?? ''
677 const hex = code === 'x' ? /^[0-9A-Fa-f]{1,2}/.exec(command.slice(at + 1)) : null
678 const octal = /^[0-7]{1,3}/.exec(command.slice(at))
679 if (Object.hasOwn(ANSI_C, code)) text += ANSI_C[code]
680 else if (hex) {
681 text += String.fromCharCode(parseInt(hex[0], 16))
682 at += hex[0].length
683 } else if (octal) {
684 text += String.fromCharCode(parseInt(octal[0], 8))
685 at += octal[0].length - 1
686 } else {
687 isShellSpecific ||= code !== '' && 'uUc'.includes(code)
688 text += `\\${code}`
689 }
690 }
691 add(text, true).isRunTime ||= isShellSpecific
692 return at
693 }
694 // $… or `…`: a word built at run time, kept as written; returns the index of its last character.
695 const dollar = (at: number, isQuoted: boolean): number => {
696 const next = command[at + 1] ?? ''
697 if (command[at] === '`') {
698 const stop = end(at + 1, '`')
699 runTime(command.slice(at, stop + 1), isQuoted ? undefined : command.slice(at + 1, stop))
700 return stop
701 }
702 if (next === "'" && !isQuoted) return ansiC(at + 2)
703 // $"…" is translated at run time; the "…" itself is read next.
704 if (next === '"' && !isQuoted) {
705 runTime('')
706 return at
707 }
708 if (next === '(' || next === '{') {
709 const stop = closing(at + 1, next, next === '(' ? ')' : '}')
710 // shortcut: the code of "$(…)" in double quotes, like a commit message from a heredoc, is not read.
711 const isCode = next === '(' && command[at + 2] !== '(' && !isQuoted
712 runTime(command.slice(at, stop + 1), isCode ? command.slice(at + 2, stop) : undefined)
713 return stop
714 }
715 const name = /^(?:[A-Za-z_]\w*|[0-9@*#?$!-])/.exec(command.slice(at + 1))
716 if (name === null) {
717 add('$', isQuoted)
718 return at
719 }
720 runTime(`$${name[0]}`)
721 return at + name[0].length
722 }
723 // "…", unescaped; returns the index of its closing quote.
724 const doubleQuoted = (from: number): number => {
725 add('', true)
726 for (let at = from; at < command.length; at++) {
727 const char = command[at]
728 const next = command[at + 1]
729 if (char === '"') return at
730 if (char === '\\' && next !== undefined && '"\\$`\n'.includes(next)) {
731 at++
732 if (next !== '\n') add(next, true)
733 } else if (char === '$' || char === '`') at = dollar(at, true)
734 else add(char, true)
735 }
736 return command.length
737 }
738
739 for (let at = 0; at < command.length; at++) {
740 const char = command[at]
741 const next = command[at + 1]
742 if (char === '\\') {
743 at++
744 if (next !== '\n') add(next ?? '\\', true)
745 } else if (char === "'") {
746 const stop = end(at + 1, "'")
747 add(command.slice(at + 1, stop), true)
748 at = stop
749 } else if (char === '"') at = doubleQuoted(at + 1)
750 else if (char === '$' || char === '`') at = dollar(at, false)
751 else if (char === '#' && word === null) {
752 // A comment runs to the end of its line.
753 const stop = command.indexOf('\n', at)
754 at = (stop < 0 ? command.length : stop) - 1
755 } else if (char === ' ' || char === '\t') endWord()
756 else if (';|&\n'.includes(char)) {
757 endPiece()
758 if ((char === '|' || char === '&') && next === char) at++
759 // After the line that starts them, heredocs' bodies, in order.
760 for (const { delimiter, isTabbed } of char === '\n' ? heredocs.splice(0) : []) {
761 const { lines, next: stop } = body(at + 1, delimiter, isTabbed)
762 for (const line of lines) pieces.push(...shellPieces(line).map(piece => ({ ...piece, isBody: true })))
763 at = stop
764 }
765 } else if ('()<>'.includes(char)) {
766 endWord()
767 const heredoc = char === '<' ? HEREDOC.exec(command.slice(at)) : null
768 const operator = command.startsWith('<<<', at) ? '<<<' : heredoc ? `<<${heredoc[1]}` : command.startsWith('>>', at) ? '>>' : char
769 if (heredoc && operator !== '<<<') heredocs.push({ delimiter: heredoc[3], isTabbed: heredoc[1] === '-' })
770 words.push({ text: operator, isRunTime: false })
771 at += operator.length - 1
772 } else add(char)
773 }
774 endPiece()
775 return pieces
776}
777
778/** Splits a shell command at ;, |, ||, &, && and newlines that stand outside single and double quotes. */
779function commandPieces(command: string): string[] {
780 const pieces: string[] = []
781 let piece = ''
782 let quote: string | null = null
783 for (let at = 0; at < command.length; at++) {
784 const char = command[at]
785 if (quote === null && ';|&\n'.includes(char)) {
786 pieces.push(piece)
787 piece = ''
788 if ((char === '|' || char === '&') && command[at + 1] === char) at++
789 continue
790 }
791 if (char === '\\' && quote !== "'") {
792 piece += char + (command[++at] ?? '')
793 continue
794 }
795 if (quote === null && (char === '"' || char === "'")) quote = char
796 else if (char === quote) quote = null
797 piece += char
798 }
799 return [...pieces, piece]
800}
801
802// The pieces of a command that run gh: pieces at the top level, and pieces of the quoted command string of
803// bash -c, sh -c or zsh -c. Text inside other quotes, like a commit message, is never a piece of its own.
804// shortcut: reads the command as text; the word checks below see quoted and escaped spellings, and a heredoc line
805// that starts with gh pr merge counts as a merge (refused, never allowed by mistake).
806const WRAPPED = /^\s*(?:ba|z)?sh\s+-c\s+(["'])([\s\S]*)\1\s*$/
807const ghPieces = (command: string): string[] =>
808 commandPieces(command).flatMap(piece => {
809 const wrapped = WRAPPED.exec(piece)
810 return wrapped ? ghPieces(wrapped[2]) : [piece]
811 })
812const PR_MERGE = /^\s*gh\s+pr\s+merge\b/
813// gh api, curl and wget routes that merge or schedule a merge: REST pull and branch merges, GraphQL merge, auto-merge and merge queue.
814const MERGE_ROUTE =
815 /pulls\/[^/\s]+\/merge\b|repos\/[^/\s]+\/[^/\s]+\/merges\b|mergePullRequest|enablePullRequestAutoMerge|enqueuePullRequest|mergeBranch/
816
817// A merge run through a wrapper instead of on its own: (…), { …; }, !, env, command, sudo, exec, time, xargs, VAR=x,
818// a path to gh, or eval and sh -c after any of those. Fails closed: gh pr merge outside quotes anywhere in the piece
819// counts, and so does the quoted text that eval or sh -c runs. Text inside other quotes, like a commit message, does not.
820const QUOTED = /"(?:\\[\s\S]|[^"\\])*"|'[^']*'/g
821const RUNS_QUOTED = /(?:^|[^\w-])(?:(?:ba|z)?sh\s+-\w*c|eval)\b/
822const GH_MERGE = /(?:^|[^\w-])gh\s+pr\s+merge\b/
823const GH_API = /(?:^|[^\w-])gh\s+api\b/
824// The text of a piece that runs: what stands outside quotes, or all of it when eval or sh -c runs its quoted text.
825const runText = (piece: string) => {
826 const outside = piece.replace(QUOTED, '""')
827 return RUNS_QUOTED.test(outside) ? piece : outside
828}
829const wrappedMerge = (piece: string) => GH_MERGE.test(runText(piece))
830// gh api run in any piece, bare or wrapped; text that only mentions it, like echo "gh api", does not run it.
831const runsGhApi = (command: string) => ghPieces(command).some(piece => GH_API.test(runText(piece)))
832
833// curl or wget where a command starts: at the start of a piece, after $( or `, after if, then, else, elif, do, while,
834// until or the wrappers above, all outside quotes; the quoted text that eval or sh -c runs is read the same way. Text
835// that only mentions them, like echo curl or grep wget, does not run them.
836// shortcut: reads the command as text; curl or wget reached through a variable, an alias, a script, an interpreter, "$(…)"
837// in double quotes or another wrapper is not detected, and a heredoc line that starts with curl or wget counts as running it.
838const HTTP_CLIENT =
839 /(?:^|\$\(|`)(?:\s|[({!]|\w+=\S*\s|(?:env|command|sudo|exec|eval|time|xargs|if|then|else|elif|do|while|until)(?:\s+-\S+(?:\s+[^-\s]\S*)?)*\s)*(?:\S*\/)?\\?(?:curl|wget)(?![\w.-])/
840const runsHttpClient = (command: string): boolean =>
841 commandPieces(command.replace(/\\\r?\n/g, ' ')).some(piece => {
842 const outside = piece.replace(QUOTED, '""')
843 if (HTTP_CLIENT.test(outside)) return true
844 return RUNS_QUOTED.test(outside) && [...piece.matchAll(QUOTED)].some(([quoted]) => runsHttpClient(quoted.slice(1, -1)))
845 })
846
847/** Whether a shell command runs `gh pr merge`, as the Ship it guard reads it; text that only mentions it does not. */
848export const runsPrMerge = (command: string) =>
849 ghPieces(command).some(piece => PR_MERGE.test(piece)) || wordFindings(command, command).some(found => 'merge' in found)
850
851// MCP actions that merge a pull request, turn on auto-merge or add it to a merge queue, lowercased without _ and -.
852// shortcut: an exact closed list, so a merge tool by another name passes; add names seen in a supported server.
853const MCP_MERGE_ACTIONS = new Set(['mergepullrequest', 'enableautomerge', 'enablepullrequestautomerge', 'enqueuepullrequest'])
854
855/** Whether a tool is an MCP action that merges a pull request or schedules its merge; the server's name is never read. */
856export function isMcpMergeAction(tool: string): boolean {
857 const at = tool.lastIndexOf('__')
858 // The action follows the last __; a name with no __ after mcp__ has no action, only a server.
859 return tool.startsWith('mcp__') && at > 3 && MCP_MERGE_ACTIONS.has(tool.slice(at + 2).toLowerCase().replace(/[_-]/g, ''))
860}
861
862const APPROVED_ONLY =
863 'Ship it merges only the head commit the person approved. End your turn by showing the pull request link, the ' +
864 'checks and the full head SHA, then "Reply exactly: Approve merge <full SHA>", and wait for exactly that reply. ' +
865 'Then run gh pr merge --squash --delete-branch --match-head-commit <that full SHA>.'
866
867// The Ship it guard's refusals, shared by the text checks and the word checks.
868const NEVER_ADMIN = 'Ship it never merges with --admin or --auto. Leave the pull request open and tell the person why it cannot merge.'
869const DIRECT_ONLY =
870 'Ship it merges only with gh pr merge run directly, never through (…), !, env, command, sudo, exec, eval, ' +
871 'a path or another wrapper. Run gh pr merge --squash --delete-branch --match-head-commit <approved SHA> on its own.'
872const ON_ITS_OWN = 'Run the approved gh pr merge on its own, with nothing before or after it, so its exit code shows whether it merged.'
873const NO_HTTP = 'Ship it merges only with gh pr merge --match-head-commit, never through curl or wget. Leave the pull request open.'
874const NO_API = 'Ship it merges only with gh pr merge --match-head-commit, never through gh api. Leave the pull request open.'
875const RUN_TIME =
876 'While Ship it runs, a command and the first words of gh are never built at run time ($…, `…`, a glob, {a,b}, ~ or =). ' +
877 'Spell them out.'
878const PR_FLAG_FIRST =
879 'While Ship it runs, gh pr takes its subcommand right after pr, never after a flag, which could hide a merge. ' +
880 'Put -R or --repo before pr and other flags after the subcommand.'
881const GH_ALIAS = 'While Ship it runs, gh runs only its own commands, never an alias or extension, which could hide a merge. Spell the gh command out.'
882const MERGE_WORDS =
883 'Ship it merges only with gh pr merge, its own flags and at most one pull request. ' +
884 'Run gh pr merge --squash --delete-branch --match-head-commit <approved SHA> on its own.'
885
886// gh's own top-level commands, their built-in aliases and its help topics (gh 2.100, `gh help`). Any other first word
887// is an alias or extension, which could run a merge the guard cannot read; so is gh extension exec.
888// shortcut: a fixed list; a gh command added later is refused during Ship it until it is listed here.
889const GH_COMMANDS = new Set(
890 (
891 'agent-task agent-tasks agent agents alias api attestation at auth browse cache codespace cs completion config copilot ' +
892 'discussion extension extensions ext gist gpg-key help issue label licenses org pr preview project release repo ruleset ' +
893 'rs run search secret skill skills ssh-key status variable version workflow ' +
894 'accessibility actions environment exit-codes formatting mintty reference telemetry'
895 ).split(' '),
896)
897const GH_EXTENSION = new Set(['extension', 'extensions', 'ext'])
898// gh pr merge's own flags (gh 2.100), with the inherited --repo and --help, and whether each takes a value.
899const MERGE_FLAGS = new Map(
900 Object.entries({
901 admin: false, auto: false, 'author-email': true, body: true, 'body-file': true, 'delete-branch': false, 'disable-auto': false,
902 help: false, 'match-head-commit': true, merge: false, rebase: false, repo: true, squash: false, subject: true,
903 }),
904)
905const MERGE_SHORT = new Map(Object.entries({ A: 'author-email', b: 'body', F: 'body-file', d: 'delete-branch', m: 'merge', r: 'rebase', R: 'repo', s: 'squash', t: 'subject' }))
906
907// Words before a command: ( { ! and keywords (P), VAR=x (A), wrappers that run the words after them (W), their
908// options (O) and anything else (X). A command stands first, after P and A, or anywhere after a wrapper.
909const PREFIXES = new Set(['(', '{', '!', 'if', 'then', 'else', 'elif', 'do', 'while', 'until'])
910const WRAPPERS = new Set(['env', 'command', 'builtin', 'sudo', 'doas', 'exec', 'time', 'xargs', 'nohup', 'nice', 'timeout', 'watch'])
911const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh'])
912const AT_COMMAND = /^(?:[PA]|W[WOX]*)*$/
913const baseName = (text: string) => text.slice(text.lastIndexOf('/') + 1)
914const wordClass = ({ text, isRunTime }: ShellWord) =>
915 /^[A-Za-z_]\w*=/.test(text) ? 'A' : isRunTime ? 'X' : PREFIXES.has(text) ? 'P' : WRAPPERS.has(baseName(text)) ? 'W' : text.startsWith('-') ? 'O' : 'X'
916
917// The first two words gh reads as its command, past -R / --repo and other flags before the first; null when one is
918// built at run time. After pr the next word is kept as written, a flag too: its value count is never guessed.
919function ghCommand(args: ShellWord[]): string[] | null {
920 const found: string[] = []
921 let isPastFlags = false
922 for (let at = 0; at < args.length && found.length < 2; at++) {
923 const { text, isRunTime } = args[at]
924 if (isRunTime) return null
925 if (isPastFlags || !text.startsWith('-') || text === '-' || found[0] === 'pr') found.push(text)
926 else if (text === '--') isPastFlags = true
927 else if (text === '-R' || text === '--repo') at++
928 }
929 return found
930}
931
932type WordFinding = { refusal: string } | { merge: ShellWord[]; isAlone: boolean }
933
934/**
935 * What a command runs, read as the words Bash passes on: gh merges, gh api and curl or wget merge routes, gh aliases
936 * and extensions, and command words built at run time, in the command itself and in the code bash -c or eval runs.
937 * A gh merge is direct only as the first word of the command, or of a plain bash -c "…"; anywhere else it is wrapped.
938 * Merge routes are looked for in the whole command as written, the way the text checks look for them.
939 */
940function wordFindings(code: string, command: string, isWrapped = false, isAlone = true, found: WordFinding[] = []): WordFinding[] {
941 // Blank space around the command runs nothing; a \ and newline at its end is a continued line, kept.
942 const pieces = shellPieces(code.replace(/^\s+|(?<!\\)\s+$/g, ''))
943 const alone = isAlone && pieces.length === 1
944 for (const { words, isBody } of pieces) {
945 const classes = words.map(wordClass).join('')
946 // A heredoc's line may start with anything; only the commands it names count.
947 if (words[classes.search(/[^PA]/)]?.isRunTime && !isBody) found.push({ refusal: RUN_TIME })
948 words.forEach((word, at) => {
949 for (const code of word.runs ?? []) wordFindings(code, command, true, false, found)
950 const name = baseName(word.text)
951 const rest = words.slice(at + 1)
952 const isCommand = AT_COMMAND.test(classes.slice(0, at))
953 if (word.isRunTime) return
954 if (name === 'gh') {
955 const gh = ghCommand(rest)
956 if (gh === null) {
957 if (isCommand) found.push({ refusal: RUN_TIME })
958 } else if (gh[0] === 'pr' && gh[1] === 'merge') {
959 // Fails closed: gh pr merge anywhere else in a piece, even after echo, is read as a wrapped merge.
960 found.push(!isWrapped && !isBody && at === 0 && word.text === 'gh' ? { merge: rest, isAlone: alone } : { refusal: DIRECT_ONLY })
961 } else if (gh[0] === 'pr' && gh[1]?.startsWith('-')) {
962 // Fails closed like a merge: a flag's value could stand where gh reads its subcommand.
963 found.push({ refusal: PR_FLAG_FIRST })
964 } else if (gh[0] === 'api' && MERGE_ROUTE.test(command)) found.push({ refusal: NO_API })
965 else if (isCommand && gh.length > 0 && (!GH_COMMANDS.has(gh[0]) || (GH_EXTENSION.has(gh[0]) && gh[1] === 'exec'))) {
966 found.push({ refusal: GH_ALIAS })
967 }
968 } else if (!isCommand) {
969 return
970 } else if (WRAPPERS.has(name)) {
971 // The command a wrapper runs: its first word that is not an option or VAR=x.
972 if (rest.find(one => !/[OA]/.test(wordClass(one)))?.isRunTime && !isBody) found.push({ refusal: RUN_TIME })
973 } else if (SHELLS.has(name)) {
974 const isPlain = !isWrapped && !isBody && at === 0 && word.text === name && words.length === 3 && rest[0].text === '-c'
975 const flag = rest.findIndex(one => /^-\w*c/.test(one.text))
976 if (isPlain) wordFindings(rest[1].text, command, false, alone, found)
977 else if (flag >= 0) for (const one of rest.slice(flag + 1)) wordFindings(one.text, command, true, false, found)
978 } else if (name === 'eval') {
979 wordFindings(rest.map(one => one.text).join(' '), command, true, false, found)
980 } else if ((name === 'curl' || name === 'wget') && MERGE_ROUTE.test(command)) {
981 found.push({ refusal: NO_HTTP })
982 }
983 })
984 }
985 return found
986}
987
988/**
989 * Why a direct gh pr merge may not run, read the way gh's flag parser reads its words, or null when it is the
990 * approved merge: no word built at run time, no --admin or --auto in any word, only gh pr merge's own flags and at most
991 * one pull request, every --match-head-commit (gh keeps the last) the approved head commit, and nothing else run.
992 */
993function mergeRefusal(args: ShellWord[], approvedSha: string | null, isAlone: boolean): string | null {
994 if (args.some(word => word.isRunTime)) return RUN_TIME
995 if (args.some(word => /^--(admin|auto)(=|$)/.test(word.text))) return NEVER_ADMIN
996 const positionals: string[] = []
997 const shas: string[] = []
998 for (let at = 0; at < args.length; at++) {
999 const text = args[at].text
1000 if (text === '--') {
1001 positionals.push(...args.slice(at + 1).map(word => word.text))
1002 break
1003 }
1004 if (!text.startsWith('-') || text === '-') {
1005 positionals.push(text)
1006 continue
1007 }
1008 let flag: string | undefined
1009 let value: string | undefined
1010 if (text.startsWith('--')) {
1011 const equals = text.indexOf('=')
1012 flag = text.slice(2, equals < 0 ? undefined : equals)
1013 value = equals < 0 ? undefined : text.slice(equals + 1)
1014 if (!MERGE_FLAGS.has(flag)) return MERGE_WORDS
1015 } else {
1016 // Short flags run together (-sd); one that takes a value takes the rest of the word (past a =) or the next word.
1017 for (let one = 1; one < text.length && flag === undefined; one++) {
1018 const name = MERGE_SHORT.get(text[one])
1019 const after = text.slice(one + 1)
1020 if (name === undefined) return MERGE_WORDS
1021 if (MERGE_FLAGS.get(name)) {
1022 flag = name
1023 value = after.length > 1 && after[0] === '=' ? after.slice(1) : after || undefined
1024 } else if (after[0] === '=') break
1025 }
1026 }
1027 if (flag !== undefined && MERGE_FLAGS.get(flag) && value === undefined) value = args[++at]?.text
1028 if (flag === 'match-head-commit') shas.push(value ?? '')
1029 }
1030 if (positionals[0] !== 'pr' || positionals[1] !== 'merge' || positionals.length > 3) return MERGE_WORDS
1031 if (approvedSha === null || shas.length === 0 || shas.some(sha => sha !== approvedSha)) return APPROVED_ONLY
1032 return isAlone ? null : ON_ITS_OWN
1033}
1034
1035/**
1036 * Why a shell command may not run during Ship it, or null when it may. Every `gh pr merge` it runs, wrapped in
1037 * `bash -c` or not, names only the approved head commit with --match-head-commit and never --admin or --auto, and is
1038 * the whole command, so a failed merge is never read as a success; merging through `gh api`, curl or wget is never allowed.
1039 * The command is read twice: as text, and as the words Bash rebuilds from it (see shellPieces), so a quoted or escaped
1040 * word, a continued line, -R before pr merge, a gh alias or extension, or gh words built at run time hide no merge.
1041 */
1042export function unsafeMerge(command: string, approvedSha: string | null): string | null {
1043 // The route may sit anywhere in the written command: a heredoc body, a continued line or a literal variable.
1044 if (MERGE_ROUTE.test(command) && runsHttpClient(command)) {
1045 return NO_HTTP
1046 }
1047 // Likewise for gh api, so a body it reads from stdin, like gh api graphql --input - <<EOF, is seen.
1048 // shortcut: reads the command as text; a body in a file (--input body.json) or made at run time is not seen, and any
1049 // gh api run beside a merge route in the text, like a heredoc that only writes one, is refused (never allowed by mistake).
1050 if (MERGE_ROUTE.test(command) && runsGhApi(command)) {
1051 return NO_API
1052 }
1053 for (const part of ghPieces(command)) {
1054 if (!PR_MERGE.test(part)) {
1055 if (wrappedMerge(part)) return DIRECT_ONLY
1056 continue
1057 }
1058 if (/(?<![\w-])--(admin|auto)\b/.test(part)) return NEVER_ADMIN
1059 const shas = [...part.matchAll(/(?<![\w-])--match-head-commit[=\s]+["']?([0-9a-f]{40})\b/g)].map(found => found[1])
1060 if (approvedSha === null || shas.length === 0 || shas.some(sha => sha !== approvedSha)) return APPROVED_ONLY
1061 // The tool's exit code is the merge's own only when nothing else runs: `; true`, `|| true` or `| cat` hide a failure.
1062 if (ghPieces(command.trim()).length > 1) return ON_ITS_OWN
1063 }
1064 // The same command read as the words Bash passes on.
1065 for (const found of wordFindings(command, command)) {
1066 const refusal = 'refusal' in found ? found.refusal : mergeRefusal(found.merge, approvedSha, found.isAlone)
1067 if (refusal !== null) return refusal
1068 }
1069 return null
1070}
1071
1072// PowerShell's only merge: the whole command, one line, words apart by spaces, and a PR argument with no PowerShell
1073// metacharacter (# starts a comment); none of --admin, --auto, chaining, a wrapper or a backtick fits it.
1074const PS_SANCTIONED = /^gh[ \t]+pr[ \t]+merge(?:[ \t]+[\w./:][\w./:-]*)?[ \t]+--squash[ \t]+--delete-branch[ \t]+--match-head-commit[ \t]+([0-9a-f]{40})$/
1075// Fail-closed PowerShell rule, no parser: read with backticks gone and case ignored, merge text (or a merge route) beside
1076// gh, the GitHub API or GraphQL, or an HTTP cmdlet or client is refused.
1077// Accepted false positive: during Ship it, merge in harmless argument text, like gh pr create --title "…merge…", is
1078// refused too, with no gh pr create exception. Bash keeps its own reading.
1079// shortcut: reads the command as text; a command built at run time (string joins, variables, -EncodedCommand, a script
1080// file) is not seen, and branch protection stays the backstop.
1081const PS_MERGE = new RegExp(`merge|${MERGE_ROUTE.source}`, 'i')
1082const PS_RUNNER = /(?<![\w-])(?:gh|invoke-restmethod|irm|invoke-webrequest|iwr|curl|wget)(?:\.exe)?(?![\w-])|api\.github\.com|graphql/i
1083
1084/** Whether a PowerShell command is the sanctioned Ship it merge, as the guard reads it. */
1085export const runsPowerShellMerge = (command: string) => PS_SANCTIONED.test(command.trim())
1086
1087/**
1088 * Why a PowerShell command may not run during Ship it, or null when it may: the only merge is the sanctioned
1089 * gh pr merge at the approved head commit, and any other command with a merge route is refused.
1090 */
1091export function unsafePowerShellMerge(command: string, approvedSha: string | null): string | null {
1092 const sanctioned = PS_SANCTIONED.exec(command.trim())
1093 if (sanctioned) return approvedSha !== null && sanctioned[1] === approvedSha ? null : APPROVED_ONLY
1094 const text = command.replace(/`/g, '')
1095 if (PS_MERGE.test(text) && PS_RUNNER.test(text)) {
1096 return (
1097 'In Ship it, PowerShell may merge only with gh pr merge --squash --delete-branch --match-head-commit <approved SHA> ' +
1098 'as the whole command; anything else that names a merge beside gh, the GitHub API or an HTTP client is refused, ' +
1099 'even in a title. Leave the pull request open.'
1100 )
1101 }
1102 return null
1103}
1104
1105export const MAX_QUESTION = 160
1106
1107/** The question Claude ended on, as one plain line: its last sentence, or the whole last paragraph when that sentence is a few words. */
1108export function questionOf(answer: string): string | null {
1109 if (!asksQuestion(answer)) return null
1110 const paragraph = (answer.trim().split(/\n\s*\n/).pop() ?? '').replace(/[*_`#>]+/g, '').replace(/\s+/g, ' ').trim()
1111 const last = paragraph.split(/(?<=[.!?;?؟])\s+/).pop() ?? ''
1112 const line = maskPrivate(last.length >= 12 ? last : paragraph)
1113
1114 return line === '' ? null : line.length > MAX_QUESTION ? `${line.slice(0, MAX_QUESTION - 1)}…` : line
1115}
1116
1117/** True when the text has no letters outside the Latin alphabet, so it can stand as an English title. */
1118export function isLatinText(text: string): boolean {
1119 return !/(?!\p{Script=Latin})\p{L}/u.test(text)
1120}
1121
1122/** What a tool call works on, for the Plan in Details: the command, a file's name or a site. */
1123export function activityTarget(input: { command?: unknown; file_path?: unknown; notebook_path?: unknown; url?: unknown }): string | null {
1124 if (typeof input.command === 'string' && input.command.trim()) {
1125 return maskPrivate(input.command.trim().split('\n')[0]!).slice(0, 160)
1126 }
1127 const file = typeof input.file_path === 'string' ? input.file_path : typeof input.notebook_path === 'string' ? input.notebook_path : null
1128 if (file) return file.split(/[\\/]/).pop() ?? null
1129 if (typeof input.url === 'string') {
1130 const host = /^[a-z]+:\/\/([^/]+)/i.exec(input.url)
1131 return host ? host[1]! : null
1132 }
1133 return null
1134}
1135
1136export const widthOf = (text: string) => Array.from(text).reduce((sum, char) => sum + cellsOf(char), 0)
1137
1138export const childrenOf = (children: unknown) =>
1139 (Array.isArray(children) ? children : [children]).filter(kid => kid !== null && kid !== undefined && kid !== false)
1140
1141/** A drawing of nothing but buttons: a Button, or Boxes that hold only buttons. */
1142export function isButtonsOnly(tree: unknown): boolean {
1143 if (tree === null || typeof tree !== 'object') return false
1144 const { type, children } = tree as { type?: unknown; children?: unknown }
1145 if (type === 'Button') return true
1146 if (type !== 'Box') return false
1147 const kids = childrenOf(children)
1148 return kids.length > 0 && kids.every(isButtonsOnly)
1149}
1150
1151/** The buttons in a drawing of nothing but buttons, in order, to line up in a row of their own. */
1152export const buttonsIn = (tree: unknown): unknown[] =>
1153 (tree as { type?: unknown }).type === 'Button' ? [tree] : childrenOf((tree as { children?: unknown }).children).flatMap(buttonsIn)
1154
1155/**
1156 * What other mods draw beneath, split: their lone buttons (Replay, say), which join GlanceFlow's actions, and the
1157 * rest, which stays under the band. A drawing of nothing but buttons comes up whole; inside a stack (a column) only a
1158 * button standing on its own does, so a mod's own group of buttons (the next-steps suggestions) stays with its words.
1159 */
1160export function liftButtons(tree: unknown, isWhole = true): { buttons: unknown[]; rest: unknown } {
1161 if (tree === null || typeof tree !== 'object') return { buttons: [], rest: tree }
1162 const { type, props, children } = tree as { type?: unknown; props?: { flexDirection?: unknown }; children?: unknown }
1163 if (type === 'Button' || (isWhole && isButtonsOnly(tree))) return { buttons: buttonsIn(tree), rest: null }
1164 if (type !== 'Box' || props?.flexDirection !== 'column') return { buttons: [], rest: tree }
1165 const parts = childrenOf(children).map(kid => liftButtons(kid, false))
1166 const buttons = parts.flatMap(part => part.buttons)
1167 if (buttons.length === 0) return { buttons: [], rest: tree }
1168 const kept = parts.map(part => part.rest).filter(one => one !== null && one !== undefined)
1169 return { buttons, rest: kept.length === 0 ? null : { ...(tree as object), children: kept } }
1170}
1171
1172/** The person's own words: notes an app adds around a prompt (<system-reminder>…) are not the request. */
1173export function ownWords(text: string): string {
1174 return text.replace(/<([A-Za-z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>/g, ' ').trim()
1175}
1176
1177export function formatLeft(ms: number): string {
1178 const minutes = Math.max(1, Math.round(ms / 60000))
1179
1180 return minutes < 60 ? tr('{0}m', minutes) : tr('{0}h {1}m', Math.floor(minutes / 60), minutes % 60)
1181}
1182
1183/** Keeps exactly one active step while any step is unfinished. */
1184export function settle(tasks: GlanceTask[]): GlanceTask[] {
1185 const lastActive = tasks.map(one => one.status).lastIndexOf('active')
1186 const fixed = tasks.map((one, index) =>
1187 one.status === 'active' && index !== lastActive ? { ...one, status: 'upcoming' as const } : one,
1188 )
1189 if (lastActive !== -1) {
1190 return fixed
1191 }
1192 const next = fixed.findIndex(one => one.status === 'upcoming')
1193
1194 return fixed.map((one, index) => (index === next ? { ...one, status: 'active' as const } : one))
1195}
1196
1197/** Applies a progress report: earlier steps check off, 100 moves to the next. */
1198export function applyProgress(tasks: GlanceTask[], rawName: string, rawPercent: number): GlanceTask[] {
1199 const name = cleanName(rawName)
1200 const percent = Math.min(100, Math.max(0, Math.round(Number(rawPercent) || 0)))hooks/kit.tsx 61 lines1import type { ElementTable, RenderElement, RenderSurface } from 'claude-code'
2
3import { GLYPH, TONE_TEXT, badgeSvg, dotsSvg, iconSvg, meterSvg, openRingSvg, ringSvg } from './look'
4import type { IconName, Tone } from './look'
5import { tr } from './words'
6
7/** Icon size in the band and the panels, in CSS px: a touch smaller than the desktop's 14.5px text. */
8const ICON = 15
9/** The desktop's line of text, in CSS px: marks are drawn this tall, centered, so they line up with a first line. */
10const LINE = 21
11/** The room a mark of ICON size takes, in cells: as wide as the room a line under it keeps, so the two start alike. */
12const MARK = 2
13
14/**
15 * The marks every screen draws, from one icon set (look.ts): SVG where the surface draws vectors (the desktop app,
16 * VS Code, the phone), one-cell glyphs on the terminal, so a status reads the same everywhere.
17 */
18export function kitOf(table: ElementTable, surface: RenderSurface) {
19 const { Box, Text } = table
20 // The terminal's table answers for Svg too, and draws it as an empty box: go by the surface.
21 const Svg = surface !== 'terminal' && 'Svg' in table ? table.Svg : null
22 // Every drawing says what it is: the desktop app draws nothing for an Svg whose alt is empty.
23 const draw = (source: string, alt: string, width: number, height = width): RenderElement | null =>
24 Svg ? <Svg source={source} alt={alt} width={width} height={height} /> : null
25 // A mark of ICON size sits in MARK cells, so a blank of the same cells lines a line up under it with nothing to read.
26 const placed = (drawn: RenderElement | null, size: number) =>
27 drawn !== null && size === ICON ? (
28 <Box width={MARK} flexShrink={0}>
29 {drawn}
30 </Box>
31 ) : (
32 drawn
33 )
34 const glyph = (name: IconName, tone: Tone) => (
35 <Text color={TONE_TEXT[tone]} dimColor={tone === 'quiet'}>
36 {GLYPH[name]}
37 </Text>
38 )
39
40 return {
41 isVector: Svg !== null,
42 /** A line icon. */
43 icon: (name: IconName, tone: Tone, alt: string, size = ICON) => placed(draw(iconSvg(name, tone, size, LINE), alt, size, LINE), size) ?? glyph(name, tone),
44 /** A filled disc with the icon in white: done, failed, waiting on you, stopped. */
45 badge: (name: IconName, tone: Tone, alt: string, size = ICON) =>
46 placed(draw(badgeSvg(name, tone, size, LINE), alt, size, LINE), size) ?? glyph(name, tone),
47 /** The current step: a ring filled to `percent`, or turning with `turn` while there is none. */
48 ring: (percent: number | null, turn: number, alt: string, size = ICON, tone: Tone = 'active') =>
49 placed(draw(ringSvg(tone, size, percent, turn, LINE), alt, size, LINE), size) ?? glyph('play', tone),
50 /** A step still to come. */
51 open: (alt: string, size = ICON) => placed(draw(openRingSvg(size, LINE), alt, size, LINE), size) ?? <Text dimColor>○</Text>,
52 /** A mark's room with nothing in it, so a line under a step starts where the step's name does; no drawing, so a
53 * screen reader passes over it. */
54 blank: () => (Svg ? <Box width={MARK} flexShrink={0} /> : <Text> </Text>),
55 /** A slim bar; vector surfaces only. */
56 meter: (tone: Tone, percent: number | null, sweep: number, alt: string, width = 96) => draw(meterSvg(tone, width, percent, sweep), alt, width, 6),
57 /** Where the welcome cards are; vector surfaces only. */
58 dots: (count: number, current: number) => draw(dotsSvg(count, current), tr('Card {0} of {1}', current + 1, count), count * 11 + 3, 6),
59 }
60}
61hooks/look.ts 168 lines1/**
2 * GlanceFlow's look: one icon set and one set of tones, so every screen draws the same marks.
3 *
4 * Surfaces that draw vectors (the desktop app, VS Code, the phone) get these SVG icons and meters; the terminal draws
5 * the glyph named beside each, one cell wide. Both come from the same names, so a status reads the same everywhere.
6 */
7
8export type Tone = 'ok' | 'active' | 'warn' | 'alert' | 'quiet'
9
10/**
11 * The vector tones, matched to the desktop app's own green, blue, amber and grey; an image can't read the app's
12 * theme, so each also stays visible on a light window.
13 */
14export const TONE: Record<Tone, string> = {
15 ok: '#3fa45a',
16 active: '#3194d4',
17 warn: '#d9970b',
18 alert: '#e0574b',
19 quiet: '#8e8e8e',
20}
21
22/** The same tones as the terminal names them, for text and glyphs. */
23export const TONE_TEXT: Record<Tone, string | undefined> = {
24 ok: 'green',
25 active: 'cyan',
26 warn: 'yellow',
27 alert: 'red',
28 quiet: undefined,
29}
30
31/** Each icon on a 24 × 24 grid, stroked 1.75 wide with round ends and joins: one weight and one corner for all. */
32const PATHS = {
33 check: '<path d="M6.8 12.5l3.4 3.4 7-7.4"/>',
34 done: '<circle cx="12" cy="12" r="8.5"/><path d="M8.5 12.4l2.4 2.4 4.7-5"/>',
35 alert: '<path d="M10.3 5.1a2 2 0 0 1 3.4 0l6.9 11.9a2 2 0 0 1-1.7 3H5.1a2 2 0 0 1-1.7-3z"/><path d="M12 10v3.6"/><path d="M12 16.6v.01"/>',
36 clock: '<circle cx="12" cy="12" r="8.5"/><path d="M12 7.6V12l2.9 1.9"/>',
37 stop: '<rect x="7" y="7" width="10" height="10" rx="2"/>',
38 pause: '<path d="M9 6.6v10.8M15 6.6v10.8" stroke-width="3.2"/>',
39 play: '<path d="M8.6 6.8v10.4a.8.8 0 0 0 1.2.7l8.2-5.2a.8.8 0 0 0 0-1.4L9.8 6.1a.8.8 0 0 0-1.2.7z"/>',
40 close: '<path d="M8 8l8 8M16 8l-8 8"/>',
41 plan: '<path d="M10 6.5h10M10 12h10M10 17.5h10"/><path d="M4.8 6.5h.01M4.8 12h.01M4.8 17.5h.01"/>',
42 history: '<path d="M3.8 12a8.2 8.2 0 1 0 2.4-5.8"/><path d="M3.6 4.3v4.1h4.1"/><path d="M12 7.8v4.4l2.9 1.8"/>',
43 sliders: '<path d="M4 7.5h9.3M18.1 7.5H20"/><circle cx="15.7" cy="7.5" r="2.3"/><path d="M4 16.5h1.9M10.7 16.5H20"/><circle cx="8.3" cy="16.5" r="2.3"/>',
44 fresh: '<path d="M5.6 5h12.8A1.6 1.6 0 0 1 20 6.6v8.8a1.6 1.6 0 0 1-1.6 1.6H10.6L6 20.4V17h-.4A1.6 1.6 0 0 1 4 15.4V6.6A1.6 1.6 0 0 1 5.6 5z"/><path d="M12 8.4v5.2M9.4 11h5.2"/>',
45 bang: '<path d="M12 7.2v5.6"/><path d="M12 16.6v.01"/>',
46 eye: '<path d="M2.8 12S6 6.2 12 6.2 21.2 12 21.2 12 18 17.8 12 17.8 2.8 12 2.8 12z"/><circle cx="12" cy="12" r="2.6"/>',
47 sound: '<path d="M4.2 9.8v4.4h3.3l4.2 3.5V6.3L7.5 9.8z"/><path d="M15.3 9.3a3.8 3.8 0 0 1 0 5.4"/><path d="M17.9 6.8a7.4 7.4 0 0 1 0 10.4"/>',
48 bell: '<path d="M6.3 16.6v-5.1a5.7 5.7 0 0 1 11.4 0v5.1l1.4 1.8H4.9z"/><path d="M10.1 21h3.8"/>',
49 moon: '<path d="M19.6 14.4A7.9 7.9 0 0 1 9.6 4.4a7.9 7.9 0 1 0 10 10z"/>',
50 globe: '<circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17"/><path d="M12 3.5c2.4 2.3 3.6 5.1 3.6 8.5s-1.2 6.2-3.6 8.5c-2.4-2.3-3.6-5.1-3.6-8.5s1.2-6.2 3.6-8.5z"/>',
51 approve: '<rect x="4.2" y="4.2" width="15.6" height="15.6" rx="3.2"/><path d="M8.3 12.2l2.5 2.5 4.9-5.1"/>',
52 lock: '<rect x="5.2" y="10.6" width="13.6" height="9.4" rx="2.2"/><path d="M8.3 10.6V8a3.7 3.7 0 0 1 7.4 0v2.6"/><path d="M12 14.3v2"/>',
53 tidy: '<path d="M8 4.8l4 4 4-4"/><path d="M8 19.2l4-4 4 4"/><path d="M5 12h14"/>',
54 file: '<path d="M13.6 3.9H7.3a1.4 1.4 0 0 0-1.4 1.4v13.4a1.4 1.4 0 0 0 1.4 1.4h9.4a1.4 1.4 0 0 0 1.4-1.4V8.4z"/><path d="M13.6 3.9v4.5h4.5"/>',
55 sub: '<path d="M7 5v7a3 3 0 0 0 3 3h7.5"/><path d="M14.6 12l3 3-3 3"/>',
56 spark: '<path d="M12 4.5c.5 3.9 3.6 7 7.5 7.5-3.9.5-7 3.6-7.5 7.5-.5-3.9-3.6-7-7.5-7.5 3.9-.5 7-3.6 7.5-7.5z"/>',
57 bookmark: '<path d="M7 4.5h10a1 1 0 0 1 1 1v14l-6-4-6 4v-14a1 1 0 0 1 1-1z"/>',
58 ship: '<circle cx="7" cy="6" r="2.2"/><circle cx="7" cy="18" r="2.2"/><circle cx="17" cy="12" r="2.2"/><path d="M7 8.2v7.6"/><path d="M7 8.2c0 2.8 2.6 3.8 7.8 3.8"/>',
59 more: '<path d="M6.4 12h.01M12 12h.01M17.6 12h.01" stroke-width="3.4"/>',
60} as const
61
62export type IconName = keyof typeof PATHS
63
64/** What a terminal draws for each icon: one cell wide, so rows line up. */
65export const GLYPH: Record<IconName, string> = {
66 check: '✓',
67 done: '✓',
68 alert: '⚠',
69 clock: '◷',
70 stop: '■',
71 pause: '‖',
72 play: '▶',
73 close: '✗',
74 plan: '▤',
75 history: '≣',
76 sliders: '⚙',
77 fresh: '↻',
78 bang: '!',
79 eye: '◉',
80 sound: '♪',
81 bell: '◈',
82 moon: '☾',
83 globe: '◍',
84 approve: '▣',
85 lock: '◆',
86 tidy: '⇅',
87 file: '▫',
88 sub: '↳',
89 spark: '✦',
90 bookmark: '◆',
91 ship: '⇡',
92 more: '…',
93}
94
95const XMLNS = 'xmlns="http://www.w3.org/2000/svg"'
96
97/**
98 * A line icon in one tone, `size` px wide. Given a taller `height` (a line of text), it sits centered in it, so a
99 * mark lines up with the first line of the text beside it.
100 */
101export function iconSvg(name: IconName, tone: Tone, size = 16, height = size): string {
102 // Small icons get a heavier line, so they keep the weight of the text beside them.
103 return `<svg ${XMLNS} viewBox="0 0 24 24" width="${size}" height="${height}" fill="none" stroke="${TONE[tone]}" stroke-width="${size <= 14 ? 2.1 : 1.75}" stroke-linecap="round" stroke-linejoin="round">${PATHS[name]}</svg>`
104}
105
106/** A filled disc with the icon cut out in white: a step that is done, failed, waits on you or stopped. */
107export function badgeSvg(name: IconName, tone: Tone, size = 16, height = size): string {
108 return `<svg ${XMLNS} viewBox="0 0 24 24" width="${size}" height="${height}" fill="none" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10" fill="${TONE[tone]}"/><g stroke="#fff" stroke-width="2.3">${PATHS[name]}</g></svg>`
109}
110
111const RING = 2 * Math.PI * 8.5
112
113/**
114 * The current step: a ring that fills with its percentage. With none, a short arc stands at the turn `turn` gives
115 * (a twelfth of a circle each), so a screen redrawn each tick spins it and a still screen holds it.
116 */
117export function ringSvg(tone: Tone, size = 16, percent: number | null = null, turn = 0, height = size): string {
118 const known = percent !== null
119 // A ring barely begun still shows a sliver, so it never reads as a step still to come.
120 const length = (known ? Math.max(8, Math.min(100, percent)) / 100 : 0.3) * RING
121 const start = known ? -90 : -90 + (turn % 12) * 30
122 const arc =
123 length > 0.5
124 ? `<circle cx="12" cy="12" r="8.5" stroke="${TONE[tone]}" stroke-width="3" stroke-dasharray="${length.toFixed(2)} ${RING.toFixed(2)}" transform="rotate(${start} 12 12)"/>`
125 : ''
126
127 // The track takes the ring's own tone, faint, so a ring barely begun still reads apart from a step to come.
128 return `<svg ${XMLNS} viewBox="0 0 24 24" width="${size}" height="${height}" fill="none" stroke-linecap="round"><circle cx="12" cy="12" r="8.5" stroke="${TONE[tone]}" stroke-opacity=".4" stroke-width="3"/>${arc}</svg>`
129}
130
131/** A step still to come: an open ring. */
132export function openRingSvg(size = 16, height = size): string {
133 return `<svg ${XMLNS} viewBox="0 0 24 24" width="${size}" height="${height}" fill="none"><circle cx="12" cy="12" r="8.5" stroke="${TONE.quiet}" stroke-width="1.9"/></svg>`
134}
135
136/**
137 * A slim progress bar `width` px wide. A known `percent` fills from the left; with none, a short bar travels along
138 * the track, `sweep` (0 to 1) saying how far.
139 */
140export function meterSvg(tone: Tone, width = 96, percent: number | null = null, sweep = 0): string {
141 const height = 6
142 const track = `<rect width="${width}" height="${height}" rx="3" fill="${TONE.quiet}" fill-opacity=".28"/>`
143 let fill = ''
144 if (percent !== null) {
145 const filled = Math.round((Math.max(0, Math.min(100, percent)) / 100) * width)
146 if (filled > 0) fill = `<rect width="${Math.max(filled, height)}" height="${height}" rx="3" fill="${TONE[tone]}"/>`
147 } else {
148 const bar = Math.round(width * 0.28)
149 const at = Math.round((width - bar) * Math.max(0, Math.min(1, sweep)))
150 fill = `<rect x="${at}" width="${bar}" height="${height}" rx="3" fill="${TONE[tone]}"/>`
151 }
152
153 return `<svg ${XMLNS} viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">${track}${fill}</svg>`
154}
155
156/** Step dots for a short sequence (the welcome cards): the current one long, the rest round. */
157export function dotsSvg(count: number, current: number): string {
158 let x = 0
159 const marks = Array.from({ length: count }, (_, index) => {
160 const width = index === current ? 14 : 6
161 const mark = `<rect x="${x}" width="${width}" height="6" rx="3" fill="${index === current ? TONE.active : TONE.quiet}"${index === current ? '' : ' fill-opacity=".45"'}/>`
162 x += width + 5
163 return mark
164 })
165
166 return `<svg ${XMLNS} viewBox="0 0 ${x - 5} 6" width="${x - 5}" height="6">${marks.join('')}</svg>`
167}
168types/index.d.ts 258 lines1export type GlanceTaskStatus = 'done' | 'active' | 'upcoming'
2
3/** How big a step is: small, medium or large, counting 1, 2 or 3 toward overall progress. */
4export type GlanceTaskSize = 'S' | 'M' | 'L'
5
6export type GlanceTask = {
7 id: string
8 name: string
9 status: GlanceTaskStatus
10 percent: number
11 hasReported: boolean
12 size: GlanceTaskSize
13 /** What the step got done, in one plain-English line, as Claude said when it checked it off; null until then. */
14 summary: string | null
15 /** Tokens the model handled for this step: sent, read from the cache, written to it, and written back. */
16 tokens: number
17 /** Of those, the tokens read from the prompt cache. */
18 cachedTokens: number
19 /** When the step became the current one; null while upcoming. */
20 startedAt: number | null
21 /** When it was checked off; null until then. */
22 finishedAt: number | null
23 /** Files Claude wrote or edited during the step; absent on steps saved before 0.20. */
24 files?: GlanceFile[]
25 /** Whether a test, build or type check passed after the step last changed code; absent while it changed none. */
26 check?: GlanceCheck
27}
28
29/** Checking for and installing a newer GlanceFlow: the newest version found, and the install it was found for (`glanceflow@marketplace`). */
30export type GlanceUpdate = {
31 state: 'idle' | 'checking' | 'latest' | 'available' | 'updating' | 'updated' | 'folder' | 'failed'
32 latest: string | null
33 id: string | null
34}
35
36/** A step's code: checked by a test, build or type check that passed, one that failed, or not checked since it changed. */
37export type GlanceCheck = 'passed' | 'failed' | 'unchecked'
38
39/** A file Claude wrote or edited: its path within the project (just its name outside it), and whether the step created it. */
40export type GlanceFile = { path: string; isNew: boolean }
41
42/** `background`: Claude answered, but helpers or background tasks still run. */
43export type GlancePhase = 'working' | 'needsYou' | 'stuck' | 'stopped' | 'background' | 'done'
44
45/** A helper working under a step: a subagent, or a background task such as a long command. */
46export type GlanceHelper = {
47 id: string
48 /** The step it was started under. */
49 stepId: string
50 kind: 'helper' | 'background'
51 /** What it works on, in plain words. */
52 label: string
53 /** The helper type (Explore, general-purpose) or the background task's type (shell). */
54 type: string
55 /** The model it runs on, as people say it ("Haiku 4.5"); null until known. */
56 model: string | null
57 /** How hard it thinks (low to max); null until known or for a model without effort. */
58 effort: string | null
59 status: 'running' | 'done' | 'failed'
60 /** A helper Claude started to work in the background: its Stop ends it alone. */
61 isBackground?: boolean
62 /** Tokens this helper's own model requests handled. */
63 tokens: number
64}
65
66export type GlanceChecklist = {
67 title: string
68 phase: GlancePhase
69 tasks: GlanceTask[]
70 needsYouReason: string | null
71 /** What Claude asked, in its own words, when the turn ended on a question; shown in place of the general reason. */
72 question?: string | null
73 stuckReason: string | null
74 startedAt: number
75 finishedAt: number | null
76 isCollapsed: boolean
77 /** True once Claude laid out a real plan (plan_steps, TodoWrite, TaskCreate or Claude Desktop's own task list). */
78 hasPlan: boolean
79 /** True once Claude Desktop's own task list laid out this job's steps: that list is the plan, and the band folds it. */
80 isNative?: boolean
81 /** True once this job made any call Claude Desktop's own task list reads, even a move before its steps: no plan_steps. */
82 hasNativeList?: boolean
83 /** The turn that started this job; a late job name for another job is ignored. */
84 jobId: string
85 /** When the real plan arrived; the time-left estimate counts from here. */
86 planAt: number | null
87 /** How many steps the first plan had, to say when the plan grew. */
88 plannedCount: number
89 /** Subagents and background tasks this job started. */
90 helpers: GlanceHelper[]
91 /** Tokens of requests outside any step, such as Claude's final answer: counted in the job's total only. */
92 extraTokens: number
93 /** Of those, the tokens read from the prompt cache. */
94 extraCachedTokens: number
95 /** How a stopped job was stopped: Esc, or the Pause button. */
96 stopKind: 'esc' | 'pause' | null
97 /** What Claude is doing right now, in plain words ("Reading files"), and how many times in a row. */
98 activity: {
99 label: string
100 count: number
101 /** Claude's own one-line description of the call, when it gave one. */
102 detail: string | null
103 /** What the call works on, for the Plan in Details: the command, a file's name or a site. */
104 target: string | null
105 } | null
106 /** Approve the plan first: `waiting` until the person presses Start; `approved` for the rest of the job. */
107 approval: 'none' | 'waiting' | 'approved'
108 /** The session's spend in US dollars when the job started; null where the host keeps no ledger. */
109 costAtStart: number | null
110 /** How long one unit of step size took in this project's earlier finished jobs, in ms; null until History knows. */
111 paceMs: number | null
112 /** What will be true when the job is done, and what will show it, as Claude said in its plan. */
113 doneWhen?: string | null
114 /** The person's standing goal for this project when the job started (`/glanceflow goal`). */
115 goal?: string | null
116 /** What only the person can do or decide, as Claude reported it: a sign-in, a key, a choice, a step it couldn't run. */
117 forYou?: string[]
118 /** Choices Claude made that neither the plan nor the person settled. */
119 decided?: string[]
120}
121
122/** One plan window and how much of it is used. */
123export type GlanceLimit = {
124 /** In plain words: "5-hour", "weekly", "spending". */
125 label: string
126 /** 0 to 100. */
127 percent: number
128}
129
130/** The plan limits and chat length, shown under the checklist. */
131export type GlanceUsage = {
132 /** Every plan window the last response reported; empty off a subscription. */
133 limits: GlanceLimit[]
134 /** The fullest plan window, 0 to 100; null off a subscription. */
135 limitPercent: number | null
136 /** Which window that is, in plain words ("5-hour", "weekly"). */
137 limitLabel: string | null
138 /** When that window resets, as an ISO 8601 timestamp; null when not reported. */
139 limitResetsAt: string | null
140 /** How full this chat's context window is, 0 to 100. */
141 contextPercent: number | null
142 /** What the session has cost so far in US dollars; null where the host keeps no ledger. */
143 costUsd: number | null
144}
145
146/** Another chat on this computer, as this one mentions it: its job's name, and whether it needs the person or works on. */
147export type GlanceOtherChat = {
148 title: string
149 /** True when it waits on the person or is stuck; false while it works. */
150 needsYou: boolean
151}
152
153/** How a job ended, as the history shows it. */
154export type GlanceOutcome = 'done' | 'stopped' | 'stuck' | 'waiting' | 'background' | 'working'
155
156/** One job in the day's history: kept in the store for 30 days, on this computer only. */
157export type GlanceHistoryEntry = {
158 jobId: string
159 /** The folder the session ran in. */
160 project: string
161 startedAt: number
162 finishedAt: number | null
163 title: string
164 outcome: GlanceOutcome
165 stepsDone: number
166 stepsTotal: number
167 newTokens: number
168 cachedTokens: number
169 /** Names of the steps it finished, for the team report. */
170 doneSteps: string[]
171 /** What each finished step got done, in the order of `doneSteps`; '' where Claude gave no summary. */
172 doneNotes?: string[]
173 /** Names of the steps still open. */
174 openSteps: string[]
175 /** Files the job created, and files it changed that were there before, as paths within the project. */
176 filesAdded?: string[]
177 filesChanged?: string[]
178 /** A quick answer with no plan: listed in the panel, left out of the team report. */
179 isQuickAnswer: boolean
180 /** What the job cost in US dollars; absent where the host keeps no ledger. */
181 costUsd?: number | null
182 /** Size units of the steps it checked off (S 1, M 2, L 3), and the time they took in ms: the project's pace. */
183 doneUnits?: number
184 doneMs?: number
185 /** Whether the code it changed was checked: the worst of its steps; absent when it changed no code. */
186 check?: GlanceCheck | null
187 doneWhen?: string | null
188 goal?: string | null
189 forYou?: string[]
190 decided?: string[]
191}
192
193/** What the history pane shows: one day of one project. */
194export type GlanceHistoryView = {
195 /** YYYY-MM-DD, local time. */
196 day: string
197 project: string
198 entries: GlanceHistoryEntry[]
199 /** Days with saved history, newest first, for the day picker. */
200 days: string[]
201 /** True while the plain-English team report shows in place of the list. */
202 isReportShown: boolean
203 /** The team report for the day or the 7 days up to it, or `mine`: your own week across every project. */
204 reportSpan: 'day' | 'week' | 'mine'
205 /** This project's entries for the 7 days up to `day`, for the weekly report. */
206 weekEntries: GlanceHistoryEntry[]
207 /** Every project's entries for the 7 days up to `day`, for your own weekly summary. */
208 myWeekEntries: GlanceHistoryEntry[]
209}
210
211declare module 'claude-code' {
212 interface PluginState {
213 'glanceflow': {
214 glanceEnabled: boolean
215 /** `simple`: steps, progress and time. `detailed`: also models, effort, tokens, cache and plan usage. */
216 detailLevel: 'simple' | 'detailed'
217 checklist: GlanceChecklist | null
218 tick: number
219 usage: GlanceUsage
220 historyView: GlanceHistoryView | null
221 /** The Fresh chat button: `working` while the handoff note is written. */
222 handoffState: 'idle' | 'working'
223 /** Settings' Version row: where checking for an update, or installing one, stands. */
224 update: GlanceUpdate
225 /** The button that waits for a second press to confirm, if any. */
226 armedButton: 'handoff' | 'ship' | null
227 /** Alerts: `chime` plays a short sound when Claude needs you, gets stuck or finishes a long job; `voice` also says it. */
228 soundMode: 'off' | 'chime' | 'voice'
229 /** Desktop notices: the computer's own notification when Claude needs you, gets stuck or finishes a long job. */
230 isNoticing: boolean
231 /** The welcome card in view, 0 to 2; null once it is done or skipped. */
232 tourStep: number | null
233 /** After a tidy-up with a checkpoint, until the next message: the band offers Where we left off. */
234 isRecapShown: boolean
235 /** Calm mode: nothing moves, and statuses read in bold. */
236 isCalm: boolean
237 /** Password guard: a message that looks like it holds a password or key is held back until sent twice. */
238 isGuarded: boolean
239 /** Approve the plan first: Claude lays out its plan and waits for Start or a change. */
240 approvePlan: boolean
241 /** Finish on GitHub: a finished job offers Ship it, which commits, opens a pull request and merges once the person approves. */
242 shipsOnGithub: boolean
243 /** Whether this session's folder pushes to GitHub; Ship it shows only then. */
244 hasGithub: boolean
245 /** How full the chat gets, in percent, before the band offers to tidy it up; 0 never offers. */
246 tidyAt: number
247 /** When the last checkpoint was saved before tidying up; null when none was. */
248 checkpointAt: number | null
249 /** The other chats that need the person or are at work, read every little while from what each one saves. */
250 otherChats: GlanceOtherChat[]
251 /** Whether the band names the other chats at all: off before sharing the screen, say. */
252 showsOthers: boolean
253 /** The language GlanceFlow speaks: English, or Greek. */
254 language: 'en' | 'el'
255 }
256 }
257}
258