2026-10-18 15:39:24 -07:00
// Plan2Code Web Console - the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up; defines only.
import {
selHandoff ,
scan ,
selSpec ,
agentWorking ,
specList ,
handoffList ,
loadOverview ,
finish ,
2026-11-02 12:00:12 -08:00
loopDriving ,
2026-11-14 23:05:35 -08:00
learningBusyNow ,
LEARNING_BUSY_MS ,
2026-11-27 23:19:42 -08:00
learningBusyLimit ,
2026-10-18 15:39:24 -07:00
} from "../selectors.js" ;
2026-11-17 18:08:01 -08:00
import { whenTitle , whenWords } from "../labels.js" ;
2026-10-18 15:39:24 -07:00
import { hooks , page , redraw , saveNow } from "../state.js" ;
2026-11-17 18:08:01 -08:00
import { el , approvalTip , mdInto , releasesLink , copyButton , lightDismiss , icon , SVG_NS } from "../render.js" ;
2026-10-18 15:39:24 -07:00
import { needsRoleNudge , ROLE_NOT_SET } from "../starters.js" ;
2026-11-02 12:00:12 -08:00
import { looks , saveLooks } from "../looks.js" ;
2026-10-25 12:46:52 -07:00
import { RED_BANNER , RED_BANNER_IN_APP } from "../meter.js" ;
2026-11-12 10:35:30 -08:00
import { steadyColumns } from "../card-rows.js" ;
2026-10-18 15:39:24 -07:00
import {
dashNoteKind ,
defaultSpec ,
onInitialPick ,
cardPresentation ,
CATALOG_GROUPS ,
SKILL_CATALOG ,
2026-10-19 15:56:52 -07:00
catalogEntry ,
2026-11-02 12:00:12 -08:00
LOOP_ENTRY ,
2026-11-28 21:09:02 -08:00
APP_ONLY_ENTRIES ,
2026-11-02 12:00:12 -08:00
OUTSIDE_APP_LINE ,
2026-10-19 15:56:52 -07:00
launchVariant ,
2026-10-18 15:39:24 -07:00
SPEC_STATE_LABELS ,
chipDetail ,
isDeletableSpecDir ,
handoffAge ,
handoffCopyText ,
pickupAction ,
pickupReply ,
launchTarget ,
cardAvailability ,
launchReply ,
deleteSummary ,
deleteHandoffAction ,
deleteHandoffReply ,
deleteAction ,
deleteReply ,
2026-11-13 23:29:12 -08:00
learningAction ,
learningReply ,
learningBannerText ,
2026-11-27 23:19:42 -08:00
learningNearCapText ,
2026-10-27 18:20:30 -07:00
noteSwitchShows ,
noteTabEmpty ,
defaultNoteTicks ,
toggleNoteTick ,
formatBytes ,
NOTE_LONG_BYTES ,
MAX_ATTACHMENTS ,
2026-10-18 15:39:24 -07:00
} from "../answers.js" ;
import { stateFor } from "../spec-states.js" ;
import { sound , soundOn , fadeSound , dropSounds } from "../sound.js" ;
import { playWake } from "../boot.js" ;
const $ = ( id ) => document . getElementById ( id );
// The dashboard's first-open wake-up itself is page.wake (state.js). Once per
// page, whatever storage allows: a re-render mid-run must never start a
// second one.
let wakeTried = false ;
// True when a wake-up is waiting on the first click: the page load's opening
// chime then gives way to the boot-up sound, played as he powers on.
export let wakeHoldsChime = false ;
// His snore while he sleeps (an Audio on loop), or null. Usually silent until
// the waking click, since browsers refuse sound before one.
let snore = null ;
2026-11-17 18:08:01 -08:00
// The role is asked once; closing Preferences without one, or Not now, counts
// as asked and ends the line (Help says so).
function roleAsked () {
if ( looks . role === undefined ) {
looks . role = ROLE_NOT_SET ;
saveLooks ();
redraw ();
}
}
// After the first launch: one quiet line for the two optional extras, a role
// (starter templates ordered for you) and Learning. Until then both are held,
// so the first dashboard offers a card and nothing else.
function extrasLine () {
const line = el ( "p" , "dash-extras" );
// Learning is only on offer while it is Not set up; the role is always there
// (the line shows only while the role is unasked).
const learning = scan () && scan (). learning ;
const withLearning = Boolean ( learning && learning . state === "not-set-up" );
line . appendChild ( document . createTextNode ( withLearning ? "Two optional extras: " : "One optional extra: " ));
const role = el ( "button" , "dash-extras-link" , "set your role" );
role . type = "button" ;
role . addEventListener ( "click" , () => {
$ ( "looks-modal" ). addEventListener ( "close" , roleAsked , { once : true });
2026-11-02 12:00:12 -08:00
hooks . openPrefs ( "appearance" );
2026-10-18 15:39:24 -07:00
});
2026-11-17 18:08:01 -08:00
line . appendChild ( role );
if ( withLearning ) {
line . appendChild ( document . createTextNode ( ", " ));
const learn = el ( "button" , "dash-extras-link" , "switch on Learning" );
learn . type = "button" ;
learn . addEventListener ( "click" , () => {
const row = $ ( "main" ). querySelector ( ".learn-row" );
if ( ! row ) return ;
row . scrollIntoView ({ block : "center" });
const go = row . querySelector ( "button" );
if ( go ) go . focus ();
});
line . appendChild ( learn );
}
line . appendChild ( document . createTextNode ( "." ));
const notNow = el ( "button" , "btn xs soft" , "Not now" );
2026-10-18 15:39:24 -07:00
notNow . type = "button" ;
notNow . addEventListener ( "click" , () => {
looks . role = ROLE_NOT_SET ;
saveLooks ();
redraw ();
});
2026-11-17 18:08:01 -08:00
line . appendChild ( notNow );
return line ;
2026-10-18 15:39:24 -07:00
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey () {
try {
return "p2c-update-dismissed:" + page . S . sid ;
} catch {
return "p2c-update-dismissed:" ;
}
}
function updateDismissed () {
try {
return sessionStorage . getItem ( updateDismissKey ()) === page . updateFrame . latest ;
} catch {
return false ;
}
}
const UPDATE_COMMAND = "plan2code update" ;
// For a machine without the plan2code command: the full installer, menu and all.
2026-11-17 18:08:01 -08:00
const UPDATE_FALLBACK_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release" ;
2026-10-18 15:39:24 -07:00
function openUpdateModal () {
if ( ! page . updateFrame ) return ;
const versions = $ ( "update-versions" );
versions . replaceChildren (
document . createTextNode ( "Version " ),
releasesLink ( "v" + page . updateFrame . latest ),
2026-11-17 18:08:01 -08:00
document . createTextNode ( " is out, you have " ),
2026-10-18 15:39:24 -07:00
el ( "code" , null , page . updateFrame . installed ),
document . createTextNode ( "." )
);
const row = $ ( "update-command" );
const code = el ( "code" , null , UPDATE_COMMAND );
2026-11-17 18:08:01 -08:00
row . replaceChildren ( code , copyButton ( UPDATE_COMMAND , "btn sm ghost handoff-copy" , code ));
2026-10-18 15:39:24 -07:00
const fallbackRow = $ ( "update-fallback" );
const fallback = el ( "code" , null , UPDATE_FALLBACK_COMMAND );
2026-11-17 18:08:01 -08:00
fallbackRow . replaceChildren ( fallback , copyButton ( UPDATE_FALLBACK_COMMAND , "btn sm ghost handoff-copy" , fallback ));
// Under the app, the bar's Update and restart does all of it in one click;
// the command is the fallback, and its terminal panel runs the agent, so
// it goes in a terminal outside the app.
$ ( "update-step-run" ). replaceChildren (
...( page . inApp
? [ "Press " , el ( "strong" , null , "Update and restart" ), " in the app's top bar. Or run this in a terminal outside the app (not in its terminal panel, which runs your agent):" ]
: [ "Run this in your terminal (not in this page or your agent):" ])
);
2026-11-10 10:19:33 -08:00
$ ( "update-step-restart" ). replaceChildren (
...( page . inApp
2026-11-17 18:08:01 -08:00
? [ "Update and restart reopens the app by itself. After the command, close the app and open it again." ]
2026-11-10 10:19:33 -08:00
: [ "When it finishes, close this console and start " , el ( "code" , null , "plan2code" ), " again." ])
);
2026-10-18 15:39:24 -07:00
$ ( "update-modal" ). showModal ();
}
export function renderDashboard ( main ) {
maybeWake ();
2026-10-27 18:20:30 -07:00
// The menu is up, so the confirm pane was left: its Notebook switch starts
// off again, with nothing picked, the next time a card is opened.
note = null ;
2026-10-18 15:39:24 -07:00
// First, so nothing below reads a pick whose handoff has left the scan, and
// a delete the agent's rescan has finished stops holding the buttons.
selHandoff ();
settleDeleting ();
const menu = ( page . S && page . S . menu ) || {};
const wrap = el ( "div" , "dash" );
2026-11-17 18:08:01 -08:00
const firstRun = looks . skillLaunched !== true ;
2026-10-18 15:39:24 -07:00
// Advice only: words, never a button, and nothing is blocked.
if ( page . meterFrame && page . meterFrame . level === "red" ) {
2026-11-17 18:08:01 -08:00
const warn = el ( "div" , "callout is-warn dash-nudge meter-banner" , page . inApp ? RED_BANNER_IN_APP : RED_BANNER );
2026-10-18 15:39:24 -07:00
warn . setAttribute ( "role" , "status" );
wrap . appendChild ( warn );
}
2026-11-10 10:19:33 -08:00
// Built here only, so no other workflow's page ever shows it. It shows under
// the app too, beside the app bar's own "Update available": the app cannot
// replace itself, so a new release is the same terminal command either way
// (the bar's one-click Update skills only levels skills to the app's own
// version), and the modal words its steps for the app.
if ( page . updateFrame && ! updateDismissed ()) {
2026-11-17 18:08:01 -08:00
const notice = el ( "div" , "callout is-info dash-nudge update-banner" );
2026-10-18 15:39:24 -07:00
notice . setAttribute ( "role" , "status" );
2026-11-17 18:08:01 -08:00
const open = el ( "button" , "update-banner-open" , "Update available · v" + page . updateFrame . latest );
2026-10-18 15:39:24 -07:00
open . type = "button" ;
open . addEventListener ( "click" , openUpdateModal );
2026-11-17 18:08:01 -08:00
const dismiss = el ( "button" , "update-banner-dismiss" );
dismiss . appendChild ( icon ( "close" ));
2026-10-18 15:39:24 -07:00
dismiss . type = "button" ;
dismiss . setAttribute ( "aria-label" , "Dismiss until next time" );
dismiss . addEventListener ( "click" , () => {
try {
sessionStorage . setItem ( updateDismissKey (), page . updateFrame . latest );
} catch {}
redraw ();
});
notice . append ( open , dismiss );
wrap . appendChild ( notice );
}
2026-11-13 23:29:12 -08:00
// Lessons waiting for review: last of the banners, so it sits nearest the
// title (the others are more urgent). Hidden while paused or off.
const learnBanner = learningBanner ( scan ());
if ( learnBanner ) wrap . appendChild ( learnBanner );
2026-11-17 18:08:01 -08:00
if ( ! firstRun && needsRoleNudge ( looks )) wrap . appendChild ( extrasLine ());
2026-10-18 15:39:24 -07:00
wrap . appendChild ( el ( "p" , "card-kicker" , "Plan2Code" ));
wrap . appendChild ( el ( "h2" , "dash-title" , "What are we doing today?" ));
// The agent's note reads the spec the picker opened on (the same "initial"
// test cardPresentation uses): another pick, or Start from scratch, gets
// the neutral line rather than context about a spec no longer shown.
const first = defaultSpec ( scan () && scan (). specs );
const picked = selSpec ();
const noteKind = dashNoteKind ({ menu , hasMenu : Boolean ( page . S . menu ), onInitial : onInitialPick ( first , picked ), working : agentWorking () });
if ( noteKind === "agent" ) {
wrap . appendChild ( el ( "p" , "dash-note" , menu . note ));
} else if ( noteKind === "looking" ) {
// The cards work from the first paint; the agent's read of the
// project arrives a moment later, and this says so meanwhile.
const note = el ( "p" , "dash-note" );
note . appendChild ( document . createTextNode ( "Pick what to do next. " ));
const working = el ( "span" , "dash-working" );
working . appendChild ( el ( "span" , "spinner tiny" ));
working . appendChild (
el (
"span" ,
null ,
"Plan2Code is still looking over the project and will flag where it would start when it is done."
)
);
note . appendChild ( working );
wrap . appendChild ( note );
} else {
wrap . appendChild (
el ( "p" , "dash-note" , "Pick what to do next. It starts right here, and this page becomes its home." )
);
}
const specs = specList ();
if ( specs . length || handoffList (). length ) wrap . appendChild ( renderSpecPicker ( specs ));
const handoff = selHandoff ();
if ( handoff ) {
// A handoff is picked up, not launched: its skill and spec come from its
// own record, so the skill cards and their toggle have nothing to say.
if ( ! page . local . launching && ! page . launchScoping && page . scopeMine !== "" ) hooks . syncWorkspaceScope ();
wrap . appendChild ( renderHandoffPreview ( handoff ));
main . appendChild ( wrap );
queueMicrotask ( hooks . maybeWelcome );
return ;
}
wrap . appendChild ( hideUnavailableToggle ());
2026-11-13 23:29:12 -08:00
// Learning while it needs the person (not set up, off, paused): under the
// picker. Never while a handoff preview shows (returned above).
const learnTop = hooks . renderLearningRow ( scan (), "top" );
if ( learnTop ) wrap . appendChild ( learnTop );
2026-10-18 15:39:24 -07:00
// Only when this tab's own pick moved: another tab changing the scope
// sends a frame here too, and re-asserting this tab's pick on every render
// had two dashboards trade the workspace back and forth without end.
const wantScope = ( selSpec () && selSpec (). dir ) || "" ;
if ( ! page . local . launching && ! page . launchScoping && wantScope !== page . scopeMine ) hooks . syncWorkspaceScope ();
// "Unavailable" is the scan's verdict for the selected spec, not the
2026-10-26 06:36:46 -07:00
// momentary graying while a launch is in flight or the server is away, so
2026-10-18 15:39:24 -07:00
// cards never blink out of the menu mid-handoff.
const hide = looks . hideUnavailable ;
const sel = selSpec ();
const available = ( e ) => cardPresentation ( e , scan (), sel , menu ). on ;
let shown = 0 ;
for ( const g of CATALOG_GROUPS ) {
const entries = SKILL_CATALOG . filter (( e ) => e . group === g . id && ( ! hide || available ( e )));
2026-11-28 21:09:02 -08:00
// The desktop app's Implementation Loop and Review Loop cards close their
// group. Outside the app they are always drawn, grayed, so the features can
// be found.
const loopCards = APP_ONLY_ENTRIES . filter (( e ) => e . group === g . id && ( ! page . inApp || ! hide || available ( e )));
if ( ! entries . length && ! loopCards . length ) continue ;
shown += entries . length + loopCards . length ;
2026-10-18 15:39:24 -07:00
const section = el ( "section" , "dash-group" );
section . appendChild ( el ( "h3" , "dash-group-title" , g . title ));
const grid = el ( "div" , "dash-grid" );
for ( const e of entries ) grid . appendChild ( dashCard ( e , menu ));
2026-11-28 21:09:02 -08:00
for ( const e of loopCards ) grid . appendChild ( dashCard ( e , menu ));
2026-10-18 15:39:24 -07:00
section . appendChild ( grid );
wrap . appendChild ( section );
}
if ( ! shown ) {
wrap . appendChild (
2026-11-17 18:08:01 -08:00
el ( "p" , "empty" , "Nothing fits this pick right now. Turn off the toggle above to see every skill." )
2026-10-18 15:39:24 -07:00
);
}
2026-11-13 23:29:12 -08:00
// Learning while on: after the last card group, before the approval tip.
const learnBottom = hooks . renderLearningRow ( scan (), "bottom" );
if ( learnBottom ) wrap . appendChild ( learnBottom );
2026-10-18 15:39:24 -07:00
wrap . appendChild ( approvalTip ());
// Mid wake-up: the groups wait hidden until the glide lets them rise in,
// and the note shows only as far as it has been typed. Once the entrance
// has played, a re-render draws the menu plainly, never replaying it.
if ( page . wake && ! page . wake . entered ) wrap . classList . add ( "waking" , ...( page . wake . cards ? [ "is-in" ] : []));
if ( page . wake && page . wake . typed != null ) {
const note = wrap . querySelector ( ".dash-note" );
if ( note ) revealNote ( note , page . wake . typed );
}
main . appendChild ( wrap );
2026-11-12 10:35:30 -08:00
fitCardRows ( wrap );
watchCardRows ( wrap );
2026-10-18 15:39:24 -07:00
// Deferred: this runs inside render(), and the dialog is not part of it.
queueMicrotask ( hooks . maybeWelcome );
}
2026-11-12 10:35:30 -08:00
// Each group's cards share one width, in as many columns as leave no card
// alone on a row (card-rows.js). Measured from the grid's own width, so the
// Card width setting and the window both count; only a change is written.
function fitCardRows ( root ) {
for ( const grid of root . querySelectorAll ( ".dash-grid" )) {
const { cols , center } = steadyColumns ( grid . children . length , grid . clientWidth );
if ( grid . style . getPropertyValue ( "--dash-cols" ) !== String ( cols )) grid . style . setProperty ( "--dash-cols" , String ( cols ));
grid . classList . toggle ( "is-centered" , center );
}
}
// One watcher, on the menu drawn last: a resize refits its groups. Fitting
2026-11-12 10:59:09 -08:00
// changes the menu's height, which usually refits to the same columns. It can
// feed itself only when that height change adds or removes the main column's
// scrollbar and the grid's width sits within a scrollbar's width of a column
// break; then the count may swap back and forth.
2026-11-12 10:35:30 -08:00
const rowsObserver = typeof ResizeObserver === "function" ? new ResizeObserver (( entries ) => entries . forEach (( e ) => fitCardRows ( e . target ))) : null ;
function watchCardRows ( wrap ) {
if ( ! rowsObserver ) return ;
rowsObserver . disconnect ();
rowsObserver . observe ( wrap );
}
2026-10-18 15:39:24 -07:00
const WAKE_TYPE_DELAY_MS = 350 ;
const WAKE_TYPE_EVERY_MS = 14 ;
const WAKE_ENTRANCE_MS = 900 ;
// One snore, for a nudge with no sound to time it (sounds off, or refused).
const SNORE_MS = 2600 ;
// The longest a nudge waits on the snore ending: a hidden tab may never say.
const SNORE_MAX_MS = 6000 ;
const BOOTUP_FADE_MS = 500 ;
const delay = ( ms ) => new Promise (( resolve ) => setTimeout ( resolve , ms ));
// Only a newly opened dashboard carries `wake` (console.mjs deletes it on
// every resume), and only the first page load in this tab plays it.
function maybeWake () {
if ( wakeTried || page . S . wake !== true || finish ()) return ;
wakeTried = true ;
2026-11-09 11:46:13 -08:00
if ( looks . skipIntro === true ) return ;
2026-10-18 15:39:24 -07:00
const key = "p2c-console:woke:" + page . S . sid ;
try {
if ( sessionStorage . getItem ( key )) return ;
sessionStorage . setItem ( key , "1" );
} catch {
// Blocked storage only costs the reload guard.
}
const stage = $ ( "wake" );
const pilot = $ ( "planny" ). closest ( ".pilot" );
page . wake = { cards : false , entered : false , typed : 0 , timers : [], abort : new AbortController () };
wakeHoldsChime = ! matchMedia ( "(prefers-reduced-motion: reduce)" ). matches ;
if ( wakeHoldsChime && soundOn ( "snore" )) {
snore = new Audio ( "/sleeping.mp3" );
snore . loop = true ;
snore . play (). catch (() => {});
}
pilot . classList . add ( "is-waking" );
playWake ({
stage ,
bot : stage . querySelector ( ".wake-bot" ),
skipEl : stage . querySelector ( ".wake-skip" ),
target : $ ( "planny" ),
stir : stirWake ,
onStart : () => sound ( "bootup" ),
onGlide : wakeGlide ,
onSkip : skipWakeSounds ,
signal : page . wake . abort . signal ,
}). then (({ skipped }) => {
stopSnore ();
fadeSound ( "bootup" , BOOTUP_FADE_MS );
pilot . classList . remove ( "is-waking" );
// An abort or reduced motion jumps straight to the finished
// dashboard. A run that reached its end leaves the note typing on.
if ( skipped || ( page . wake && ! page . wake . cards )) finishWake ();
});
}
// The nudge: one whole snore from the top, however far the loop had got (or
// the first one heard, since the loop is usually refused until this click).
// Called inside the click, so the browser lets it play. Settles when it ends,
// and never rejects: a refused or silent snore just takes one snore's time.
function stirWake () {
if ( ! snore ) return delay ( SNORE_MS );
const heard = new Promise (( resolve ) => snore . addEventListener ( "ended" , resolve , { once : true }));
snore . loop = false ;
snore . currentTime = 0 ;
return snore . play (). then (
() => Promise . race ([ heard , delay ( SNORE_MAX_MS )]),
() => delay ( SNORE_MS )
);
}
function stopSnore () {
if ( ! snore ) return ;
snore . pause ();
snore = null ;
}
// The Skip button: silence anything the intro already queued or started. The
// promise's .then does the snore and the bootup fade; this only clears cues
// still waiting to play.
function skipWakeSounds () {
dropSounds ();
}
// The glide: the menu rises in and the note starts typing. On a skip the run
// is already ending and its promise settles everything, so nothing here.
function wakeGlide ({ instant }) {
if ( ! page . wake ) return ;
page . wake . cards = true ;
if ( instant ) return ;
page . wake . timers . push (
setTimeout (() => {
page . wake . entered = true ;
settleWake ();
}, WAKE_ENTRANCE_MS ),
setTimeout ( typeNote , WAKE_TYPE_DELAY_MS )
);
redraw ();
}
// One more character of the note on the live element. Whatever the note says
// right now is what gets typed, so a `menu` note that lands mid-way simply
// carries on from the same count.
function typeNote () {
if ( ! page . wake || page . wake . typed == null ) return ;
page . wake . typed += 1 ;
const note = $ ( "main" ). querySelector ( ":scope > .dash .dash-note" );
if ( ! note || page . wake . typed >= revealNote ( note , page . wake . typed )) {
page . wake . typed = null ;
if ( note ) revealNote ( note , Infinity );
return settleWake ();
}
page . wake . timers . push ( setTimeout ( typeNote , WAKE_TYPE_EVERY_MS ));
}
// Done once the entrance has played and the note is all there. Nothing to
// redraw: what is on screen already is the finished dashboard.
function settleWake () {
if ( page . wake && page . wake . entered && page . wake . typed == null ) {
page . wake = null ;
hooks . maybeWelcome ();
}
}
function finishWake () {
if ( ! page . wake ) return ;
for ( const t of page . wake . timers ) clearTimeout ( t );
page . wake = null ;
redraw ();
}
// Shows the first `count` characters of a note's text, across its text nodes,
// and returns how many there are in all. The full text is kept per node the
// first time it is cut, so later calls can grow it back. An element the
// typing has not reached yet (the "still looking" pill and its spinner) is
// kept out of sight, rather than showing as an empty box.
const noteFullText = new WeakMap ();
function revealNote ( note , count ) {
const walker = document . createTreeWalker ( note , NodeFilter . SHOW_TEXT | NodeFilter . SHOW_ELEMENT );
let total = 0 ;
for ( let n = walker . nextNode (); n ; n = walker . nextNode ()) {
if ( n . nodeType === Node . ELEMENT_NODE ) {
n . classList . toggle ( "is-untyped" , total >= count );
continue ;
}
if ( ! noteFullText . has ( n )) noteFullText . set ( n , n . data );
const full = noteFullText . get ( n );
n . data = full . slice ( 0 , Math . max ( 0 , count - total ));
total += full . length ;
}
return total ;
}
// A page-wide preference, so it rides in `looks` (looks.json) and follows the
// person to every session and port rather than resetting per dashboard.
function hideUnavailableToggle () {
const label = el ( "label" , "dash-toggle" );
const box = el ( "input" );
box . type = "checkbox" ;
// The id is what lets withFocus hand focus back after the rebuild.
box . id = "dash-hide-unavailable" ;
box . setAttribute ( "role" , "switch" );
box . checked = looks . hideUnavailable ;
box . addEventListener ( "change" , () => {
looks . hideUnavailable = box . checked ;
saveLooks ();
redraw ();
});
label . appendChild ( box );
label . appendChild ( el ( "span" , "dash-toggle-track" ));
2026-11-17 18:08:01 -08:00
label . appendChild ( el ( "span" , "dash-toggle-text" , "Hide unavailable skills" ));
2026-10-18 15:39:24 -07:00
return label ;
}
/* The spec picker: every spec the server found under specs/, plus "start
from scratch". The selection decides which cards below are lit, and rides
along on the launch of any card that takes a spec. Picking is page-local —
no send — so it costs nothing to change your mind. */
function renderSpecPicker ( specs ) {
const sel = selSpec ();
const handoffs = handoffList ();
const pickedHandoff = selHandoff ();
const box = el ( "section" , "spec-pick" );
box . appendChild (
el ( "h3" , "dash-group-title" , handoffs . length ? "Pick up a spec or a handoff, or start fresh" : "Pick up a spec, or start fresh" )
);
const row = el ( "div" , "spec-row" );
const scratchOn = ! sel && ! pickedHandoff ;
const scratch = el ( "button" , "spec-chip" + ( scratchOn ? " is-sel" : "" ));
scratch . type = "button" ;
scratch . setAttribute ( "aria-current" , String ( scratchOn ));
scratch . appendChild ( el ( "span" , "spec-chip-name" , "Start from scratch" ));
scratch . appendChild ( el ( "span" , "spec-chip-state" , "a new idea" ));
scratch . addEventListener ( "click" , () => {
page . local . specSel = null ;
saveNow ();
redraw ();
loadOverview ();
});
row . appendChild ( scratch );
for ( const spec of specs ) {
const on = sel && sel . dir === spec . dir ;
// A finished spec (a fixed bug) is hidden while unavailable workflows
// are, dimmed otherwise. A pick already on it stays visible, so it is
// never lost.
const fixed = Boolean ( stateFor ( spec . state ) ? . finished );
if ( fixed && looks . hideUnavailable && ! on ) continue ;
const deleting = Boolean ( page . local . deleting && page . local . deleting . dir === spec . dir );
const wrap = el ( "div" , "spec-chip-wrap" + ( deleting ? " is-deleting" : "" ) + ( fixed ? " is-fixed" : "" ));
const b = el ( "button" , "spec-chip" + ( on ? " is-sel" : "" ));
b . type = "button" ;
b . setAttribute ( "aria-current" , String ( Boolean ( on )));
b . appendChild ( el ( "span" , "spec-chip-name" , spec . name ));
b . appendChild ( el ( "span" , "spec-chip-state" , deleting ? "Deleting…" : SPEC_STATE_LABELS [ spec . state ] || spec . state ));
const detail = chipDetail ( spec );
if ( detail ) b . appendChild ( el ( "span" , "spec-chip-detail" , detail ));
b . addEventListener ( "click" , () => {
page . local . specSel = spec . dir ;
saveNow ();
redraw ();
loadOverview ();
});
wrap . appendChild ( b );
if ( isDeletableSpecDir ( spec . dir )) {
// A fixed bug is done with, so its Delete is a visible button rather
// than the hover ✕ every other spec has.
2026-11-17 18:08:01 -08:00
const del = fixed ? el ( "button" , "spec-chip-del-label" , "Delete" ) : el ( "button" , "spec-chip-del" );
if ( ! fixed ) del . appendChild ( icon ( "close" ));
2026-10-18 15:39:24 -07:00
del . type = "button" ;
del . title = `Delete ${ spec . dir } /` ;
del . setAttribute ( "aria-label" , `Delete the spec ${ spec . name } ` );
del . disabled = deleting || Boolean ( page . local . deleting ) || page . gone || page . pendingResult || Boolean ( page . local . launching );
del . addEventListener ( "click" , () => openDeleteConfirm ( spec ));
wrap . appendChild ( del );
}
row . appendChild ( wrap );
}
// Handoffs follow the specs: dashed chips, the state word is "Handoff".
for ( const h of handoffs ) {
const on = Boolean ( pickedHandoff && pickedHandoff . id === h . id );
const deleting = Boolean ( page . local . deleting && page . local . deleting . dir === "handoff:" + h . id );
const b = el ( "button" , "spec-chip is-handoff" + ( on ? " is-sel" : "" ) + ( deleting ? " is-deleting" : "" ));
b . type = "button" ;
b . setAttribute ( "aria-current" , String ( on ));
b . appendChild ( el ( "span" , "spec-chip-name" , h . title || "Handoff" ));
b . appendChild ( el ( "span" , "spec-chip-state" , deleting ? "Deleting…" : "Handoff" ));
b . appendChild ( el ( "span" , "spec-chip-detail" , handoffAge ( h . written )));
b . addEventListener ( "click" , () => {
page . local . specSel = "handoff:" + h . id ;
saveNow ();
redraw ();
});
row . appendChild ( b );
}
box . appendChild ( row );
return box ;
}
// A delete in flight ends when the agent's rescan lands (a new scan), gone
// or refused: either way the picker is the truth again.
function settleDeleting () {
const sc = scan ();
if ( page . local . deleting && sc && sc . at !== page . local . deleting . scanAt ) {
page . local . deleting = null ;
saveNow ();
}
}
// What a picked handoff shows: where it came from and its Next task, with the
// four things to do with it.
function renderHandoffPreview ( h ) {
const box = el ( "section" , "handoff-preview" );
box . appendChild ( el ( "h3" , "handoff-preview-title" , h . title || "Handoff" ));
2026-10-19 15:56:52 -07:00
const entry = catalogEntry ( h . skill );
2026-10-18 15:39:24 -07:00
const meta = [
2026-11-17 18:08:01 -08:00
"Written " + ( h . written ? whenWords ( h . written ) || "at an unknown time" : "at an unknown time" ),
2026-10-18 15:39:24 -07:00
h . spec ? "spec " + h . spec . replace ( /^specs\// , "" ) : "no spec" ,
"from " + ( entry ? entry . title : h . skill ),
];
2026-11-17 18:08:01 -08:00
const metaLine = el ( "p" , "handoff-preview-meta" , meta . join ( " · " ));
if ( h . written ) metaLine . title = whenTitle ( h . written );
box . appendChild ( metaLine );
2026-10-18 15:39:24 -07:00
if ( h . next ) {
box . appendChild ( el ( "p" , "handoff-preview-label" , "Next task" ));
box . appendChild ( el ( "p" , "handoff-preview-next" , h . next ));
}
const busy = Boolean ( page . local . launching || page . local . deleting ) || page . gone || page . pendingResult ;
const actions = el ( "div" , "handoff-preview-actions" );
const go = el ( "button" , "btn primary" , "Pick it up here" );
go . type = "button" ;
go . disabled = busy ;
go . addEventListener ( "click" , () => pickUpHandoff ( h ));
const read = el ( "button" , "btn" , "Read it all" );
read . type = "button" ;
read . addEventListener ( "click" , () => readHandoff ( h ));
2026-10-25 12:46:52 -07:00
const copyLabel = page . inApp ? "Copy for another session" : "Copy for a new conversation" ;
2026-10-26 21:43:53 -07:00
const shown = handoffCopied && handoffCopied . id === h . id && Date . now () < handoffCopied . until ? handoffCopied . word : copyLabel ;
const copy = el ( "button" , "btn" , shown );
2026-10-18 15:39:24 -07:00
copy . type = "button" ;
2026-10-26 21:43:53 -07:00
copy . dataset . handoffCopy = h . id ;
2026-10-18 15:39:24 -07:00
copy . addEventListener ( "click" , () => {
const dir = ( scan () && scan (). handoffsDir ) || "" ;
const sep = dir . includes ( "\\" ) ? "\\" : "/" ;
const file = dir ? dir . replace ( /[\\/]+$/ , "" ) + sep + h . id + ".md" : h . id + ".md" ;
2026-10-26 21:43:53 -07:00
copyHandoffText ( handoffCopyText ( file ), h . id , copyLabel );
2026-10-18 15:39:24 -07:00
});
const del = el ( "button" , "btn danger" , "Delete" );
del . type = "button" ;
del . disabled = busy ;
del . addEventListener ( "click" , () => openHandoffDelete ( h ));
actions . append ( go , read , copy , del );
box . appendChild ( actions );
return box ;
}
// The prompt that sends a new conversation to the handoff. A refused
// clipboard gets a plain word on the button instead of a silent nothing.
2026-10-26 21:43:53 -07:00
// A redraw while the clipboard answers rebuilds the button, so the word is
// kept in handoffCopied (which the rebuilt button reads) and put on whichever
// button is on the page when the answer comes.
let handoffCopied = null ;
const handoffCopyButton = ( id ) => document . querySelector ( `button[data-handoff-copy=" ${ CSS . escape ( id ) } "]` );
async function copyHandoffText ( text , id , label ) {
let word ;
2026-10-18 15:39:24 -07:00
try {
await navigator . clipboard . writeText ( text );
2026-10-26 21:43:53 -07:00
word = "Copied" ;
2026-10-18 15:39:24 -07:00
} catch {
2026-10-26 21:43:53 -07:00
word = "Copy was refused" ;
2026-10-18 15:39:24 -07:00
}
2026-10-26 21:43:53 -07:00
const mark = { id , word , until : Date . now () + 1500 };
handoffCopied = mark ;
const shown = handoffCopyButton ( id );
if ( shown ) shown . textContent = word ;
setTimeout (() => {
if ( handoffCopied !== mark ) return ;
handoffCopied = null ;
const live = handoffCopyButton ( id );
if ( live ) live . textContent = label ;
}, 1500 );
2026-10-18 15:39:24 -07:00
}
// Pick it up here: a hop like a card launch. The page sends only the id; the
// CLI reads the stored skill and spec, marks the handoff used and falls back
// to Quick Task if either is gone.
async function pickUpHandoff ( h ) {
2026-11-05 11:38:59 -08:00
if ( page . gone || page . pendingResult || page . local . launching || page . launchScoping || finish ()) return ;
2026-10-18 15:39:24 -07:00
page . launchScoping = true ;
await hooks . syncWorkspaceScope ( h . spec || "" );
try {
const res = await fetch ( "/submit" , {
method : "POST" ,
headers : { "content-type" : "application/json" },
body : JSON . stringify ({ actions : [ pickupAction ( h )], reply : pickupReply ( h ) }),
});
if ( res . status === 409 ) {
page . launchScoping = false ;
page . pendingResult = true ;
hooks . banner ( "Your last pick is still being picked up. One moment." , "info" );
return ;
}
if ( ! res . ok ) throw new Error ( String ( res . status ));
sound ( "startSkill" );
page . local . launching = { skill : h . skill , title : h . title || "the handoff" , at : Date . now () };
page . launchScoping = false ;
page . pendingResult = true ;
saveNow ();
redraw ();
} catch {
page . launchScoping = false ;
hooks . banner ( "That did not go through. Nothing was lost; try again." , "warn" );
}
}
// Read it all: the document, in a dialog, from /handoff?id= (served only for
// an id the dashboard's own scan listed).
async function readHandoff ( h ) {
$ ( "handoff-title" ). textContent = h . title || "Handoff" ;
const body = $ ( "handoff-body" );
body . replaceChildren ( el ( "p" , "md-p" , "Reading…" ));
$ ( "handoff-modal" ). showModal ();
try {
const res = await fetch ( "/handoff?id=" + encodeURIComponent ( h . id ), { cache : "no-store" });
if ( res . status !== 200 ) throw new Error ( String ( res . status ));
mdInto ( body , await res . text ());
} catch {
body . replaceChildren ( el ( "p" , "md-p" , "This handoff could not be read." ));
}
}
2026-11-28 21:09:02 -08:00
const REVIEW_LOOP_SKILL = "plan2code-review-loop" ;
2026-10-18 15:39:24 -07:00
function dashCard ( entry , menu ) {
2026-11-02 12:00:12 -08:00
const presentation = entry . appOnly ? loopPresentation ( entry , menu ) : cardPresentation ( entry , scan (), selSpec (), menu );
2026-10-18 15:39:24 -07:00
// The agent's `recommend` and detail describe the initially selected spec.
// Other picker choices derive both from the scan, so stale context never
2026-10-26 06:36:46 -07:00
// follows a person to a different spec or to "start from scratch". A grayed
2026-10-18 15:39:24 -07:00
// recommendation also yields to the selected spec's actual next step.
2026-10-19 15:56:52 -07:00
const going = page . local . launching && ( page . local . launching . skill === entry . skill || page . local . launching . skill === entry . review );
2026-10-18 15:39:24 -07:00
const b = el (
"button" ,
"dash-card" + ( presentation . recommended ? " is-suggested" : "" ) + ( going ? " is-going" : "" )
);
b . type = "button" ;
2026-11-02 12:00:12 -08:00
b . disabled = Boolean ( page . local . launching ) || page . gone || page . pendingResult || loopDriving () || ! presentation . on ;
2026-10-18 15:39:24 -07:00
if ( ! presentation . on && presentation . reason ) b . title = presentation . reason ;
const head = el ( "span" , "dash-card-head" );
2026-11-17 18:08:01 -08:00
head . appendChild ( el ( "span" , "pill is-neutral is-caps dash-chip" , entry . chip ));
if ( presentation . recommended ) head . appendChild ( el ( "span" , "pill is-accent is-caps suggested" , "Suggested" ));
2026-10-18 15:39:24 -07:00
b . appendChild ( head );
2026-11-02 13:22:59 -08:00
const title = el ( "span" , "dash-card-title" );
if ( entry . icon ) {
const svg = document . createElementNS ( SVG_NS , "svg" );
svg . setAttribute ( "class" , "dash-card-icon" );
svg . setAttribute ( "aria-hidden" , "true" );
const use = document . createElementNS ( SVG_NS , "use" );
use . setAttribute ( "href" , "#ci-" + entry . icon );
svg . appendChild ( use );
title . appendChild ( svg );
}
title . appendChild ( document . createTextNode ( entry . title ));
b . appendChild ( title );
2026-10-18 15:39:24 -07:00
b . appendChild ( el ( "span" , "dash-card-blurb" , entry . blurb ));
2026-11-28 21:09:02 -08:00
// A line only the desktop app shows (the Review card's pointer to the Review Loop).
if ( entry . appNote && page . inApp ) b . appendChild ( el ( "span" , "dash-card-detail" , entry . appNote ));
2026-10-18 15:39:24 -07:00
if ( presentation . detail ) b . appendChild ( el ( "span" , "dash-card-detail" , presentation . detail ));
if ( ! presentation . on && presentation . reason ) b . appendChild ( el ( "span" , "dash-card-off" , presentation . reason ));
const foot = el ( "span" , "dash-card-foot" );
foot . appendChild ( el ( "code" , "dash-card-cmd" , entry . command ));
foot . appendChild ( el ( "span" , "dash-card-go" , going ? "…" : "→" ));
b . appendChild ( foot );
b . addEventListener ( "click" , () => {
2026-11-28 21:09:02 -08:00
// A loop card opens its own setup screen instead of a confirm pane.
if ( entry . appOnly ) return entry . skill === REVIEW_LOOP_SKILL ? hooks . openReviewLoopSetup ( selSpec ()) : hooks . openLoopSetup ( selSpec ());
2026-10-18 15:39:24 -07:00
page . dashPick = entry ;
redraw ();
});
2026-11-17 18:08:01 -08:00
// "How the loop works" is a link of its own beside the card, never inside
// the button (a link in a button is not valid and reads badly aloud).
if ( entry . appOnly ) {
const wrap = el ( "div" , "dash-card-wrap" );
wrap . appendChild ( b );
2026-11-28 21:09:02 -08:00
wrap . appendChild ( loopHelpLink ( entry ));
2026-11-17 18:08:01 -08:00
return wrap ;
}
2026-10-18 15:39:24 -07:00
return b ;
}
2026-11-02 12:00:12 -08:00
// The loop card is lit only inside the desktop app and, there, by the same
// rule as Implement (a documented or building spec). Never recommended or
// pre-selected: a person opts into running unattended.
function loopPresentation ( entry , menu ) {
if ( ! page . inApp ) return { on : false , reason : OUTSIDE_APP_LINE , recommended : false , detail : "" };
2026-11-28 21:09:02 -08:00
if ( entry . skill === REVIEW_LOOP_SKILL && loopDriving ()) {
return { on : false , reason : "A loop is running. Stop it from the banner at the top of the window first." , recommended : false , detail : "" };
}
2026-11-02 12:00:12 -08:00
return { ... cardPresentation ( entry , scan (), selSpec (), menu ), recommended : false };
}
2026-11-17 18:08:01 -08:00
// "How the loop works" under the card: a real button styled as a link, a
// sibling of the card button inside its wrapper.
2026-11-28 21:09:02 -08:00
function loopHelpLink ( entry ) {
const review = entry && entry . skill === REVIEW_LOOP_SKILL ;
const a = el ( "button" , "dash-card-link" , review ? "How the Review Loop works" : "How the loop works" );
2026-11-17 18:08:01 -08:00
a . type = "button" ;
2026-11-28 22:29:52 -08:00
a . addEventListener ( "click" , () => hooks . openHelpOn ( review ? "review-loop" : "loop" ));
2026-11-02 12:00:12 -08:00
return a ;
}
2026-10-27 18:20:30 -07:00
// "Start with a note from your Notebook": the switch a lit card's confirm
// pane offers when noteSwitchShows() says so. The pane is rebuilt on every
// state frame, so what the person did lives here, keyed to the card and the
// picked spec it was done for: `on`, the tabs as read (`null` until then,
// each with its text and pictures once fetched), the picked tab and its
// ticked picture ids. `pick` is the pending pick Phase 2 reads at Start.
let note = null ;
const noteKey = ( entry ) => entry . skill + "|" + (( selSpec () && selSpec (). dir ) || "" );
function noteFor ( entry ) {
const key = noteKey ( entry );
if ( ! note || note . key !== key ) note = { key , on : false , tabs : null , failed : false , picked : null , ticked : [] };
return note ;
}
/**
* The tab the confirm pane has picked for this card, as `{ tab, name, text,
* images }` with only the ticked pictures, or null when the switch is off or
* no tab is picked.
*/
export function pendingNotePick ( entry ) {
if ( ! entry || ! note || note . key !== noteKey ( entry ) || ! note . on || ! note . picked || ! note . tabs ) return null ;
const tab = note . tabs . find (( t ) => t . id === note . picked );
if ( ! tab || ! tab . read ) return null ;
return {
tab : tab . id ,
name : tab . name ,
text : tab . read . text ,
images : tab . read . images . filter (( img ) => note . ticked . includes ( img . id )),
};
}
// Every tab, then each tab's text and pictures (the list shows an empty tab
// grayed, so each must be read). Read only: GET /notepad never writes.
async function readNoteTabs ( state ) {
try {
const res = await fetch ( "/notepad" , { cache : "no-store" });
if ( ! res . ok ) throw new Error ( String ( res . status ));
const body = await res . json ();
const tabs = Array . isArray ( body . tabs ) ? body . tabs : [];
const read = await Promise . all (
tabs . map ( async ( t ) => {
try {
const r = await fetch ( "/notepad?tab=" + encodeURIComponent ( t . id ), { cache : "no-store" });
if ( ! r . ok ) return null ;
const b = await r . json ();
return b && b . tab ? { text : typeof b . tab . text === "string" ? b . tab . text : "" , images : Array . isArray ( b . tab . images ) ? b . tab . images : [] } : null ;
} catch {
return null ;
}
}),
);
state . tabs = tabs . map (( t , i ) => ({ id : t . id , name : t . name , sent : t . sent || null , read : read [ i ] }));
state . failed = false ;
} catch {
state . tabs = [];
state . failed = true ;
}
}
// Read the tabs again (`fresh` shows "Reading…" meanwhile, for a first read).
// The pick survives only while its tab is still there with something in it,
// and its ticks only for pictures still in that tab, so what Start reads is
// never older than the last time the Notebook was closed.
async function refreshNoteTabs ( state , fresh = false ) {
if ( state . reading ) return ;
state . reading = true ;
if ( fresh ) {
state . tabs = null ;
redraw ();
}
await readNoteTabs ( state );
state . reading = false ;
const tab = state . tabs . find (( t ) => t . id === state . picked );
if ( ! tab || ! tab . read || noteTabEmpty ( tab . read )) {
state . picked = null ;
state . ticked = [];
} else {
const ids = tab . read . images . map (( img ) => img . id );
state . ticked = state . ticked . filter (( id ) => ids . includes ( id ));
}
// A state frame may have rebuilt the pane while the read was out, so the
// whole page redraws rather than a (perhaps detached) box.
if ( note === state ) redraw ();
}
// The switch, the tab list and the preview, drawn into `box`; `cmdNote` is the
// command line's `+ note: <tab>` span. Each change redraws only this box, so
// the rest of the pane (and the focus on it) stays put.
function drawNoteBox ( entry , box , cmdNote ) {
const state = noteFor ( entry );
const focusKey = document . activeElement && box . contains ( document . activeElement ) ? document . activeElement . dataset . noteFocus : null ;
const again = () => drawNoteBox ( entry , box , cmdNote );
box . replaceChildren ();
const label = el ( "label" , "confirm-note-switch" );
const toggle = el ( "input" );
toggle . type = "checkbox" ;
toggle . id = "confirm-note-switch" ;
toggle . dataset . noteFocus = "switch" ;
toggle . checked = state . on ;
toggle . addEventListener ( "change" , () => {
state . on = toggle . checked ;
again ();
if ( state . on && ( state . tabs === null || state . failed )) refreshNoteTabs ( state , true );
});
2026-11-02 12:00:12 -08:00
label . append ( toggle , el ( "span" , "confirm-note-switch-text" , "Start with a note from your Notebook" ));
// A callout row, so the switch stands out under the card's long text; the
// hint sits outside the label to keep the checkbox's name short.
2026-11-17 18:08:01 -08:00
const head = el ( "div" , "callout is-info confirm-note-head" + ( state . on ? " is-on" : "" ));
2026-11-02 12:00:12 -08:00
head . appendChild ( label );
if ( ! state . on ) {
const hint = el ( "span" , "confirm-note-hint" , "Hand it a tab you wrote earlier, with its pictures." );
hint . id = "confirm-note-hint" ;
toggle . setAttribute ( "aria-describedby" , hint . id );
head . appendChild ( hint );
}
box . appendChild ( head );
2026-10-27 18:20:30 -07:00
const picked = state . on && state . tabs ? state . tabs . find (( t ) => t . id === state . picked && t . read ) : null ;
cmdNote . textContent = picked ? " + note: " + picked . name : "" ;
cmdNote . hidden = ! picked ;
if ( ! state . on ) return ;
const wrap = el ( "div" , "confirm-note" );
if ( state . tabs === null ) {
wrap . appendChild ( el ( "p" , "confirm-note-msg" , "Reading your Notebook…" ));
} else if ( state . failed ) {
2026-11-17 18:08:01 -08:00
wrap . appendChild ( el ( "p" , "confirm-note-msg" , "Your Notebook could not be read." ));
const retry = el ( "button" , "btn xs soft confirm-note-retry" , "Try again" );
retry . type = "button" ;
retry . dataset . noteFocus = "retry" ;
retry . addEventListener ( "click" , () => refreshNoteTabs ( state , true ));
wrap . appendChild ( retry );
2026-10-27 18:20:30 -07:00
} else if ( ! state . tabs . length ) {
wrap . appendChild ( el ( "p" , "confirm-note-msg" , "Your Notebook has no tabs yet. Open it from the top bar to write one." ));
} else {
const list = el ( "div" , "confirm-note-tabs" );
list . setAttribute ( "role" , "group" );
list . setAttribute ( "aria-label" , "Notebook tabs" );
for ( const t of state . tabs ) {
const empty = ! t . read || noteTabEmpty ( t . read );
const b = el ( "button" , "confirm-note-tab" + ( t . id === state . picked ? " is-picked" : "" ));
b . type = "button" ;
b . dataset . noteFocus = "tab-" + t . id ;
b . disabled = empty ;
b . setAttribute ( "aria-pressed" , String ( t . id === state . picked ));
b . appendChild ( el ( "span" , "confirm-note-tab-name" , t . name ));
if ( t . sent ) {
2026-11-17 18:08:01 -08:00
const badge = el ( "span" , "pill is-accent notepad-sent-badge" , "previously sent" );
2026-10-27 18:20:30 -07:00
badge . setAttribute ( "aria-hidden" , "true" );
b . appendChild ( badge );
}
2026-11-02 12:00:12 -08:00
b . setAttribute ( "aria-label" , t . name + ( t . sent ? ", previously sent" : "" ) + ( empty ? ", empty" : "" ));
2026-10-27 18:20:30 -07:00
if ( empty ) b . title = t . read ? "This tab has no text or pictures." : "This tab could not be read." ;
b . addEventListener ( "click" , () => {
if ( state . picked === t . id ) return ;
state . picked = t . id ;
state . ticked = defaultNoteTicks ( t . read . images );
again ();
});
list . appendChild ( b );
}
wrap . appendChild ( list );
wrap . appendChild ( notePreview ( picked , state , again ));
}
box . appendChild ( wrap );
if ( focusKey ) {
const back = box . querySelector ( `[data-note-focus=" ${ focusKey } "]` );
if ( back && ! back . disabled ) back . focus ();
}
}
// The picked tab in full: a "Long tab" note over NOTE_LONG_BYTES, its text as
// Markdown, and its pictures, each with a tick (at most MAX_ATTACHMENTS).
function notePreview ( picked , state , again ) {
const pane = el ( "div" , "confirm-note-preview" );
pane . setAttribute ( "role" , "region" );
pane . setAttribute ( "aria-label" , "Preview of the picked tab" );
if ( ! picked ) {
pane . appendChild ( el ( "p" , "confirm-note-msg" , "Pick a tab to see it here." ));
return pane ;
}
const bytes = new TextEncoder (). encode ( picked . read . text ). length ;
if ( bytes > NOTE_LONG_BYTES ) pane . appendChild ( el ( "p" , "confirm-note-long" , "Long tab: " + formatBytes ( bytes )));
const text = el ( "div" , "confirm-note-text md" );
if ( picked . read . text . trim ()) mdInto ( text , picked . read . text );
else text . appendChild ( el ( "p" , "confirm-note-msg" , "No text, only pictures." ));
pane . appendChild ( text );
const images = picked . read . images ;
if ( images . length ) {
const full = state . ticked . length >= MAX_ATTACHMENTS ;
pane . appendChild (
el (
"p" ,
"confirm-note-msg" ,
images . length > MAX_ATTACHMENTS
? `Up to ${ MAX_ATTACHMENTS } pictures go with it. Untick one to tick another.`
: "Untick a picture to leave it out." ,
),
);
const strip = el ( "ul" , "confirm-note-pics" );
images . forEach (( img , i ) => {
const li = el ( "li" , "confirm-note-pic" );
const lab = el ( "label" );
const tick = el ( "input" );
tick . type = "checkbox" ;
tick . dataset . noteFocus = "pic-" + img . id ;
tick . checked = state . ticked . includes ( img . id );
tick . disabled = ! tick . checked && full ;
tick . setAttribute ( "aria-label" , `Picture ${ i + 1 } of ${ images . length } ` );
tick . addEventListener ( "change" , () => {
state . ticked = toggleNoteTick ( state . ticked , img . id );
again ();
});
const pic = el ( "img" );
pic . src = img . thumb || img . url ;
pic . alt = "" ;
pic . loading = "lazy" ;
lab . append ( tick , pic );
li . appendChild ( lab );
strip . appendChild ( li );
});
pane . appendChild ( strip );
}
return pane ;
}
2026-10-18 15:39:24 -07:00
// The confirm pane. A card or rail click lands here rather than launching
// straight away: picking a skill is the one irreversible-feeling click on the
// dashboard, and it deserves a beat: what it is, what it will do, and a
// START that means it. Planny turns up leaning (his "this way" pose) in a
// small sky, because a bare paragraph with two buttons is a dialog, not a
// moment. BACK returns to the menu; Escape does the same (see the global
// keydown in core.js).
export function renderConfirm ( main , entry ) {
const menu = ( page . S && page . S . menu ) || {};
const presentation = cardPresentation ( entry , scan (), selSpec (), menu );
const pane = el ( "div" , "dash-confirm" );
const stage = el ( "div" , "launch-stage confirm-stage" );
const sky = el ( "div" , "sky launch-sky" );
const r = ( a , b ) => a + Math . random () * ( b - a );
for ( let i = 0 ; i < 16 ; i ++ ) {
const star = el ( "i" , "star" + ( i % 5 === 0 ? " hot" : "" ));
const dur = r ( 4 , 10 );
star . style . setProperty ( "--y" , r ( 2 , 98 ). toFixed ( 1 ) + "%" );
star . style . setProperty ( "--p" , r ( 0 , 1 ). toFixed ( 3 ));
star . style . setProperty ( "--s" , r ( 1.2 , 2.4 ). toFixed ( 2 ) + "px" );
star . style . setProperty ( "--dur" , dur . toFixed ( 2 ) + "s" );
star . style . setProperty ( "--delay" , ( - r ( 0 , dur )). toFixed ( 2 ) + "s" );
sky . appendChild ( star );
}
stage . appendChild ( sky );
const bot = $ ( "planny" ). cloneNode ( true );
bot . removeAttribute ( "id" );
bot . setAttribute ( "class" , "planny is-point v0 confirm-planny" );
stage . appendChild ( bot );
pane . appendChild ( stage );
const head = el ( "div" , "confirm-head" );
2026-11-17 18:08:01 -08:00
head . appendChild ( el ( "span" , "pill is-neutral is-caps dash-chip" , entry . chip ));
if ( presentation . recommended ) head . appendChild ( el ( "span" , "pill is-accent is-caps suggested" , "Suggested" ));
2026-10-18 15:39:24 -07:00
pane . appendChild ( head );
pane . appendChild ( el ( "h2" , "dash-title" , entry . title ));
pane . appendChild ( el ( "p" , "confirm-about" , entry . about || entry . blurb ));
if ( presentation . detail ) pane . appendChild ( el ( "p" , "confirm-detail" , presentation . detail ));
// A card that takes a spec names the one the picker is holding, so START
// reads as "build THIS spec", not the skill in the abstract.
const target = launchTarget ( entry , selSpec ());
if ( target ) {
const specLine = el ( "p" , "confirm-spec" );
specLine . appendChild ( el ( "span" , null , "for " ));
specLine . appendChild ( el ( "code" , null , target . dir ));
specLine . appendChild ( el ( "span" , null , ` · ${ SPEC_STATE_LABELS [ target . state ] || target . state } ` ));
pane . appendChild ( specLine );
}
2026-10-19 15:56:52 -07:00
// Implement's card reviews the phase before sign-off unless this is unticked.
let review = null ;
if ( entry . review ) {
2026-10-19 17:55:37 -07:00
pane . appendChild ( el ( "hr" , "confirm-rule" ));
2026-10-19 15:56:52 -07:00
const label = el ( "label" , "confirm-review" );
review = el ( "input" );
review . type = "checkbox" ;
review . checked = page . dashReview !== false ;
review . addEventListener ( "change" , () => {
page . dashReview = review . checked ;
cmdCode . textContent = launchVariant ( entry , review . checked ). command ;
});
2026-11-17 18:08:01 -08:00
label . append ( review , el ( "span" , null , "Review each phase with a fresh agent before sign-off" ));
2026-10-19 15:56:52 -07:00
pane . appendChild ( label );
}
2026-10-27 18:20:30 -07:00
// The Notebook switch, on the cards and specs noteSwitchShows() names.
const cmdNote = el ( "span" , "confirm-cmd-note" );
cmdNote . hidden = true ;
if ( noteSwitchShows ( entry , scan (), selSpec ())) {
const box = el ( "div" , "confirm-note-box" );
// Which control in the box has the focus, so a rebuild of the whole pane
// can hand it back (see the end of this function).
box . addEventListener ( "focusin" , ( e ) => ( noteFor ( entry ). focus = e . target . dataset . noteFocus || null ));
box . addEventListener ( "focusout" , ( e ) => {
if ( e . relatedTarget && ! box . contains ( e . relatedTarget )) noteFor ( entry ). focus = null ;
});
drawNoteBox ( entry , box , cmdNote );
pane . appendChild ( box );
}
2026-11-03 10:24:34 -08:00
// The command line and the buttons ride in one bar (.confirm-tail) pinned
// to the pane's bottom edge: however tall the Notebook box makes this pane,
// START stays in view.
const tail = el ( "div" , "confirm-tail" );
2026-10-18 15:39:24 -07:00
const cmd = el ( "p" , "confirm-cmd" );
2026-10-19 15:56:52 -07:00
const cmdCode = el ( "code" , null , launchVariant ( entry , ! review || review . checked ). command );
cmd . appendChild ( cmdCode );
2026-10-27 18:20:30 -07:00
cmd . appendChild ( cmdNote );
2026-11-03 10:24:34 -08:00
tail . appendChild ( cmd );
2026-10-18 15:39:24 -07:00
const actions = el ( "div" , "confirm-actions" );
const start = el ( "button" , "btn primary" , "Start " + entry . title );
start . type = "button" ;
start . disabled = page . gone || page . pendingResult ;
2026-10-19 15:56:52 -07:00
start . addEventListener ( "click" , () => launchSkill ( launchVariant ( entry , Boolean ( review ) && review . checked )));
2026-10-18 15:39:24 -07:00
const back = el ( "button" , "btn ghost" , "Back" );
back . type = "button" ;
back . addEventListener ( "click" , () => {
page . dashPick = null ;
redraw ();
});
actions . appendChild ( back );
actions . appendChild ( start );
2026-11-03 10:24:34 -08:00
tail . appendChild ( actions );
pane . appendChild ( tail );
2026-10-18 15:39:24 -07:00
main . appendChild ( pane );
// Focus lands on START after a pick (the clicked control was rebuilt away,
// leaving focus on <body>), but never yanked back from a deliberate click
2026-10-27 18:20:30 -07:00
// elsewhere: a state frame can re-render this pane at any time. A control
// in the Notebook box gets its focus back instead.
if ( document . activeElement === document . body ) {
const held = note && note . key === noteKey ( entry ) && note . focus ? pane . querySelector ( `[data-note-focus=" ${ note . focus } "]` ) : null ;
( held && ! held . disabled ? held : start ). focus ();
}
2026-10-18 15:39:24 -07:00
}
// A pick is a send like a brief or a stop: it names no question, so `__launch`
// marks the action as being about the session, and it reaches the agent
// through the same wait loop. The dashboard reads `skill` off it.
2026-11-02 12:00:12 -08:00
export async function launchSkill ( entry ) {
2026-11-05 11:38:59 -08:00
if ( page . gone || page . pendingResult || page . local . launching || page . launchScoping || finish ()) return ;
2026-10-18 15:39:24 -07:00
const target = launchTarget ( entry , selSpec ());
// The card was clickable, so this should never fire — but a spec picked in
// one tab could have shifted the ground under a stale render in another.
if ( ! cardAvailability ( entry , scan (), selSpec ()). on ) {
2026-11-17 18:08:01 -08:00
hooks . banner ( "That skill is not available for the spec you picked." , "warn" );
2026-10-18 15:39:24 -07:00
redraw ();
return ;
}
page . dashPick = null ;
const action = {
i : "__launch" ,
type : "launch" ,
skill : entry . skill ,
workflow : entry . workflow ,
title : entry . title ,
};
// The picker's spec goes to the skill being launched, not to the card:
// cards that take no spec (utilities, setup) launch untargeted even while
2026-11-13 23:29:12 -08:00
// a spec is selected, save Quick Task on a diagnosed bug, an upgrade brief
// or a folder of saved prototypes (launchTarget).
2026-10-18 15:39:24 -07:00
if ( target ) action . spec = target . dir ;
2026-11-13 23:29:12 -08:00
// Launched from a dashboard showing lessons waiting: the skill's Start reads
// with --from-banner (shared-references/lessons.md).
if ( learningBannerText ( scan () && scan (). learning )) action . fromBanner = true ;
2026-10-27 18:20:30 -07:00
// A Notebook tab picked in the pane rides the hop in this page only, never
// on the action: the launched skill's `fill: "note"` box is filled from it
// (core.js), and the agent reads it only when that box is sent.
// Set either way, so a pick left from a launch that never hopped cannot
// fill this one.
const pick = pendingNotePick ( entry );
page . local . noteSend = pick
? {
tab : pick . tab ,
text : pick . text ,
pictures : pick . images . map (( img ) => img . id ),
workflow : entry . workflow ,
...( target ? { spec : target . dir } : {}),
}
: null ;
saveNow ();
2026-10-18 15:39:24 -07:00
// The skill opens on the folders remembered for what it was launched for.
// Held until the launch is in flight: the swap's own frame re-renders the
// dashboard, which would otherwise sync back to the picker's spec.
page . launchScoping = true ;
await hooks . syncWorkspaceScope ( target ? target . dir : "" );
try {
const res = await fetch ( "/submit" , {
method : "POST" ,
headers : { "content-type" : "application/json" },
body : JSON . stringify ({
actions : [ action ],
reply : launchReply ( entry , target ),
}),
});
if ( res . status === 409 ) {
page . launchScoping = false ;
2026-10-27 18:20:30 -07:00
dropNoteSend ();
2026-10-18 15:39:24 -07:00
page . pendingResult = true ;
hooks . banner ( "Your last pick is still being picked up. One moment." , "info" );
return ;
}
if ( ! res . ok ) throw new Error ( String ( res . status ));
sound ( "startSkill" );
2026-11-17 18:08:01 -08:00
// The first launch from this machine ends the first-run hold on the
// optional extras (never cleared, not even by Back to default).
if ( looks . skillLaunched !== true ) {
looks . skillLaunched = true ;
saveLooks ();
}
2026-10-18 15:39:24 -07:00
page . local . launching = { skill : entry . skill , title : entry . title , at : Date . now () };
page . launchScoping = false ;
page . pendingResult = true ;
saveNow ();
redraw ();
} catch {
page . launchScoping = false ;
2026-10-27 18:20:30 -07:00
dropNoteSend ();
2026-10-18 15:39:24 -07:00
hooks . banner ( "That did not go through. Nothing was lost; try again." , "warn" );
}
}
2026-10-27 18:20:30 -07:00
// A launch that did not go through takes no Notebook tab anywhere.
function dropNoteSend () {
if ( ! page . local . noteSend ) return ;
page . local . noteSend = null ;
saveNow ();
}
2026-10-18 15:39:24 -07:00
// The picker's Delete: a dialog in two steps. The first says what goes and
// that it is for good; "Delete this spec…" then reveals the second, which
// enables the final button only once the spec's name is typed exactly. A
// fixed bug skips the second step: its first press sends the delete.
// Cancel, Escape or a click on Keep it at either step changes nothing.
let deleteTarget = null ;
// The spec warning as index.html writes it, kept so a fixed bug's wording
// never sticks for the next spec.
let deleteWarnDefault = null ;
// A handoff's Delete reuses the same dialog in one step: no name to type, and
// the warning says where the file lives instead of what git does not track.
function openHandoffDelete ( h ) {
if ( page . gone || page . pendingResult || page . local . launching || page . local . deleting ) return ;
deleteTarget = { handoff : h };
$ ( "delete-title" ). textContent = "Delete this handoff?" ;
$ ( "delete-blurb" ). textContent = "This handoff will be deleted from ~/.plan2code/handoffs/." ;
$ ( "delete-warn" ). hidden = true ;
$ ( "delete-warn-handoff" ). hidden = false ;
const facts = $ ( "delete-facts" );
facts . replaceChildren ();
2026-11-17 18:08:01 -08:00
const fact = ( term , value , title ) => {
2026-10-18 15:39:24 -07:00
if ( ! value ) return ;
facts . appendChild ( el ( "dt" , "" , term ));
2026-11-17 18:08:01 -08:00
const dd = el ( "dd" , "" , value );
if ( title ) dd . title = title ;
facts . appendChild ( dd );
2026-10-18 15:39:24 -07:00
};
2026-10-19 15:56:52 -07:00
const entry = catalogEntry ( h . skill );
2026-10-18 15:39:24 -07:00
fact ( "Handoff" , h . title || h . id );
2026-11-17 18:08:01 -08:00
fact ( "Written" , h . written ? whenWords ( h . written ) : "" , h . written ? whenTitle ( h . written ) : "" );
2026-10-18 15:39:24 -07:00
fact ( "Spec" , h . spec ? h . spec . replace ( /^specs\// , "" ) : "" );
fact ( "From" , entry ? entry . title : h . skill );
$ ( "delete-confirm" ). hidden = true ;
const go = $ ( "delete-go" );
go . textContent = "Delete it" ;
go . classList . add ( "is-on" );
go . disabled = false ;
$ ( "delete-modal" ). showModal ();
}
function openDeleteConfirm ( spec ) {
if ( ! isDeletableSpecDir ( spec . dir ) || page . gone || page . pendingResult || page . local . launching || page . local . deleting ) return ;
deleteTarget = spec ;
2026-11-13 23:29:12 -08:00
// A finished spec (a fixed bug, a done upgrade): one confirm, and a warning that says so.
2026-10-18 15:39:24 -07:00
const fixed = Boolean ( stateFor ( spec . state ) ? . finished );
2026-11-13 23:29:12 -08:00
const done = spec . state === "upgraded" ? "The upgrade is done, so this only clears the brief. " : "The bug is fixed, so this only clears the write-up. " ;
2026-10-18 15:39:24 -07:00
$ ( "delete-title" ). textContent = "Delete this spec?" ;
const warn = $ ( "delete-warn" );
if ( ! deleteWarnDefault ) deleteWarnDefault = [... warn . childNodes ]. map (( n ) => n . cloneNode ( true ));
warn . replaceChildren (
...( fixed
2026-11-13 23:29:12 -08:00
? [ done , el ( "code" , "" , "specs/" ), " is not tracked by git, so it cannot be brought back." ]
2026-10-18 15:39:24 -07:00
: deleteWarnDefault . map (( n ) => n . cloneNode ( true )))
);
warn . hidden = false ;
$ ( "delete-warn-handoff" ). hidden = true ;
const sum = deleteSummary ( spec );
$ ( "delete-blurb" ). textContent = `Everything in ${ sum . folder } will be deleted from this project.` ;
const facts = $ ( "delete-facts" );
facts . replaceChildren ();
2026-11-17 18:08:01 -08:00
const fact = ( term , value , title ) => {
2026-10-18 15:39:24 -07:00
if ( ! value ) return ;
facts . appendChild ( el ( "dt" , "" , term ));
2026-11-17 18:08:01 -08:00
const dd = el ( "dd" , "" , value );
if ( title ) dd . title = title ;
facts . appendChild ( dd );
2026-10-18 15:39:24 -07:00
};
fact ( "Spec" , spec . name );
fact ( "Folder" , sum . folder );
fact ( "Stage" , sum . stage );
fact ( "Files" , sum . files );
2026-11-17 18:08:01 -08:00
fact ( "Last changed" , sum . touched ? whenWords ( sum . touched ) : "" , sum . touched ? whenTitle ( sum . touched ) : "" );
2026-10-18 15:39:24 -07:00
$ ( "delete-name-hint" ). textContent = spec . name ;
$ ( "delete-name" ). value = "" ;
$ ( "delete-confirm" ). hidden = true ;
const go = $ ( "delete-go" );
go . textContent = fixed ? "Delete it" : "Delete this spec…" ;
go . classList . toggle ( "is-on" , fixed );
go . disabled = false ;
$ ( "delete-modal" ). showModal ();
}
function deleteStep () {
const go = $ ( "delete-go" );
if ( ! deleteTarget ) return ;
if ( deleteTarget . handoff ) return sendDeleteHandoff ( deleteTarget . handoff );
if ( stateFor ( deleteTarget . state ) ? . finished ) return sendDelete ( deleteTarget );
if ( $ ( "delete-confirm" ). hidden ) {
$ ( "delete-confirm" ). hidden = false ;
go . textContent = "Delete for good" ;
go . classList . add ( "is-on" );
go . disabled = true ;
$ ( "delete-name" ). focus ();
return ;
}
if ( $ ( "delete-name" ). value . trim () !== deleteTarget . name ) return ;
sendDelete ( deleteTarget );
}
async function sendDeleteHandoff ( h ) {
const go = $ ( "delete-go" );
go . disabled = true ;
try {
const res = await fetch ( "/submit" , {
method : "POST" ,
headers : { "content-type" : "application/json" },
body : JSON . stringify ({ actions : [ deleteHandoffAction ( h )], reply : deleteHandoffReply ( h ) }),
});
if ( res . status === 409 ) throw Object . assign ( new Error ( "pending" ), { pending : true });
if ( ! res . ok ) throw new Error ( String ( res . status ));
const sc = scan ();
page . local . deleting = { dir : "handoff:" + h . id , scanAt : sc ? sc . at : null };
if ( page . local . specSel === "handoff:" + h . id ) delete page . local . specSel ;
page . pendingResult = true ;
saveNow ();
$ ( "delete-modal" ). close ();
} catch ( err ) {
$ ( "delete-modal" ). close ();
if ( err && err . pending ) page . pendingResult = true ;
hooks . banner (
err && err . pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again." ,
"warn"
);
} finally {
deleteTarget = null ;
redraw ();
}
}
async function sendDelete ( spec ) {
const go = $ ( "delete-go" );
go . disabled = true ;
try {
const res = await fetch ( "/submit" , {
method : "POST" ,
headers : { "content-type" : "application/json" },
body : JSON . stringify ({ actions : [ deleteAction ( spec )], reply : deleteReply ( spec ) }),
});
if ( res . status === 409 ) throw Object . assign ( new Error ( "pending" ), { pending : true });
if ( ! res . ok ) throw new Error ( String ( res . status ));
const sc = scan ();
page . local . deleting = { dir : spec . dir , scanAt : sc ? sc . at : null };
// The selection must not outlive the folder: back to the default pick,
// which the agent's fresh menu recommends for.
if ( page . local . specSel === spec . dir ) delete page . local . specSel ;
page . pendingResult = true ;
saveNow ();
$ ( "delete-modal" ). close ();
} catch ( err ) {
$ ( "delete-modal" ). close ();
if ( err && err . pending ) page . pendingResult = true ;
hooks . banner (
err && err . pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again." ,
"warn"
);
} finally {
deleteTarget = null ;
redraw ();
}
}
2026-11-13 23:29:12 -08:00
// The Learning banner above the title, or null: only while lessons wait and
// Learning is on or not set up. Review sends the __learning action.
function learningBanner ( sc ) {
2026-11-14 23:05:35 -08:00
const state = sc && sc . learning && sc . learning . state ;
const busy = learningBusyNow ( state );
// Review pressed, or the choices just saved: the banner says what the agent
// is doing, in the same place, so the wait is never silent.
2026-11-27 23:19:42 -08:00
const working = busy && ( busy . what === "review" || busy . what === "decide" || busy . what === "tidy" ) ? busy : null ;
2026-11-13 23:29:12 -08:00
const text = learningBannerText ( sc && sc . learning );
2026-11-27 23:19:42 -08:00
const nudge = learningNearCapText ( sc && sc . learning );
if ( ! text && ! nudge && ! working ) return null ;
2026-11-17 18:08:01 -08:00
const banner = el ( "div" , "callout is-info dash-nudge learn-banner" );
2026-11-13 23:29:12 -08:00
banner . setAttribute ( "role" , "status" );
2026-11-14 23:05:35 -08:00
if ( working ) {
banner . classList . add ( "is-busy" );
banner . setAttribute ( "aria-busy" , "true" );
const line = el ( "span" , "dash-nudge-text learn-busy" );
2026-11-27 23:19:42 -08:00
line . append ( el ( "span" , "spinner tiny" ), document . createTextNode ( working . what === "review" ? "Opening lessons…" : working . what === "tidy" ? "Looking over your lessons…" : "Saving your lessons…" ));
2026-11-14 23:05:35 -08:00
banner . appendChild ( line );
if ( working . what === "review" ) {
2026-11-17 18:08:01 -08:00
const review = el ( "button" , "btn sm primary" , "Review" );
2026-11-14 23:05:35 -08:00
review . type = "button" ;
review . disabled = true ;
banner . appendChild ( review );
}
return banner ;
}
2026-11-13 23:29:12 -08:00
const why = hooks . learningBlocked ();
2026-11-27 23:19:42 -08:00
// Each line is its own row with its own button: lessons waiting, and lessons near their limit.
const row = ( words , label , what , primary ) => {
const r = el ( "div" , "learn-banner-row" );
r . appendChild ( el ( "span" , "dash-nudge-text" , words ));
const b = el ( "button" , "btn sm" + ( primary ? " primary" : "" ), label );
b . type = "button" ;
b . disabled = Boolean ( why );
if ( why ) b . title = why ;
b . addEventListener ( "click" , () => sendLearning ( what ));
r . appendChild ( b );
banner . appendChild ( r );
};
if ( text ) row ( text , "Review" , "review" , true );
if ( nudge ) row ( nudge , "Tidy up" , "tidy" , ! text );
2026-11-13 23:29:12 -08:00
return banner ;
}
2026-11-14 23:05:35 -08:00
// The agent finishing with nothing to show ends the wait early: a Review whose
// card never came (the banner was stale) says so at once instead of spinning
// to the limit, and a saved choice stops when the agent is back to waiting.
// `seen` waits for the send to be picked up first (or three seconds), so the
// gap before the agent collects it is not read as "finished".
function watchLearningBusy ( busy ) {
const timer = setInterval (() => {
if ( page . learningBusy !== busy ) return clearInterval ( timer );
2026-11-27 23:19:42 -08:00
if ( Date . now () - busy . at > learningBusyLimit ( busy )) {
2026-11-14 23:05:35 -08:00
clearInterval ( timer );
page . learningBusy = null ;
redraw ();
return ;
}
if ( page . pendingResult || agentWorking ()) {
busy . seen = true ;
return ;
}
// Idle and never seen busy: the agent was quicker than the page's poll
// (or the send is a moment from being picked up), so give it three seconds.
if ( ! busy . seen && Date . now () - busy . at < 3000 ) return ;
clearInterval ( timer );
page . learningBusy = null ;
2026-11-27 23:19:42 -08:00
if ( busy . what === "review" || busy . what === "tidy" ) {
const none = hooks . banner ( busy . what === "tidy" ? "Nothing to tidy up right now." : "No lessons are waiting any more." , "info" );
2026-11-17 18:08:01 -08:00
setTimeout (() => hooks . clearBanner ( none ), 4000 );
2026-11-14 23:05:35 -08:00
}
redraw ();
}, 400 );
}
/**
* The lessons dialog's Save lessons went through: the banner's place says
* "Saving your lessons…" until the agent is done with the choices.
*/
export function beginLearningSave () {
const sc = scan ();
const busy = { what : "decide" , from : sc && sc . learning && sc . learning . state , at : Date . now (), seen : false };
page . learningBusy = busy ;
watchLearningBusy ( busy );
setTimeout ( redraw , LEARNING_BUSY_MS + 500 );
redraw ();
}
2026-11-13 23:29:12 -08:00
// A Learning control that changes the project: a __learning action to the
// dashboard agent, posted the way sendDelete() posts. No hop: the agent runs
// lessons.mjs, rescans and posts the menu again.
export async function sendLearning ( what ) {
if ( hooks . learningBlocked ()) return ;
2026-11-14 23:05:35 -08:00
// Switching on or off, or opening Review, shows as working at once, before
// the agent answers.
2026-11-14 10:42:23 -08:00
const sc = scan ();
const from = sc && sc . learning && sc . learning . state ;
2026-11-27 23:19:42 -08:00
if (( what === "switch-on" || what === "switch-off" || what === "review" || what === "tidy" ) && from ) {
2026-11-14 23:05:35 -08:00
const busy = { what , from , at : Date . now (), seen : false };
page . learningBusy = busy ;
2026-11-14 10:42:23 -08:00
redraw ();
2026-11-14 23:05:35 -08:00
// One redraw at the limit, so an action the agent never answers stops spinning.
setTimeout ( redraw , LEARNING_BUSY_MS + 500 );
2026-11-27 23:19:42 -08:00
if ( what === "review" || what === "tidy" ) watchLearningBusy ( busy );
2026-11-14 10:42:23 -08:00
}
2026-11-13 23:29:12 -08:00
try {
const res = await fetch ( "/submit" , {
method : "POST" ,
headers : { "content-type" : "application/json" },
body : JSON . stringify ({ actions : [ learningAction ( what )], reply : learningReply ( what ) }),
});
if ( res . status === 409 ) throw Object . assign ( new Error ( "pending" ), { pending : true });
if ( ! res . ok ) throw new Error ( String ( res . status ));
page . pendingResult = true ;
saveNow ();
} catch ( err ) {
2026-11-14 10:42:23 -08:00
page . learningBusy = null ;
2026-11-13 23:29:12 -08:00
if ( err && err . pending ) page . pendingResult = true ;
hooks . banner (
err && err . pending
? "Your last pick is still being picked up, so that could not go yet. Try again in a moment."
: "That did not go through. Nothing changed; try again." ,
"warn"
);
} finally {
redraw ();
}
}
2026-10-18 15:39:24 -07:00
// The dialogs' buttons, wired once at start-up: the update notice's Done, the
// handoff preview's close, and the delete dialog's Cancel, name box and go.
export function wireDashboard () {
2026-10-27 18:20:30 -07:00
// Closing the Notebook over an open confirm pane with the switch on reads
// the tabs again, so an edit or a delete made there shows in the preview.
$ ( "notepad-modal" ). addEventListener ( "close" , () => {
if ( note && note . on && page . dashPick ) refreshNoteTabs ( note );
});
2026-10-18 15:39:24 -07:00
$ ( "update-done" ). addEventListener ( "click" , () => $ ( "update-modal" ). close ());
$ ( "delete-cancel" ). addEventListener ( "click" , () => $ ( "delete-modal" ). close ());
$ ( "handoff-close" ). addEventListener ( "click" , () => $ ( "handoff-modal" ). close ());
2026-10-23 10:04:13 -07:00
lightDismiss ( $ ( "handoff-modal" ));
2026-10-18 15:39:24 -07:00
$ ( "delete-go" ). addEventListener ( "click" , deleteStep );
$ ( "delete-name" ). addEventListener ( "input" , () => {
$ ( "delete-go" ). disabled = ! deleteTarget || $ ( "delete-name" ). value . trim () !== deleteTarget . name ;
});
$ ( "delete-name" ). addEventListener ( "keydown" , ( e ) => {
if ( e . key === "Enter" ) {
e . preventDefault ();
2026-11-05 11:38:59 -08:00
if ( ! $ ( "delete-go" ). disabled ) deleteStep ();
2026-10-18 15:39:24 -07:00
}
});
2026-10-26 21:43:53 -07:00
// `close` is queued, so it can land after the dialog was opened again for
// another spec; that new target must survive it.
2026-10-18 15:39:24 -07:00
$ ( "delete-modal" ). addEventListener ( "close" , () => {
2026-10-26 21:43:53 -07:00
if ( ! $ ( "delete-modal" ). open ) deleteTarget = null ;
2026-10-18 15:39:24 -07:00
});
}