Commit Graph
13519 Commits
Author SHA1 Message Date
Diego Imbert 03c236ea2f feat(drafts): wire Ctrl/Cmd+S to flush the pending autosave immediately
Each builder already had a Ctrl/Cmd+S keybinding routed through a
saveDraft() no-op left over from the LS-era — the comment said
"persistence happens via the page-level UserDraft autosave" but the
shortcut was the user's only way to actually force a save without
waiting for the 1.5s debounce. Restore the intent.

* UserDraftDbSyncer.flush({ workspace, itemKind, path }) — new method
  that re-submits whatever's queued in pendingSaveOpts with
  immediate: true. No-op when nothing's pending.

* Editor.svelte.flushPendingChanges() — exposes a synchronous
  updateCode() with chain reset, so callers can drain Monaco's own
  trailing debounce before asking the syncer to flush. Without this
  step a Ctrl+S within ~500ms of typing would POST the pre-burst
  content.

* ScriptBuilder.saveDraft() — editor?.flushPendingChanges() →
  await tick() → UserDraftDbSyncer.flush(). Toast on result.
* FlowBuilder.saveDraft() — no direct Monaco ref (flows have many
  per-module editors); just flushes the syncer. Editor.svelte's new
  1s max-wait cap means at most the last <1s of typing in a module
  Monaco won't be in this POST; it follows in the next autosave
  round.
* RawAppEditor.handleKeydown — adds a 's' case that flushes before
  the focus guard, so the shortcut fires regardless of where focus
  is in the editor pane.
2026-06-09 12:41:41 +02:00
Diego Imbert 41241dd1fd fix(editor): leading-edge fire + max-wait cap on Monaco debounce
The Editor debounced `onDidChangeModelContent` purely on the trailing
edge — every keystroke rescheduled a 500ms timer, and uninterrupted
typing held the bindable `code` prop stale until a pause. Stacked
behind our 1.5s autosave debouncer that meant our clock didn't even
start ticking until 500ms after the user paused, and the `code`
binding never updated mid-burst for downstream consumers (lint,
live preview, change listeners).

Switch to leading + trailing + max-wait:

* First keystroke of a burst fires `updateCode` synchronously, then
  stamps a wall-clock chain start.
* Each subsequent keystroke (re)arms a trailing timer at
  `min(now + changeTimeout, chainStart + maxChangeTimeout)` — the cap
  is what makes continuous typing materialize at least once per
  maxChangeTimeout window instead of indefinitely.
* When the trailing fires it resets the chain so the next keystroke
  after a pause is a fresh leading fire.

New prop `maxChangeTimeout` (default 1000ms) sits next to the
existing `changeTimeout` (default 500ms). Dispose path clears the
chain stamp alongside the timer.
2026-06-09 12:30:01 +02:00
Diego Imbert cd746e366f Merge origin/main into remove-workspace-drafts
Resolve three conflicts + adapt the workspace-drafts feature to the
per-user model:

* RawAppEditorHeader.svelte: keep our pendingDraftPath + onResetToDeployed
  props; drop main's onSaveDraft prop (dead in the per-user model — saves
  flow through UserDraftDbSyncer's autosave, no explicit "save draft"
  button exists anymore).

* ScriptEditorView.svelte's restoreDeployed: keep main's
  invalidateWorkspaceDrafts call but route the actual delete through our
  UserDraftDbSyncer.save({value: null}) instead of main's
  DraftService.deleteDraft (the workspace-draft endpoint no longer
  exists). Drop SessionItemNotFound import that was leftover from a HEAD
  refactor and never wired.

* sessionRuntime.svelte.ts: keep our SavedFlow/SavedScript types
  (Omit<X & UserDraftOverlay, 'draft'> & { draft? }) over main's
  NewScriptWithDraft / (Flow & { draft? }) shapes — the former carry the
  full overlay (is_draft, draft_saved_at, no_deployed, other_drafts_users)
  the editor reads. Adopt main's LoadSlot consolidation (single scriptSlot
  object replaces three vars + drops three dead getters from the
  interface that no consumer reads).

Cleanup the user flagged:

* Remove onSaveDraft prop + bind from RawAppEditor.svelte; ScriptBuilder
  and FlowBuilder never had it. Strip the dead onSaveDraft callbacks
  from ScriptEditorView, FlowEditorView, RawAppEditorView. In our model
  the editor auto-saves through UserDraftDbSyncer; there is no
  user-triggered save-draft event to fire.

* utils_draft_deploy.ts + rawAppDeploy.ts + CompareDrafts.svelte:
  replace main's new getXByPathWithDraft endpoints (workspace-draft
  variant we don't have) with our getXByPath({getDraft: true}). The
  WithDraftOverlay response shape is structurally compatible (.draft
  sub-object); strip the overlay markers (is_draft / draft_saved_at /
  no_deployed / other_drafts_users) on the deployed side so the
  DiffDrawer's cleanValueProperties doesn't render them as noise.

* utils_draft_deploy.ts's discardDraft: route the non-draft_only branch
  through UserDraftDbSyncer.save({value: null}) instead of
  DraftService.deleteDraft. Per-user semantics match what the workspace
  draft list (include_draft_only) returns — the user's own drafts.

ChatContextPicker.svelte: `DrillPicker<ChatLeafData>` doesn't compile
under Svelte 5's emitted Component type. Swap for
`ReturnType<typeof DrillPicker>` — `inner` is only used for
handleKeydown, the generic isn't needed at the binding site.
2026-06-09 08:17:37 +02:00
Ruben FiszelandClaude Opus 4.8 92c21bbe65 fix: drop archived items from fork compare (spurious 'not visible' warning) (#9481)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 22:45:18 +00:00
Ruben FiszelandClaude Opus 4.8 5f41ddd3a5 fix: require auth to view approval details when user_auth_required (#9482)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 22:26:19 +00:00
GuilhemandClaude Opus 4.8 b0b330c786 feat: deployed↔draft compare + AI-session draft bar (#9435)
* feat: deployed↔draft compare for current workspace + session draft bar

Add a "Deployed ↔ draft" comparison alongside the existing fork-vs-parent
compare flow, and surface drafts in the AI session UI.

- Merge the fork-direction toggle (Deploy to parent / Update current) and
  the new deployed↔draft mode into one 3-way CompareModeToggle, rendered
  inside the comparison card. Hidden in non-fork workspaces (draft only).
- CompareDrafts: list/deploy/discard server drafts (scripts, flows, apps
  incl. raw apps) via shared WorkspaceDeployLayout.
- Session draft bar (SessionDraftBar) mirrors the fork bar, only visible
  when drafts exist; its diff button opens the shared read-only diff
  drawer extracted as WorkspaceDiffDrawer (ForkDiffDrawer + DraftDiffDrawer
  are thin wrappers over it).
- WorkspaceDraftsBanner: home banner linking to draft review.
- Backend: GET /drafts/count endpoint for the draft-count badge.
- Raw app draft deploy (rawAppDeploy.ts) + vite /ui_builder proxy headers
  so the bundler iframe loads cross-origin.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: refine draft/fork compare toggle UX

Follow-up polish on the merged deploy/draft compare control:

- Relabel the draft toggle to "Deploy draft (N)" and show per-direction
  counts on all three toggle buttons (deployable / updateable / drafts),
  suppressed when zero. Counts are computed page-side so they persist in
  draft mode too.
- Warn before deploying to the parent when the fork has undeployed drafts
  ("Only deployed versions in this fork can be sent to {parent} …") with a
  one-click link to the draft view; milder note in the update direction.
- Show an empty-state message per direction ("Nothing to update — this
  fork is up to date with {parent}") instead of a table of greyed,
  non-actionable rows; hide the deploy/update button in that case.
- Drop the standalone "Pending drafts" info alert from the draft list.
- Align the fork "Show diff" button to the non-deprecated Button API
  (unifiedSize, onClick, startIcon) so it matches the draft one; mark
  "Discard draft" destructive.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: link compare row titles to the item editor

- Render each compare row title (fork and draft) as a link that opens the
  item in a new tab, scoped to the current workspace (raw apps route to
  /apps_raw/edit), matching the AI-session diff drawer: target=_blank, hover
  underline + ExternalLink icon, click stops row-selection propagation.
  Kinds without an editor stay plain; the fork rename markup is preserved.
- Drop the "Kind → name" prefix from draft rows — that arrow reads as the
  rename visual and the kind is already shown by the row icon.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: clickable rows + multi-select in deploy layout

- Make deploy-layout row cards selectable on click via an opt-in
  `selectOnRowClick` prop on the shared Row (default off, other tables
  unaffected); clicks on the checkbox, title link and action buttons are
  ignored. Adds role/tabindex + Enter/Space keyboard support.
- Support multi-select with modifier keys like classic list pickers:
  Shift+click selects the contiguous range from the anchor row; Cmd/Ctrl
  (and plain) click toggles a single row. select-none avoids text
  highlighting on shift-click.
- Turn the "Select all" text into a <label> associated with its checkbox
  so clicking the text toggles it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: select all drafts by default in draft compare

Drafts now load pre-selected (deploy-all is the common intent); guarded so
a reload after a deploy doesn't re-select the items left behind. Mirrors
CompareWorkspaces' default auto-selection.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: show diff for draft-only items stored without a draft row

A draft_only flow/script/app whose content lives in the entity row itself
(created via create*(draft_only: true), no separate draft-table row — like
u/admin/new) returns draft == null from get*ByPathWithDraft. getDraftDiffValues
passed that null through, so the diff "after" side was empty and nothing
rendered. Fall back to the row's own value as the draft content when draft is
null (deployDraft already did this), fixing both the compare-page DiffDrawer
and the session bars' WorkspaceDiffDrawer.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: shared diff button across session bars + bar spacing

- Extract SessionDiffButton (variant=default, ± DiffIcon, count, "Open diff"
  title) and use it for the diff-drawer trigger in both the fork bar and the
  draft bar, so they're identical. Drop the icons from both "Review" buttons.
- Add gap-1 (4px) between the fork bar and draft bar when both are visible
  (flex wrapper; single in-flow root per bar, drawer is portalled — no stray
  gap when only one shows).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: deploying a new (draft-only) flow or app

A draft_only flow/app already has an entity row (created via
create*(draft_only: true)), so deployDraft's createFlow/createApp rejected it
with 400 "already exists". Use updateFlow/updateApp instead — a listed draft
always has a row, and update promotes a draft_only entity to a real deployed
version (clearing the flag), like the editor does. Scripts were unaffected
(createScript + parent_hash makes a new version).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: refresh fork comparison after deploying/discarding a draft

Deploying a draft promotes it to the workspace's deployed version, changing
the fork comparison (ahead/behind vs parent) — but the compare page only
re-fetched it on workspace change, so the deploy/update toggle counts and the
CompareWorkspaces tab went stale. CompareDrafts now fires onChanged after a
successful deploy/discard; the page rewires it to refresh the comparison and
draft count.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: stop draft-count effect from freezing the AI session page

ensureDraftCount cleared its dedupe key on error; since the caller is a reactive $effect (SessionDraftBar), a persistently-failing countDrafts spun the effect into an infinite retry loop that flooded the console and froze the tab. Claim the key before awaiting and keep it set on failure; refresh*() still forces a re-fetch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: correct draft count and refresh compare counts after actions

count_drafts now counts deployable drafts (draft_only OR has-a-draft-row across script/flow/app), matching the CompareDrafts list, instead of raw draft-table rows which miss new draft-only items. CompareWorkspaces and CompareDrafts fire onChanged so the compare page re-fetches the comparison and draft count after deploy/update/discard, keeping the toggle badges in sync.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: session draft bar shows a fresh count on every (re)open

The runtime persists across client-side navigation, so the deduped
ensureDraftCount() kept a stale count (e.g. a 0 cached before a draft was
created) when a session was re-opened — the bar stayed hidden even though
the server count was >0.

Force one fresh fetch per mount from a non-reactive onMount via
refreshDraftCount(workspace) (which now takes the workspace so it works
before the dedupe key is set). The reactive $effect keeps using
ensureDraftCount: refreshDraftCount reads loadingDraftCount ($state), so
calling it from an effect would track-and-mutate that state into an
infinite fetch loop — ensureDraftCount's plain-key early-return avoids it.
ensureDraftCount also now releases its key after a 5s backoff on failure so
a transient countDrafts error retries instead of leaving the bar stuck.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: make the draft count a single deep Workspace Drafts module

The Draft Count was computed four ways (backend count_drafts SQL, the
CompareDrafts list filter, a bespoke sessionRuntime cache, and the compare
page state) that drifted — the root cause of the unreliable count, the
stale-on-reopen bug, and the effect-loop freeze.

Introduce one module (workspaceDrafts.svelte.ts):
- getDraftItems(ws) lists the deployable Draft Items once; count ≡ list length,
  never a separate query.
- useWorkspaceDrafts(() => ws) is a component-scoped runed resource (fetches on
  mount + ws change, no persistent cache → fresh on every (re)open).
- invalidateWorkspaceDrafts(ws) refreshes mounted consumers; deployDraft/
  discardDraft self-invalidate, so callers never reason about staleness.

Rewire every reader to it (SessionDraftBar, CompareDrafts, DraftDiffDrawer,
WorkspaceDraftsBanner, compare page) and delete the sessionRuntime draftCount
apparatus (key + loading flag + 4 methods + effects + backoff). With no caller
left, remove the count_drafts endpoint (handler, route, openapi, sqlx cache,
generated client) — drafts.rs/openapi return to their main state. Record the
draft vocabulary in CONTEXT.md.

A single GET /w/{ws}/drafts/items endpoint can later replace getDraftItems'
three list calls behind the unchanged seam.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: warn before deploying a draft based on an outdated version

When a newer version is deployed while a draft exists (git-sync/CLI deploys preserve drafts via skip_draft_deletion), the compare/deploy-drafts page now flags the draft as Outdated and gates deploy behind an override confirmation with a diff — instead of silently clobbering the newer version. Staleness is read from the draft's base version: scripts already store parent_hash; flows/apps now record a draft_base_version sidecar on save.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop redundant /ui_builder proxyRes hack (superseded by #9433)

main's global configure-response-headers plugin now runs with enforce:'pre'
and sets COOP/COEP/CORP on dev responses (#9433), so the per-proxy proxyRes
override is no longer needed. Revert the /ui_builder block to main's headers
form — vite.config.js now matches main with no branch-specific change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(sessions): keep draft count reactive to preview/chat deploys

Invalidate the Workspace Drafts resource at every frontend deploy seam
(ScriptEditorView / FlowEditorView / RawAppEditorView onDeploy + onSaveDraft)
so user-driven deploys from the Preview panel update the count immediately,
and refresh SessionDraftBar on the same coarse signals SessionForkBar uses
(AI turn-end + tab refocus) to cover chat-driven deploys that happen
server-side and never surface as frontend calls.

Also: always show the draft toggle count including (0) on the compare page,
drop the header/content separator line in both compare cards, and derive the
"Deploy N drafts" footer count so it stays reactive after discard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: address branch review findings

- WorkspaceDraftsBanner: use the modern Button API (variant/unifiedSize/onclick)
  instead of the deprecated size/color/on:click triad; drop "pending" from the
  banner copy to match CONTEXT.md vocabulary.
- WorkspaceDeployLayout: make Cmd/Ctrl-click distinct from a plain click.
  Plain row click now selects only that row (classic file-picker), Cmd/Ctrl
  toggles, Shift extends the range, and the checkbox still plain-toggles.
  Adds an onSelectOnly callback wired in CompareDrafts/CompareWorkspaces.
- WorkspaceDiffDrawer: document why the file filter is a raw input (bespoke
  keyboard-nav integration the design-system inputs can't express).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* revert: drop draft version-gating (stale-draft warning)

Remove the "deploying an outdated draft would override a newer version"
guard. It's a rare edge case and will be handled properly by conflict
resolution in a follow-up PR.

- CompareDrafts: drop staleMap/computeStaleness, the TOCTOU pre-deploy
  re-check, the "Outdated" badge, the override-in-diff button, and the
  "Newer version deployed" confirmation modal; deploySelected is now the
  plain deploy.
- utils_draft_deploy: remove getDraftStaleness/DraftStaleness and the
  draft_base_version strip.
- FlowBuilder / AppEditorHeader / RawAppEditorHeader / AppJsonEditor: stop
  injecting draft_base_version into draft saves — these editor paths are
  back to matching main, shrinking the PR's blast radius.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* style: unify home banner CTAs on the modern Button API

Both the Workspace Drafts banner and the sibling Fork banner now use
variant="default" unifiedSize="sm" onclick, so the two CTAs on the home
page render identically and neither uses the deprecated size/color/on:click
props.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(compare): show draft deploy direction badge inside forks

Mirror the fork compare header's "from → into" badges on the Deploy-draft
tab: "deploy: draft → into: <fork>". Makes it explicit that deploying a
draft promotes it within the fork (deployed↔draft), not up to the parent.
Only rendered inside forks, where the parent could otherwise be confused
with the deploy target.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(compare): address PR review — dedup drafts resource + shared link

- De-dupe the compare page Workspace Drafts fetch: the page owns the single
  resource and passes draftItems/draftsLoading into CompareDrafts (was mounting
  a second resource → 6 list calls; now 3).
- Prune transient deploymentStatus for items dropped from the list (no unbounded
  growth, no stale 'deployed' suppressing a re-drafted row).
- Type getDraftItems' list fields via a narrow DraftListEntry (drop Array<any>).
- Clear comparison catch-up timers on unmount (onDestroy).
- Extract shared ExternalEditLink.svelte; use it in CompareDrafts,
  CompareWorkspaces, WorkspaceDiffDrawer (was a near-verbatim <a> block x3).
- Note conflicts intentionally count in both toggle directions; drop a stray
  blank line in sessionRuntime.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(compare): show draft summary renames via shared item-summary component

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(compare): address round-2 PR review

- Point the fork-compare edit link at the workspace the item actually lives
  in: a parent-only row (absent in the fork) would 404 if linked into the
  fork, so link it into the parent instead.
- Replace the bespoke raw <button class="underline">Deploy drafts</button> in
  the undeployed-drafts alert with a design-system Button (variant=subtle).
- Drop the stray Prettier reflow in sessionRuntime (restore to match main).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(compare): warn on fork items with a pending draft

In the fork compare list, items that are deployed *and* have a pending
draft (has_draft) now:
- show a yellow "+Draft" badge (AlertTriangle), rendered before the
  New/status badges, with a per-direction tooltip explaining that
  deploying/updating moves the deployed version, not the draft;
- are excluded from the default selection (still manually selectable);
- trigger a confirmation modal if explicitly selected and deployed/updated,
  listing the affected paths.

The signal comes from the page's existing fork drafts resource (a
kind:path Set passed down) — no new fetch, no backend change. Also rename
the undeployed-drafts alert CTA from "Deploy drafts" to "See drafts".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(compare): rename page to "Compare & Deploy"

Update both the page heading (PageHeader) and the browser-tab title.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(compare): multi-select rows by default (no modifier)

In the shared WorkspaceDeployLayout (fork + draft lists), a plain row
click now toggles the item in/out of the selection instead of replacing
the whole selection with it. Removed the modifier-based selection
entirely: the now-dead onSelectOnly path and its two call sites, plus
shift+click range selection (and its anchor/isPickable helpers).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(table): don't toggle row selection on keyboard child activation

Row's onkeydown selection handler lacked the interactive-child guard that
handleRowClick already had, so pressing Enter/Space on a checkbox, action
button, or title link both activated the child and toggled the row's
selection. Extract a shared fromInteractiveChild() guard and apply it in
handleRowKeydown, mirroring the click path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(fork-banner): show draft CTA when fork is up to date

When a fork has no changes vs its parent ("Everything is up to date") but
has pending drafts, the banner now mirrors the non-fork drafts banner:
the status text becomes "This workspace has N draft(s)" and the button
becomes "Review & deploy drafts", linking to the compare page in draft
mode. When the fork has real ahead/behind diffs, the existing status and
buttons are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(compare): honor renamed draft paths + raw-app draft fixes

Address the Codex review:
- Draft deploy now uses the draft payload's path for scripts, flows and raw
  apps (keeping the URL path as the existing item key), so a rename in a
  draft deploys to the new path instead of silently staying at the old one.
- DraftDiffDrawer maps raw apps to the `raw_app` kind so their row edit
  links open the raw-app editor, not the legacy app editor.
- ScriptEditorView.restoreDeployed invalidates the workspace drafts after
  deleting the draft, so the session draft-bar count drops immediately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(compare): guard showDiff race, tree label, mode fallback

Address the cubic review:
- CompareDrafts.showDiff uses a monotonic request token so two quick "Show
  diff" clicks can't let a slow earlier fetch overwrite a faster later one.
- WorkspaceDiffDrawer.buildTree labels a 2-segment path with its leaf name
  (parts[1]) instead of the full scope key.
- The compare page only resolves ?mode=draft immediately; ?mode=fork (and
  an absent mode) defer to the isFork-aware effect, which falls back to
  draft for non-fork workspaces instead of stranding them on the fork UI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore: remove CONTEXT.md from the PR

Drop the root CONTEXT.md domain glossary and the lone comment pointer to
it in workspaceDrafts.svelte.ts.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(compare): send custom_path on raw-app draft deploy

A raw-app draft that changes or clears its custom route was silently
dropped on deploy from the compare page: updateAppRaw omitted custom_path,
so the backend preserved the old route. Send the draft's custom_path on
update — matching the fork deploy path (which spreads the full app,
custom_path included) and the createAppRaw branch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(sessions): refresh draft count on raw-app session save-draft

The script/flow session editors invalidate the workspace drafts on
save-draft, but the raw-app editor only did so on deploy. Thread an
onSaveDraft callback through RawAppEditor → RawAppEditorHeader and call
invalidateWorkspaceDrafts from RawAppEditorView, so saving a raw-app draft
in an AI session updates the SessionDraftBar count immediately (and the bar
appears when the count was zero).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(compare): honor renamed paths, draft triggers & paginate inventory

Address the Codex review:
- Draft deploy honors the draft's renamed path for scripts/flows/raw apps
  (keeping the URL path as the existing item key).
- Script/flow draft deploy now deploys draft_triggers via the shared
  deployTriggers, instead of silently dropping them with the draft.
- rawAppDeploy sends custom_path admin-gated on update (admin: value/'' to
  clear; non-admin: undefined) so non-admins don't hit RequireAdmin.
- getDraftItems pages through listScripts/listFlows/listApps so drafts past
  the first page are included in the count, banners, drawer and deploy list.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(compare): admin-gate custom_path on visual-app draft deploy

The visual-app branch of deployDraft sent custom_path unconditionally on
updateApp, so a non-admin deploying an app draft for an app with a custom
route hit RequireAdmin. Mirror AppEditorHeader and the raw-app path: admins
send the draft's custom_path ('' clears), non-admins send undefined so the
backend preserves the existing route.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(raw-app): save initial draft directly when path is known

In the AI-session preview, a never-deployed raw app has newApp=true but a
known path, so saveDraft opened the "Initial draft save" path-picker drawer
— which is gated on `appPath == ''` and therefore never rendered, making
Save draft silently do nothing. Branch the new-app case on appPath: pick a
path via the drawer only when none is chosen yet; otherwise call
saveInitialDraft() directly. saveInitialDraft now also toasts and fires
onSaveDraft so the session draft-bar count refreshes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(compare): preserve deployed custom_path on visual-app draft deploy

The visual-app draft value usually omits custom_path, so the admin branch's
`d.custom_path ?? ''` sent an empty string, which the backend treats as
"clear the route" — an admin deploying a content-only draft would wipe the
app's existing custom route. Fall back to the deployed route
(`r.custom_path`) when the draft omits it; an explicit '' still clears.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 18:24:23 +00:00
Ruben Fiszelandrubenfiszel a3740d571a chore(main): release 1.720.0 (#9464)
* chore(main): release 1.720.0

* Apply automatic changes

---------

Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com>
v1.720.0
2026-06-08 18:02:10 +00:00
hugocasaandClaude Opus 4.8 e8e0701a36 feat(api): add endpoint to update token label (#9474)
* feat(api): add endpoint to update token label

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): prevent renaming the session token label

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): restrict token-label edits to user tokens, not just session

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(frontend): edit token label in the edit modal instead of inline

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): reject relabeling tokens to reserved system-token names

Centralize the is_user_token classifier in windmill-common and reuse it
to reject labels colliding with system-token namespaces (ephemeral*,
debugger-token, mcp-oauth-*), not just session.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): match ephemeral label case-insensitively and cap label length

Align the canonical is_user_token, the SQL guard and the frontend mirror on
a case-insensitive `ephemeral` match (so a token can't be relabeled to a
casing the backend allows but the UI hides), reject labels over the
VARCHAR(1000) column limit with a 400, and add unit tests for is_user_token.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 17:33:31 +00:00
Diego Imbert bf4dd6c470 fix(drafts): swap crypto.randomUUID() for the project's randomUUID helper
crypto.randomUUID() is gated on a secure origin (HTTPS or localhost).
Self-hosted Windmill instances often run on a bare HTTP origin or a
LAN IP where the WebCrypto API is unavailable, so the /add redirect
would throw before issuing the 307. Use the existing RFC4122 v4 helper
in FlowChatManager that the rest of the codebase already imports for
this exact reason.
2026-06-08 19:32:09 +02:00
Diego Imbert f74504e273 feat(drafts): list & open draft-only items for variables, resources, schedules, triggers
For scripts/flows/apps the list and get-by-path endpoints already
surface per-user drafts that have no deployed counterpart — that's
what gates the home page from 404'ing on an AI-agent-created draft.
Extend the same support to the other UserDraftItemKinds:

Backend (list endpoints):
- Add include_draft_only to ListVariableQuery, ListResourceQuery,
  ListScheduleQuery, StandardTriggerQuery (the latter covers the
  11 trigger kinds via the generic TriggerCrud).
- Append per-user draft rows whose path has no deployed row. Same
  gate as scripts/flows/apps: non-operators, page 0, no narrowing
  filters. Synthesis is per-kind: ListableVariable/Resource get
  field-for-field synthesis; ScheduleLight reads NewSchedule shape;
  Trigger<T> uses a best-effort JSON merge + serde_json::from_value
  (rows skipped on deserialize failure rather than failing the list).
- Add draft_only: Option<bool> with sqlx(default) to each row type
  so it serializes as the column is opt-in.

Backend (get-by-path endpoints):
- get_variable, get_resource, get_schedule, get_trigger<T> fall back
  to fetch_draft_only when the deployed row is missing and the
  caller passed get_draft=true. Mirrors scripts/flows/apps.

OpenAPI:
- Shared IncludeDraftOnly parameter under components/parameters,
  wired into the 11 trigger list endpoints + listRawApps. Inline
  declarations on listVariable / listResource / listSchedules /
  listAzureTriggers.
- draft_only field on ListableVariable, ListableResource,
  Schedule, TriggerExtraProperty.

Frontend:
- variables, resources, schedules, and the 10 trigger list pages
  (routes + 9 *_triggers) pass includeDraftOnly: true on the
  initial fetch and render <DraftBadge draft_only> on synthesized
  rows. Trigger pages got a sed/perl bulk update — pattern is the
  same across kinds.
2026-06-08 19:30:44 +02:00
5d0ef7dfd9 fix: center auth0/okta icons and respect currentColor (#9457)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
2026-06-08 16:19:54 +00:00
GuilhemandClaude Opus 4.8 6d522b3989 fix: refresh session editor preview on breadcrumb target switch (#9475)
* fix: refresh session editor preview on breadcrumb target switch

Consolidate the three session editor views into a SessionEditorTarget deep module that remounts the heavy editor on a data-ready target swap ({#key slot.loadedPath}), so stale mount-time state (e.g. Path.svelte's settings-panel path) re-derives. Adds LoadSlot to the runtime and a useUserDraftSync composable + per-kind codecs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: flush pending session draft write on target switch

A breadcrumb target swap (or unmount) within the 150ms outbound debounce window cleared the pending UserDraft write instead of flushing it, dropping the last edits. Scripts previously saved immediately so this was a regression from the new uniform debounce; flow/raw_app already had the latent drop. A dedicated path/workspace-scoped effect now flushes the pending write on switch/unmount without disturbing the debounce during a typing burst. Also refreshes a stale loadScript comment that named removed symbols (addresses PR review nits).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:19:19 +00:00
hugocasaandClaude Opus 4.8 192574ab8f fix(forks): keep trigger/schedule operational state owned by the parent - WIN-2019 (#9476)
* fix(forks): defer trigger/schedule state to parent for clean git merge

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(forks): read parent trigger/schedule state on non-RLS pool for complete substitution

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(forks): read schedule fork-ness on non-RLS pool; clarify mutator-rule wording

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:18:12 +00:00
Ruben FiszelandClaude Opus 4.8 76c0d970a1 fix(oauth): persist refreshed token through configured secret backend (#9471)
The lazy on-fetch OAuth token refresh persisted the new access token with a raw
`UPDATE variable SET value = <db-encrypted>`, bypassing the secret-backend
abstraction. With an external secret backend (AWS Secrets Manager / Azure Key
Vault / Vault), secret reads resolve through the backend and ignore
`variable.value` entirely, so refresh advanced `account.expires_at` and updated
Postgres but never wrote the new token to the external store. Every read that
did not itself trigger a mint kept serving the frozen connect-time token, which
expired ~1h after connect (RefreshError on Google clients).

`windmill-oauth` can't depend on `windmill-store` (circular), so variable
persistence moves out of `refresh_token{,_for_account}` (which now only exchange
the token + update the `account` row and return the new token) into the
`windmill-store` callers, via a new `store_oauth_token_value` helper that writes
through the configured backend and stores the returned value (encrypted blob for
the DB backend, `$...:` marker for external backends) in `variable.value`.

If persisting the refreshed token fails (more likely now that it can be a
network write to an external backend) after the account was committed fresh,
`store_oauth_token_value` resets `expires_at` to the past and records
`refresh_error` — looking the account up via `variable.account` — so the next
fetch retries instead of serving the stale token for the whole token lifetime.

Also add `windmill-store/tests/oauth_refresh_secret_backend.rs`, an opt-in e2e
regression suite (RUN_SECRET_BACKEND_E2E / RUN_AWS_SM_TESTS) covering database
and external (AWS SM via LocalStack) backends plus the self-healing reset.
Verified against Postgres + LocalStack: 3 passed.

EE companion (oauth_refresh_ee.rs: 3 refresh paths) merged via #607; this OSS
half completes the fix (ee-repo-ref already at EE main 481ea7f).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:52:23 +00:00
Ruben FiszelandClaude Opus 4.8 fa86c62b66 fix(frontend): use ban icon for canceled jobs instead of hourglass (#9478)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:42:07 +00:00
centdixandwindmill-internal-app[bot] 3bc5800197 feat: allow private MCP server URLs (#9470)
* feat: allow private MCP server URLs

* docs: remove private MCP server URL doc

* fix: apply MCP URL opt-in to OAuth handlers

* fix: update EE ref for MCP OAuth redirects

* fix: preserve MCP OAuth client timeout

* chore: update ee-repo-ref to 481ea7f28dc5af6b72390c82f494f34cb9809546

This commit updates the EE repository reference after PR #608 was merged in windmill-ee-private.

Previous ee-repo-ref: 6c7da03fb994be23ed6aca59bece94d257a641b5

New ee-repo-ref: 481ea7f28dc5af6b72390c82f494f34cb9809546

Automated by sync-ee-ref workflow.

---------

Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-06-08 14:46:47 +00:00
Ruben FiszelandClaude Opus 4.8 82cb7bf375 whitelabel default timeout + test-job callbacks (#9469)
Add a configurable `defaultTimeout` to the script/flow editor whitelabel
customUi (replaces the hardcoded 300s default) and an `onTestJob` callback
on ScriptBuilder/FlowBuilder that fires with the preview job id when a test
run starts.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 14:43:07 +00:00
Diego Imbert 4264c3d9a7 refactor(drafts): type UserDraftOverlay.other_drafts_users in the OpenAPI
The backend response carried other_drafts_users on every get-by-path
that supports the draft overlay, but the OpenAPI schema didn't declare
the field. Each route had to cast the typed response to `any` to read
it (and the sibling draft_saved_at), which obscured the real shape from
the type system and rotted the discoverability of the draft surface.

Add it to UserDraftOverlay. Frontend casts collapse to plain property
reads in the three editor routes.
2026-06-08 15:35:25 +02:00
Diego Imbert 4f21fd871e refactor(drafts): extract makeDraftAddLoad helper
Four identical /add/+page.ts files differing only by the edit-route
prefix. Lift the redirect into a factory, slim each entry point to
two lines.
2026-06-08 15:32:54 +02:00
Diego Imbert 2ac14b1c67 refactor(drafts): type App.draft_path; drop the as-any cast
The audit asked for the three editors to converge on one draft_path
injection pattern. For App and Flow, the in-builder $effect-mutates-
the-store idiom is wedged into a shape that doesn't natively own the
field — App's editor type genuinely has no draft_path so the writer
had to cast through `as any`, and consumers downstream did the same.

The minimum viable fix: declare draft_path on the local App type
(it's already a field on the autosaved JSON). Lifting the writes
upward into a route-side merger would mean restructuring the
AppEditor mirror $effect and the FlowBuilder pathStore plumbing —
larger change for the same shape, deferred to a follow-up.

Flow already has the typed cast localised at one site. Will get the
OpenAPI-level draft_path field as part of task 47 (drop as-any
casts on backend overlay reads).
2026-06-08 15:31:16 +02:00
Diego Imbert 66c03d02dd refactor(drafts): unify bootstrap suspension via armRestartOnFirstInteraction
The flow and raw-app routes each rolled their own end-of-bootstrap
resume: a 700ms setTimeout for flows and a templatePicker watcher with
double-tick gating for raw-apps. Both are timing-fragile (the comments
admit it) and drift from each other.

armRestartOnFirstInteraction already existed in userDraftToast.ts for
reset-to-deployed: keydown/input/pointerdown listeners (capture phase)
that fire restartSync on the first real user touch, with a 5s
belt-and-braces fallback. Export it and use it everywhere we'd previously
have picked a magic number.

For raw-apps this is a tiny behavioural change: the user's template
choice now POSTs immediately (the pointerdown that picks the template
also resumes sync, so the picker's onStart write rides the wake-up).
Previously the choice only persisted on the user's NEXT edit. That's
strictly better — navigating away preserves the choice now.
2026-06-08 15:28:35 +02:00
Diego Imbert 02b578bca3 refactor(drafts): UserDraft.useReactive — kill array-of-one boilerplate
The script + flow routes both wanted a handle that re-keys when the URL
path changes. UserDraft.use() can't do that (its opts getter is
untracked), so each route hand-rolled the same useMany-array-of-one +
proxy idiom:

  const handles = useMany(() => [{ kind, path: reactive }])
  const handle = { get draft() { return handles[0]?.draft }, ... }

Add UserDraft.useReactive(getSpec) that internally wraps useMany with a
single spec and returns the stable proxy. Callers collapse to one line.
2026-06-08 15:23:26 +02:00
Diego Imbert 6d263bdf1e refactor(drafts): extract DraftEditorModals trailer block
The four editor routes (scripts/flows/apps/apps_raw) mounted an
identical pair of trailer modals — DraftSyncConflictModal +
OtherUsersDraftsModal — wrapped in the same guard chain and {#key path}
remount. Lift the markup into one component; routes thread their
itemKind, path, editPathFor, and loader callback.

Pure markup extraction, no state ownership change. Drops the unused
userStore import where the trailer was the only consumer.
2026-06-08 15:22:08 +02:00
Diego Imbert e71644500c refactor(drafts): remove dead endpoints + UserDraftDbSyncer.getLastSync
The list_drafts and get_draft (own) routes were added during PR
iteration and never wired up to any frontend caller — the editor
overlay path uses the per-kind get-by-path getDraft query parameter,
and the home page lists drafts via the per-kind list endpoints, not
via /drafts. Drop both routes (+ sqlx caches + OpenAPI entries).

UserDraftDbSyncer.getLastSync was a peep-hole for callers that never
materialised — the per-tab lastSync map is only ever read by postSave
internally, where the bookkeeping already lives inline.
2026-06-08 15:19:31 +02:00
Diego Imbert 149edc7bf0 refactor(drafts): drop LS-era pipeline; backend is canonical on load
The PR's iteration left behind a meta/staleness pipeline carried over
from the localStorage era — per-rev tracking, a LocalDraftStaleModal, a
'Restored from local storage' toast, and a localDraft-vs-backend
comparison branch in every editor loader. With drafts now living in
the DB and the optimistic-concurrency lastSync check handling
divergence, that whole stack is dead weight.

Worse, the comparison branch caused 'Load from server' in the conflict
modal to do nothing: the loader preferred the in-memory cell over the
backend, so the user-clicked 'load from server' just re-displayed the
local edits AND fired two confusing toasts (Restored from local
storage + Loaded your saved draft).

The rip:

* userDraft.svelte.ts: drop UserDraftMeta, StoredDraft.meta,
  checkStaleness, UserDraftStalenessCause, normalizeForCompare,
  localDraftDiffers, saveMeta, getMeta, setDraftAndMeta, setMeta,
  handle.meta/setDraftAndMeta/setMeta, force option. Handle is now
  just { draft }.
* userDraftToast.ts: drop notifyRestoredFromLocal +
  RestoreFromLocalActions. Update copy.
* LocalDraftStaleModal.svelte: deleted.
* AppEditor.svelte: drop initialRevs prop and the firstMirror
  wipe-then-restore dance (it existed only to consume the meta-mismatch
  skip slot).
* All 4 editor routes: backend is canonical on load — the in-memory
  cell is overwritten with the deployed+draft overlay, the syncer's
  seed guard swallows the first write so we don't POST it back.
* VariableEditor / ResourceEditor: drop the staleness pipeline + rev
  bookkeeping; backend wins on open.
* useTriggerDraftSync.svelte.ts: inline the JSON-normalize + deepEqual
  utility as a private cfgDiffers helper (kept for the form-vs-deployed
  dirty check, which is a genuine semantic compare, not LS legacy).
* copilot core.ts / userDraftAdapter.ts: drop meta argument from
  saveAppDraft, loadAppDraftValue, write*Draft. Test assertions on
  getMeta dropped.

Net: -22 typecheck errors, fewer moving parts, conflict modal works.
EOF
)
2026-06-08 15:14:03 +02:00
GuilhemandClaude Opus 4.7 64b089cd23 feat(frontend): use unified drill picker for AI chat @-mention dropdown (#9159)
* feat(frontend): use unified drill picker for AI chat @-mention dropdown

* fix(frontend): chat picker review followups + overlay alignment

- AIChatDisplay: migrate @-badge popover to ChatContextPicker (was still
  importing the deleted AvailableContextList after the rebase onto #9034,
  causing a build break).
- DrillPicker: handle Tab as Enter so the inline @<word> mention completes
  without losing focus. Tweak leaf-row weight to font-normal; secondary
  text uses text-hint.
- ContextTextarea: drop px-0.5 from the highlight span — extra horizontal
  padding made every glyph typed after a mention drift right of the
  invisible textarea below. box-decoration-clone keeps the rounded corners.
- ContextElementBadge: explicit font-normal label, hoist label into a
  {@const} and pass to title= so the truncated badge shows the full title
  on hover.
- workspaceTree: drop orphaned doc-comment left dangling by the rebase.
- Add unit tests for drillPicker.ts and workspaceTree.ts (51 tests cover
  resolveScope/scopeChain/collectLeavesGrouped/leafHaystack, buildWorkspaceTree
  shape + loading + dir forest + leaf shape, withCurrent rename suppression,
  extraItemsByKind dedup, legacyScopeToPath, relativizeWorkspacePath).

* fix(flow-editor): ignore keyboard shortcuts when focus is outside the flow root

Menus, modals, drawers etc. live outside the flow root and capture focus
explicitly. Flow nodes aren't focusable, so the unfocused default
(activeElement === body) means "flow is the canvas" and we should react;
anything else means another surface has the user's attention and our
shortcuts would steal it.

* fix(frontend): inline @ mention picker + chat layout polish

- ContextTextarea: swap manual Portal+caret-math positioning for
  svelte-floating-ui anchored at the `@` character (virtual reference,
  middleware [offset, flip(crossAxis:false), shift]). Picker stays
  pinned to `@` while the user types the query, slides leftward when
  hitting the right edge instead of flipping alignment, and floating-ui
  handles above-vs-below + edge clamping automatically. Drops the
  60vh-worst-case reservation that left a big gap above the caret in
  sessions, and the now-unused isFirstMessage prop is marked deprecated.
- AIChatDisplay: the `@`-button Popover now opens with placement
  bottom-start (was the default `bottom`), aligning its left edge with
  the button instead of centering under it.
- ChatContextPicker: when no Diffs/Modules/Databases branches are
  present (e.g. global chat), return the Workspace tree's children at
  the root instead of wrapping them under a redundant "Workspace" row.
  handleScopeChange handles both the wrapped and unwrapped layouts and
  the single-kind `dir:` top segment.

* chore(frontend): address review suggestions on chat picker PR

- DrillPicker: clamp width to viewport on narrow screens —
  w-[420px] → w-[min(420px,calc(100vw-20px))].
- workspaceTree.buildWorkspaceTree: make loadingKind optional (defaults
  to {}). Chat picker still passes it; callers that don't track loading
  no longer need to thread an empty object.
- ChatContextPicker.handleScopeChange: name the WRAPPED vs UNWRAPPED
  layouts in a comment block so the dir:/kind: branches are obvious.
- ContextTextarea: drop deprecated isFirstMessage prop (floating-ui
  handles direction); drop defensive Math.max on the @ index now that
  the invariant is documented; comment the floatingRef(anchorRef) call
  as the supported virtual-reference path in svelte-floating-ui.
- AIChatInput: stop forwarding isFirstMessage to ContextTextarea.

* feat(frontend): sync selectedContext with @-mentions in textarea

Both picker entry points now insert a visible `@title` token in the
textarea, and deleting that token drops the matching entry from
selectedContext.

- AIChatInput: new insertMention(title) export. Appends `@title ` to
  instructions, prefixing a space only if the existing text doesn't
  already end in whitespace.
- AIChatDisplay: the `@`-button popover calls insertMention after
  addContextToSelection so its picks match the inline-mention path's
  textarea state.
- ContextTextarea: new onRemoveContext callback. A $effect compares the
  set of `@title` tokens in `value` (derived) against the previous
  snapshot; titles that disappeared trigger onRemoveContext for any
  selectedContext entry with `deletable !== false`. The diff lives in
  an effect (not handleInput) so it catches both keystroke deletions
  AND programmatic value updates from updateInstructionsWithContext.
- AIChatInput: passes onRemoveContext that filters selectedContext by
  type+title — mirrors the existing badge X-button handler.

* chore(frontend): narrow ChatContextPicker `inner` from `any` to `DrillPicker | undefined`

The previous `let inner: any` worked around svelte-check rejecting
`DrillPicker<ChatLeafData>` (the imported component is seen as the
non-generic `Comp`). Dropping the type parameter keeps the workaround
without `any`, so handleKeydown / pickHighlighted are at least typed
at the call site.

Addresses May-14 PR review.

* fix(frontend): address PR #9159 bot-review findings (eager preload, focus, dedup, icon types)

- [P1] ChatContextPicker.handleScopeChange: stop preloading workspace
  kinds at the wrapped picker root. New `isWorkspaceOnly` $derived (true
  when no Diffs/Modules/Databases branches are present) gates the at-
  root preload, so the chat root no longer fires two list requests
  before the user enters Workspace. Reported by Codex.
- [P2] AIChatDisplay @-button popover: call aiChatInput.focusInput()
  after close() so the textarea is focused for immediate typing — mirrors
  the inline-mention path's setTimeout(textarea.focus, 0). Reported by
  Claude.
- [P2] AIChatInput.insertMention: no-op when the `@title` token is
  already present in instructions, so re-picking a workspace item
  doesn't leave duplicate visible tokens for a single selectedContext
  entry. Reported by Codex.
- [P2] drillPicker.ts: introduce `DrillIcon = ComponentType |
  Component<any, {}, ''>` and replace `icon: any` on DrillLeaf,
  DrillBranch, and ChatContextPicker.buildContextBranch. Mirrors the
  ComponentType | Component pattern used in TriggersBadge.svelte for
  the same Svelte 4/5 compatibility window. Reported by Pi.

* fix(frontend): preserve workspace context on refresh + load all kinds for internal search

- [P1, Codex] ContextManager.updateAvailableContextForScript/Flow:
  preserve workspace_script and workspace_flow entries through the
  selectedContext filter on editor refresh. They're user-picked refs
  that don't appear in availableContext, so the previous filter was
  silently dropping them whenever the script/flow editor refreshed
  options (e.g. on any code change).
- [P2, cubic-dev-ai] WorkspaceItemDrillPicker: in internal-search mode
  (externalFilter === undefined, DrillPicker renders its own search
  box), preload all kinds on mount. Without this, typing in the
  picker's search before clicking a kind branch produced incomplete
  results since DrillPicker can't reach back through the adapter to
  trigger fetches on internalFilter change. Cached items keep the
  effective cost near-zero on warm sessions.

* fix(frontend): preserve workspace refs through script-mode context refresh

The script-mode updateAvailableContext overwrites newSelectedContext
with a fresh [code] entry, defeating the workspace_script /
workspace_flow preservation in the later filter — the entries are
already gone by the time the filter runs.

Seed newSelectedContext with the refreshed code block AND the user-
picked workspace_script / workspace_flow / code_piece entries from
currentlySelectedContext, so editor refreshes don't wipe @-mention
badges in script chat. The existing line-271 filter still validates
each entry against newAvailableContext + the per-type allowlist.

Reported by Codex on PR #9159 — completes the prior workspace-context-
on-refresh fix (b02d1f2d35) which only patched the filter, not the
rebuild step that runs before it.

* fix(frontend): preserve all previously-selected contexts on script refresh

The prior c2775fe0c5 fix only carried over workspace_script /
workspace_flow / code_piece entries from currentlySelectedContext.
That preserved the workspace P1 path but still dropped previously-
selected diff / error / db / runtime-context badges, which cubic
flagged in its 16:55 review.

Spread the full currentlySelectedContext (minus `code`, which we just
rebuilt). The downstream filter validates each entry against
newAvailableContext + the per-type allowlist, so auto-derived types
like diff / error / db survive when still applicable, and unrelated
items are dropped automatically.

Reported by cubic-dev-ai on PR #9159.

* fix(frontend): rehydrate auto-derived context + sync badge X with textarea

- [P2, cubic] ContextManager.updateAvailableContext: when the rebuild
  carries over previously-selected diff/error/db entries, swap each one
  for the matching freshly-built entry from newAvailableContext in the
  final .map() step. Preserves the user's `deletable` override on top
  of the fresh content/diff/schema, so refreshes don't keep stale
  payloads while still surviving the badge across edits.
- [P2, Pi/Codex] AIChatInput: new `removeMention(title)` export that
  strips `@title` tokens from `instructions` (whitespace-bounded so
  substring matches don't bleed). The badge X-button now calls it
  after filtering selectedContext, mirroring the inverse textarea-to-
  badge sync. No double-remove: ContextTextarea's $effect-driven
  onRemoveContext is a no-op once selectedContext no longer holds the
  entry.

* fix(frontend): retype ChatContextPicker.inner to DrillPicker<ChatLeafData>

`npm run check:fast` (TypeScript-only) and `npm run check` (svelte-check)
disagree on whether the imported DrillPicker is generic — `check:fast`
sees it as `Comp` and rejects the type parameter, while `svelte-check`
sees the real generic component and requires it. CI runs `check`, so
follow that: `DrillPicker<ChatLeafData> | undefined`.

This also fully replaces the prior `inner: any` workaround called out in
multiple bot reviews — handleKeydown / pickHighlighted now type-check at
the call site against the correct component instance.

* fix(frontend): scope removeMention's whitespace collapse to the mention site

The trailing `.replace(/  +/g, ' ')` in `removeMention` was global,
collapsing any pre-existing double-spaces in the prompt — e.g. a user
typing `"hello  world  @foo  bar"` lost their intentional formatting
when they deleted the `@foo` badge.

Rework the regex to match `(^|\s)@title(\s|$)` and decide per-match:
- Mention at a boundary (no lead or no trail): drop entirely.
- Mention in the middle: keep ONE bordering whitespace char (the
  leading one verbatim, so newlines/tabs aren't downgraded to spaces).

No global pass over `instructions`. Unrelated whitespace stays intact.

Reported by cubic-dev-ai on PR #9159 (07:27 review of 9e07eac4).

* fix(frontend): expose DrillPicker.onFilterChange + lazy-load workspace kinds

Both Codex P1s came from over-eager preload heuristics on my prior fixes:
the workspace picker cold-loaded every configured kind on mount in
internal-filter mode, and the chat badge popover never observed its own
internal filter so workspace results were missing from search until the
user drilled into Workspace.

Replace both ad-hoc effects with a single `onFilterChange` callback on
DrillPicker that fires whenever the EFFECTIVE filter (external or
internal) changes:

- [P1] WorkspaceItemDrillPicker: drop the "cold-load on mount when
  externalFilter === undefined" effect. Workspace kinds now load only
  once the user actually types something — closer to the pre-refactor
  behavior where the breadcrumb / "Open editor" pickers only fetched
  the drilled-into kind plus all kinds on search.
- [P1] ChatContextPicker: handleFilterChange replaces the prior
  externalFilter-only effect. Badge-popover search (internal filter)
  now triggers the same preload as inline-mention search (external
  filter), so workspace results appear without needing to drill first.

Both fixes reported by Codex on PR #9159.

* fix(frontend): skip mention-removal sync when textarea is programmatically cleared

sendRequest() sets `instructions = ''` immediately after dispatching to
AIChatManager. The mention-removal effect treated this as user-initiated
deletion and cleared selectedContext BEFORE AIChatManager.beforeSend
snapshotted it — selected `@` contexts disappeared from the outgoing
request. Skip the sync when value is empty; user-initiated mention
deletes happen in-place against non-empty content.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): scope post-send wipe protection to the send path only

Replace the blanket `if (value !== '')` guard on the mention-removal
effect with an explicit `clearForSend()` export. `sendRequest()` now
calls it instead of `instructions = ''`, so a user manually clearing
the whole textarea still drops the corresponding context badges while
the post-dispatch programmatic wipe is silent.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(frontend): extract useWorkspaceItemsLoader composable shared by both drill picker adapters

WorkspaceItemDrillPicker and ChatContextPicker each duplicated the same
machinery: loaded/loadingKind state seeded from the module cache, a
stale-while-revalidate ensureLoaded coroutine with an untrack guard, a
kind:/dir: scope-segment decoder, and the "load every kind once the user
starts searching" filter callback.

Move that to a single useWorkspaceItemsLoader() returning
{loaded, loadingKind, ensureLoaded, ensureAll, ensureForScopeSegment,
onFilterChange}. Adapters keep their own scope-walking policy (chat
collapses an optional 'workspace' wrapper, workspace handles single-kind
mode) but delegate kind decoding and lazy fetch to the composable.

Net: -135 +28 LOC in the two adapters; +109 LOC in the new composable.
The cache-version race, untrack discipline, and stale-while-revalidate
semantics now live in one place.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): address Codex P1+P2s — non-context clear, same-title cross-removal, single-kind cold load

P1: sendRequest() now clears `instructions` unconditionally after the
optional `clearForSend()` so APP/NAVIGATOR/ASK/API modes (which don't
mount ContextTextarea) still reset the input after send.

P2: removeMention() now calls a new `unsyncMention(title)` on the
textarea before stripping `@title` from `value`, so the mention-removal
effect doesn't fire a second onRemoveContext on a same-title sibling
(e.g. workspace_script + workspace_flow sharing a path).

P2: single-kind WorkspaceItemDrillPicker loads its kind at mount even
when scope is empty — buildWorkspaceTree collapses to the kind's
children, so there's no kind row to drill into to trigger the load.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-08 11:52:41 +00:00
Diego Imbert 7969679526 nit 2026-06-08 13:18:10 +02:00
Diego Imbert 32ca1c251e fix(drafts): drop the visibilitychange flush — debouncer keeps running on hidden tabs
Tab switching just hides the page; the JS context survives and the
debouncer's `setTimeout` keeps counting down. When it fires, the runner
POSTs normally and the server's response updates `lastSync`. There's
nothing left for a visibilitychange-driven flush to do that the
ordinary pipeline doesn't already handle, and adding one only creates
extra POSTs to reason about.

`pagehide` remains the single trigger for the keepalive flush — that's
the case where the JS context is actually being torn down and the
runner's pending fetch would otherwise be killed mid-flight.
2026-06-08 13:13:49 +02:00
Diego Imbert 289c0d6010 fix(drafts): split tab-switch and unload flushes — kill self-conflict on visibility change
The single keepalive flush bound to both `visibilitychange → hidden`
and `pagehide` self-conflicted on tab switch: visibilitychange fires
on every tab/app switch with the page still alive, the keepalive POST
advanced the server's `created_at` to a fresh `now()`, the client
discarded the response (no listener), the local `lastSync` stayed at
the old value, and the next foreground autosave sent that stale
timestamp → server saw `created_at > last_sync` → conflict modal for
the user's own background-tab write. A still-pending debouncer task
made it worse: it fired a second runner POST after the keepalive with
the same stale `last_sync`, the second self-conflicted too.

Split into two paths:

- `visibilitychange → hidden` → `flushOnVisibilityHidden`: route
  through the normal runner pipeline. The page is alive, so the
  response can land and `setLastSync` keeps the baseline current. Call
  `debouncer.cancel(key)` first so a queued keystroke can't double-fire
  with the same stale `last_sync`.

- `pagehide` → `flushOnPageHide`: keep the `keepalive: true` raw fetch
  for the genuinely-going-away case (the JS context is torn down, the
  response is necessarily discarded). Same `debouncer.cancel(key)`
  guard. On the next mount, the route's `recordRemoteSync(query,
  draft_saved_at)` reseeds `lastSync` from authoritative server state
  before any user edit can fire a save.
2026-06-08 11:33:36 +02:00
Diego Imbert 486f25f0d9 indicator ui nits 2026-06-08 11:29:34 +02:00
Diego Imbert 8865c58f66 fix(drafts): defer reset-to-deployed restart until first user interaction
Two-tick `restartSync` was too aggressive: editor remounts emit a tail
of cascading writes (Monaco setValue acks, schema re-infer, UI Builder
iframe handshakes, schedule-config recomputes, …) that land well after
two ticks and would clobber the just-deleted draft with an upsert of
the deployed value — making "Reset to deployed" a no-op in practice,
the user kept seeing the draft come back.

Centralise the suspension lifecycle in a new `runResetToDeployed`
helper. It stopSyncs around the reset, POSTs the explicit delete, runs
the route's wipe-and-reload, and then arms a one-shot listener on
document keydown / input / pointerdown that restartSyncs on the user's
next real interaction. A 5-second fallback re-arms sync if the user
walks away without touching the editor, so suspensions don't leak.

Use it from both the load-time toast (`notifyDraftLoaded`) and the
autosave-indicator popover so the two stay in sync — fixes both
entry points.
2026-06-08 01:45:34 +02:00
Diego Imbert 86f5ddb84d fix(drafts): conflict modal wording — drafts are user-scoped, not teammate-scoped 2026-06-08 01:37:33 +02:00
Diego Imbert abe660d778 fix(drafts): OtherUsersDraftsModal — close on Fork, don't leak clicks through nested JSON
Two bugs in the per-editor "another user has a draft" banner:

- Fork landed the immediate save but didn't close the banner before
  navigating. Svelte hadn't torn down the previous route's components
  by the time goto returned, so the banner lingered on top of the
  destination editor. Comment the explicit isOpen=false on the
  happy path so it's clear it MUST run before goto.

- Clicking anywhere on the screen while the View JSON drilldown was
  open closed the underlying banner too. Modal2's clickOutside
  action fired on every Modal2 instance — both the JSON modal and
  the underlying banner — because both attach their own listener at
  the document level. Add `closeOnOutsideClick` opt-out on Modal2
  and pass `closeOnOutsideClick={!jsonOpen}` to the outer modal so
  clicks outside the JSON drilldown only close the drilldown.

Drive-by: Modal2's keydown handler now ignores Escape when its own
isOpen is false (was a no-op closer that would still preventDefault
on every key press, swallowing key events for any siblings).
2026-06-08 01:36:14 +02:00
Diego Imbert 9c8c4edb12 fix(drafts): conflict detection — keep last_sync map tab-local instead of in localStorage
Two tabs editing the same draft both load with last_sync = T0.
Tab-1 saves; the server accepts, returns T1, and the syncer wrote T1
into localStorage. Tab-2 then tries to save: it reads the SHARED
localStorage map, sees T1 instead of its own baseline T0, sends
last_sync = T1, and the backend's WHERE clause (`created_at <=
last_sync`) is true → tab-2 clobbers tab-1's edit without ever seeing
a conflict.

Move the map to tab-local memory (`new Map<string, …>`). Reload of the
tab now starts with an empty map; that's fine because the editor's
load path calls `recordRemoteSync(query, draft_saved_at)` right after
`get_draft=true` returns, reseeding from the authoritative server
timestamp before any user edit could fire a save.
2026-06-08 01:32:33 +02:00
Diego Imbert ef33a833b8 fix(drafts): wait for the fork POST to land before navigating
OtherUsersDraftsModal's Fork action called UserDraft.save, which routes
through the autosave debouncer (1500ms). The subsequent goto fired
within the same tick, so the destination editor's get_draft=true read
ran before the POST landed and 404'd — refreshing worked because by
then the debounced save had fired.

Call UserDraftDbSyncer.save with immediate: true and await it. The
syncer cancels any queued debouncer task for the key and resolves the
promise only after the POST completes, so the route load can find the
forked draft on the first try.
2026-06-08 01:30:18 +02:00
Diego Imbert 22f2bae8c7 feat(drafts): autosave-indicator popover with Reset-to-deployed action
Click the cloud icon → popover with "All changes are saved as a draft on
the server. The draft is per-user — your teammates' editors keep their
own." When the editor isn't on a draft-only path AND the user has a
draft (UserDraft.has returns true), a "Reset to deployed" button
mirrors the load-time toast action — stops sync, POSTs `value: null`,
runs the route's reload-without-draft callback, restarts sync past two
ticks so the deployed-seed write doesn't resurrect the draft.

Threaded `onResetToDeployed` from each route down to its builder
(ScriptBuilder / FlowBuilder / AppEditorHeader / RawAppEditorHeader)
and into the indicator. `draftOnly` is wired from `savedScript.no_deployed`
/ `newFlow` / `newApp` so the action hides where there's nothing to fall
back to. The indicator's trigger now has a hover affordance + matches
Portal's default target ('body') via Modal2's earlier fix.
2026-06-08 01:26:30 +02:00
Diego Imbert c0bf4539bb ui nit 2026-06-08 01:24:31 +02:00
Diego Imbert b646f7929f fix(drafts): Reset to deployed no longer resurrects the draft
The toast's "Reset to deployed" callback POSTed `value: null` to the
syncer, then handed control to the route's `onResetToDeployed` (which
wipes the in-memory handle and reloads the deployed payload via
`getDraft: false`). Both writes flowed through the reactive sync
effect: the wipe scheduled a delete, the reload scheduled a re-save of
the deployed value as the new draft. Coalescing collapsed them and the
draft came back — making the "discard" action effectively a no-op.

Wrap the whole callback in `UserDraft.stopSync` / `restartSync`. The
explicit `value: null` POST still goes through (it's a direct
`UserDraftDbSyncer.save` that doesn't depend on the reactive effect),
the route's wipe-then-reload mutations advance `lastSerialized` silently
under suspension, and the next user edit (after two ticks past the
deployed-seed write) is the first real save again.
2026-06-08 01:15:47 +02:00
Diego Imbert 9890a55306 fix(ui): default Modal2 target to 'body' so omitting the prop doesn't throw
Modal2 defaulted `target = ''` and forwarded it to `Portal`, which calls
`document.querySelector(target)` — an empty selector throws
"Failed to execute 'querySelector' on 'Document': The provided selector
is empty" and the modal silently fails to mount.

That's why `OtherUsersDraftsModal` (and `DraftSyncConflictModal`) never
appeared on editors where another user had a draft — both omit the
`target` prop. Other Modal2 callers (StorageSettings, CriticalAlert,
CustomInstanceDbWizardModal, …) pass an explicit `target="#content"`
and were unaffected.

Match Portal's own default of `'body'` so omitting the prop is now a
no-op rather than a runtime throw.
2026-06-08 01:12:18 +02:00
Diego Imbert 3290b80817 fix(drafts): preserve the user-typed draft_path on reload of draft-only items
The flow / app / raw-app editors all dropped the saved `draft_path`
back to the URL's `u/{user}/draft_{uuid}` slot the moment the user
reloaded a draft-only edit page: the route sourced the Path widget's
initial path from `page.params.path` instead of the previously-saved
`draft_path`, and the first user edit then mirrored that URL path
back into the autosaved draft — silently overwriting the friendly
name in both the row and the editor.

- Flow route: after computing `effectiveFlow`, override `flowInitialPath`
  with `effectiveFlow.draft_path` when set.
- App route: pass `newPath={(app.value as any)?.draft_path ?? app.path}`
  through to `AppEditor`; AppEditorHeader's `newEditedPath` default now
  prefers a non-empty `newPath` over the random `<adj>_app` seed (the
  `newApp && !newPath` branch keeps the `/apps/add` friendly auto-name).
- Raw-app route: surface `savedRawAppDraft.draft_path` onto `backendApp`
  so the `extractRawApp` path seeds `newPath` with the friendly name.

Reload + a subsequent edit now leaves `draft_path` intact for all three
kinds; verified end-to-end via the `/drafts/get_draft/...` endpoint.
2026-06-08 01:03:48 +02:00
Diego Imbert 47c45edd80 feat(drafts): render friendly user-typed path on home list for all 4 kinds
Reinstate `draft_path` on `Listable{Script,Flow,App}` so the home rows
prefer the user-typed name over the autogenerated `u/{user}/draft_{uuid}`
URL slot, with two source rules — one per how each editor wires the
Path widget:

- Scripts already work: `ScriptBuilder` binds the Path widget directly
  to `script.path`, so the typed path round-trips through the draft
  JSON's own `path` field. Backend extracts `v["path"]` when it differs
  from `row.path`.

- Flows / apps / raw apps don't write the typed path into the
  autosaved value (`Flow.path` is one-way-bound to `$pathStore`; the
  bare `App` / raw-app value has no `path` field at all). Introduce an
  explicit `draft_path` field on the draft JSON, written by the editor
  ONLY when the typed path differs from the deployed/seeded
  `savedX.path`:
  - FlowBuilder: $effect on `$pathStore` mutates `flow.draft_path`.
  - AppEditorHeader: $effect on `newEditedPath` mutates `$app.draft_path`.
  - RawAppEditorHeader: $effect surfaces `pendingDraftPath` up via the
    bind chain (RawAppEditor → route); the route's draftHandle.draft
    spread includes `draft_path` when set.
  Backend extracts `v["draft_path"]` and `None` when unchanged or after
  deploy (deploy clears the whole draft, so the field naturally
  disappears post-deploy without bookkeeping).

Flow route's `new_draft` branch now stops sync around the Path widget
cascade, with a 700ms scheduled `restartSync` (mirrors the existing
scripts/apps/raw_apps stoppers) — the new draft_path mutation lands
inside that window so `/flows/add` no longer fires an autosave before
the user's first edit. openapi/sqlx regenerated.
2026-06-08 00:54:11 +02:00
Diego Imbert 0ffcb13080 fix(drafts): seed a friendly name on /flows/add
The flow route passed `initialPath={page.params.path ?? ''}` to
FlowBuilder, so on the `/flows/add → /flows/edit/u/{user}/draft_{uuid}`
redirect the Path widget's `initPath` saw a non-empty `initialPath` and
skipped the `reset()` branch that auto-generates the friendly
`<random_adj>_flow` name. The other three editors all clear
`initialPath` in their `new_draft` branch for exactly this reason.

Track `initialPath` as route-owned state (defaults to the URL path) and
clear it to '' inside the `new_draft` branch, then bind it through to
FlowBuilder so any post-deploy update from the editor still propagates.
2026-06-08 00:25:57 +02:00
Diego Imbert 41056473e1 refactor(drafts): drop dead draft_path field from list responses
The draft-only listing branches in scripts/flows/apps computed a
`draft_path` from the draft JSON (when the user-typed path differed from
the URL's autogenerated `u/{user}/draft_{uuid}`), and `{Script,Flow,App}
Row.svelte` preferred it over `path` for the row title. In practice
that path is never written: the app, raw-app and flow editors all warn
"Deploy the X to make the path change effective" — the rename only
lands on deploy, never in the draft. So the field is always None and
the home rows always show the autogenerated slot anyway.

Drop the field from the three `Listable*` structs, the three draft-only
push sites, the three OpenAPI response schemas, and the three frontend
row components. Client regenerated.
2026-06-08 00:18:56 +02:00
Diego Imbert 00a28d5eec fix(drafts): disable the "No login required" toggle on draft-only apps
Flipping the toggle called `setPublishState`, which POSTs the new
`policy` through `AppService.updateApp` — that handler's
`UPDATE app ... RETURNING path` finds nothing on a draft-only path
and `not_found_if_none` 404s with "App not found at name …"
(apps.rs:1975). Gate the Toggle on `!newApp` too so the user has to
deploy once before configuring the publish state.
2026-06-07 23:55:30 +02:00
Diego Imbert 6c758ef3ff fix(drafts): disable Diff button on draft-only items across the 4 editors
Diff has no baseline to compare against on draft-only items — the
button used to be gated by the pre-PR `/add` route's own state, but the
`/add → /edit` redirect landed everything under the regular `/edit`
page where the gate was missing.

- ScriptBuilder: gate the topbar Diff on `savedScript.no_deployed`;
  seed `no_deployed: true` on the route's `new_draft` empty NewScript
  so the gate fires before the first deploy.
- FlowBuilder: gate the topbar Diff on `newFlow` (route already sets
  it from `backendFlow.no_deployed` and the new-draft branch).
- AppEditorHeader: gate both the "Diff" dropdown action and the
  Deploy-drawer's "Diff" button on `newApp`.
- RawAppEditorHeader: gate the topbar Diff + the Deploy-drawer's "Diff"
  button on `newApp`.

Each gate also rewrites the tooltip ("Deploy this … once to compare
against the deployed version") so the hover state explains why.
2026-06-07 23:54:26 +02:00
Diego Imbert 5f94207c02 fix(drafts): skip public-secret-URL fetch in the Deploy drawer for draft-only apps
Opening the Deploy drawer on a `/edit/u/{user}/draft_{uuid}` app fired
`AppService.getPublicSecretOfApp` immediately because the gating effect
only checked `appPath != ''` + `savedApp`. The `/secret_of/{path}` route
plain-SELECTs `app.id`, so a draft-only path 404'd with
"App not found at name …" and the public-URL ClipboardPanel spun
forever waiting on `secretUrl`.

Thread the existing `newApp` signal (already on `AppEditorHeader` /
`RawAppEditorHeader`) into `AppEditorHeaderDeploy`, gate the fetch
behind `!newApp`, and render the existing "Deploy this app once to get
the public secret URL" placeholder instead of the spinner for
draft-only items.
2026-06-07 23:49:50 +02:00
Diego Imbert 131eb8078d fix(drafts): render the right shape in View/Edit JSON for draft-only items
The previous fix landed `fapp.value` into the editor, but the
deployed-overlay flattens the bare editable shape into `inner`/the
top-level response — drafts have no nested `.value`. So:

  - App drafts (`{grid, breakpoints, hiddenInlineScripts, …}`) rendered
    as empty (`fapp.value` was undefined).
  - Raw-app drafts 404'd outright: `get_draft=true` with no `rawApp` flag
    can't tell which draft kind to look up, defaults to `app`, doesn't
    find one.

Thread the row's `raw_app` flag from AppRow → `appExport.open(path,
rawApp)` → `getAppByPath({..., rawApp})` so raw-app drafts resolve to
the right `UserDraftItemKind`. Read `fapp.draft` (the bare editable
shape from `fetch_draft_only`) into the JSON editor for draft-only
items — clean payload, no `is_draft` / `no_deployed` / overlay noise.
Save the same bare shape back through the syncer so the regular
editor reads it unchanged on the next mount.
2026-06-07 23:44:33 +02:00
Diego Imbert e21d3e0c5f fix(drafts): make the home-page View/Edit JSON action work on draft-only apps
The "View/Edit JSON" entry on the home page called `AppService.getAppByPath`
without `get_draft=true`, so for draft-only items at `u/{user}/draft_{uuid}`
the backend 404'd with "App not found at path …". Pass `get_draft=true`
and render the synthesized stand-in's editable shape:

- App drafts come back as `{summary, value, path, policy, ...}` — `value`
  is the App definition the editor was working on; show that.
- Raw-app drafts come back as the flattened
  `{files, runnables, data, summary, policy, ...}` with no nested `value`;
  show the whole shape.

On save, draft-only items can't go through `updateApp` (no deployed row).
Route the edit through `UserDraftDbSyncer.save` (with `immediate: true`
so `await` resolves after the POST lands) and relabel the button
"Save draft" + Save icon. Deployed items keep the existing "Deploy"
flow unchanged.
2026-06-07 23:36:27 +02:00
Diego Imbert 05b61b7e80 nit unused 2026-06-07 23:32:26 +02:00
Diego Imbert f08a3d92f8 fix(raw_app): propagate template picker X / Esc dismissal so autosave resumes
The picker mounted `<Modal kind="X" open ...>` (one-way prop, not
`bind:open`). When the user dismissed via X / Esc / click-outside, the
inner Modal flipped its own local `open` to false (hiding the UI) but
never wrote back to the picker's `open` $bindable. The route's
`templatePicker → false` watcher — the one that calls `restartSync`
two ticks after the picker closes — never fired, so autosave stayed
suspended and the user's edits after dismissal were silently dropped.

Switch the inner Modal to `bind:open` so the dismissal bubbles all the
way up to the route's state. "Start without AI" already worked because
its `onStart` handler explicitly sets the picker's `open = false`.
2026-06-07 23:27:56 +02:00