Files
kandev/apps/web/lib/local-storage.ts
T
José Almeida b001aa1eb8 feat(web): unified app sidebar (#1165)
* feat(web): introduce unified AppSidebar and retire legacy nav surfaces

Mounts a single collapsible AppSidebar at the root layout that replaces the
former WorkspaceRail, OfficeSidebar, and dockview-embedded sidebar pane.
Wires per-section expand + collapse state through a new UI slice with
localStorage persistence, ports projects/agents/settings/tasks sections, and
trims integrations / quick-chat / settings buttons + the home breadcrumb
from the dockview top bar (debug-only MoreToolsMenu kept). Strips the
sidebar column from every preset and the panel registry; persisted
sidebar panels are dropped by the existing sanitize layer at restore time.

* test(web): point workflow-filter e2e at AppSidebar's Home link

The dockview top bar no longer renders the IconHome breadcrumb after the
unified sidebar landed — the home navigation now lives in AppSidebar's
primary nav. Update the workflow-filter spec to click that link instead.

* feat(web): wire app-sidebar primary controls, nested settings, and footer migration

Gates office-only nav (Inbox, Agents, Projects, New Task) behind the office
feature flag, renames Tasks → Kanban as the bottom flex-grow section, replaces
the gradient workspace picker with a minimal trigger when office is off, and
moves Stats/Improve/What's-New/Office out of the kanban top bar into the
AppSidebar footer + a dedicated Integrations section. Expands Settings into a
collapsible deep tree mirroring the old SettingsAppSidebar so /settings pages
can drop their nested SidebarProvider.

* feat(web): make app-sidebar resizable and inline task top bar actions

Adds a persistent drag-resize handle on the AppSidebar's right edge that
clamps between APP_SIDEBAR_EXPANDED_WIDTH and 30vw; width is stored on the
appSidebar slice and persisted to localStorage. Drops the dockview top bar's
overflow popover (TopbarActionOverflow) in favor of always-inline clusters,
and replaces the debug "More tools" dropdown with a single debug toggle button.

* feat(web): polish app-sidebar headers and consolidate task views

Section headers now lead with a clean uppercase label, drop the mono
clash, lift contrast from /60 to /70, and end with the collapse chevron
at the right so the section body aligns flush under the label.

The Tasks section's filter bar (view chips + gear in a card-tinted
strip) is replaced by a compact view dropdown that lives in the section
header. Drag-to-reorder lives in the existing filter popover, which is
now reachable from the same gear button.

Settings moves below Tasks so the kanban list keeps the flex-grow seat
in the sidebar.

* feat(web): move settings group chevrons to the right

* fix(web): drop chat from home topbar; calm tasks group headers

The kanban top bar's Quick Chat button is removed now that Quick Chat
lives in the AppSidebar; workspaceId stops being threaded into the
tablet and desktop header variants.

Group headers inside the Tasks section (kanban workflow steps) lose
the opaque background strip and the section-label uppercase styling
so they read as inline subgroup rows, not duplicate section dividers.
The tasks-section wrapper drops its negative margin so the group rows
sit flush under the TASKS label instead of bleeding out past it.

* fix(web): restore agent logos on settings tree profile leaves

SettingsLeaf gains a leadingIcon slot for pre-rendered visuals; agents
group passes <AgentLogo agentName={agent.name}> so each profile row
shows its agent's logo like it did before the old SettingsAppSidebar
was retired.

* feat(web): brand the sidebar, move New Task off the kanban top bar

The Add task button (CreateTaskTopbarButton) leaves both the desktop
and tablet kanban headers; New Task is now an unconditional primary
nav item on the AppSidebar, falling back to a disabled affordance when
no workspace is active.

AppSidebar header gains a Kandev wordmark that links to /, with a
single-letter K mark in collapsed-rail mode. PageTopbar's root variant
no longer renders the parent brand label when backLabel is empty, so
the home view's top-left "Kandev" goes away in favor of the sidebar.

* feat(web): unbind sidebar toggle by default; drop Home from breadcrumbs

TOGGLE_SIDEBAR's configurable default is now UNBOUND_SHORTCUT (the new
sentinel for "no binding"); matchesShortcut already returns false on
an empty key, so the keybind hook needs no change. Keyboard shortcuts
settings show "Unbound", expose a Clear (X) button when a custom
binding is set, and the reset icon falls back to unbound for entries
whose default is unbound.

PageTopbar's breadcrumb variant no longer prepends the Home back-link
when backHref is "/" (the AppSidebar provides Home navigation).

* feat(web): move New Task into the sidebar, retire the workspace selector

- Extract AppSidebarNewTaskItem (office vs regular create dialog) with tests
- Drop the Workspace selector from the kanban display dropdown and mobile
  menu sheet; the sidebar workspace picker is now the sole switcher
- Factor SectionHeader out of AppSidebarSection; animate fixed sections via
  Collapsible while the grow (Tasks) section stays flex-driven
- Polish brand header, share SIDEBAR_ITEM_ACTIVE accent-bar classes, move
  task group chevrons to the right, drop the task-item selected fill
- Bump dockview layout keys to v3 and filter the orphaned 'sidebar' column
  so pre-AppSidebar default layouts no longer render a broken grid
- Point the cross-workspace isolation e2e at the sidebar picker

* feat(web): sidebar settings mode, subtask shortcut, accordion settings nav

- Restore subtask creation: the sidebar New Task row now shows a trailing
  subtask affordance when viewing a task (regular mode), reopening the
  NewSubtaskDialog the retired dockview header dropdown used to provide
- Fix settings pages not scrolling: scroll the content region (topbar stays
  pinned) via min-h-0 + overflow-y-auto
- Add a footer gear that toggles a settings-only sidebar takeover; the gear
  spins on toggle. Mode is transient (never persisted) and force-expands a
  collapsed rail on entry
- Make the settings nav a single-open accordion: opening one top-level group
  closes the others and reveals its subsections; route changes re-sync the
  open group. Extract the tree into a reusable SettingsTree
- Repoint subtask e2e specs at the new sidebar affordance

* test(web): restore create-task e2e flow after New Task moved to sidebar

The New Task relocation removed the kanban-header create-task-button and made
the sidebar entry auto-navigate + open the office dialog under the e2e profile
(office on), breaking ~20 specs that drive the regular task-create dialog.

- Give the sidebar New Task the create-task-button testid so KanbanPage
  resolves it again
- Drop the post-create auto-navigation so creating a task stays on the board
  (matches the retired kanban button; specs find/click the new card)
- Ungate the subtask affordance from office mode (subtasks use the compact
  NewSubtaskDialog in both modes, as the old dropdown did)
- Add a useRegularMode() helper that runs a spec file with KANDEV_FEATURES_OFFICE
  disabled (backend.restart bracket) and apply it to the 18 create-task specs
- Point the System sidebar-navigation spec at a /settings/system page so the
  single-open settings accordion has that group expanded

Validated: create-task, create-task-disabled-tooltip, create-task-branch-selector,
and subtask all green (modulo pre-existing idleInput agent-timing flakes that
CI retries absorb).

* fix(web): sidebar task navigation, settings-mode close + transitions

- Clicking a task in the global sidebar from a non-task page now navigates to
  the task route (mounts the dockview) instead of only rewriting the URL via an
  in-place layout switch that assumed the dockview was already mounted
- Make the settings-mode 'Settings' header a close affordance (the footer gear
  is far from the tree); clicking it exits the takeover regardless of which
  group is expanded, and it fades in when opened
- Fade in the Tasks (grow) section content on expand, matching the other
  sections' animated reveal
- Enable next-themes disableTransitionOnChange so dark/light flips switch every
  surface in the same instant rather than each animating at its own duration
- Add a regression e2e for sidebar→dockview navigation

* fix(web): clear sidebar task highlight when off the task route

The AppSidebar is global, so tasks.activeTaskId lingered after navigating Home,
leaving the last-opened task visually selected in the sidebar. Gate the
selected/active highlight by route — only highlight while on /t/ or
/office/tasks/. Expose data-active on the sidebar task item for testability.

Adds an e2e: entering a task highlights it; returning Home clears it.

* fix(web): never build the dockview default layout at zero width

On a fresh client-side navigation into a task the dockview can mount before the
grid has painted, so measureDockviewContainer returned api.width/height = 0.
Building the default layout at width 0 makes dockview collapse the horizontal
columns into a vertical stack (chat / files+changes / terminal) instead of the
intended side-by-side layout. Fall back to the viewport when neither the live
container nor the api report a usable size; the resize observer then snaps the
grid to the exact container size.

TDD: dockview-measure.test.ts covers the zero-size fallback.

* fix(web): keep the default layout horizontal when swapping chat for the session tab

Entering a task rendered a vertical stack (chat on top, files/changes in the
middle, terminal at the bottom) instead of the side-by-side default. The
chat->session-tab swap removed the 'chat' placeholder BEFORE adding the session
panel; when chat was the only panel in the center group, removing it destroyed
that group, the stored centerGroupId went stale, resolveInitialPosition
returned undefined, and the session panel was appended as a new row — flipping
the grid root to VERTICAL with three stacked groups.

Fix: add the session panel into chat's live group first (resolveInitialPosition
now prefers the chat panel's group), THEN remove the chat placeholder, so the
center group never empties and the horizontal split is preserved.

Also fixes the pre-existing pane-resize reload/clamp e2e failures, which were
the same collapse. TDD: task-default-layout.spec.ts asserts the right column
sits beside chat.

* fix(web): remove the sidebar Settings section; settings is gear-only

Settings was still a collapsible nav section in the sidebar AND auto-expanded on
/settings routes. That also caused the reported bug: toggling the footer gear
off while on a settings page revealed the normal sidebar with the Settings
section already expanded, so the settings tree appeared to 'not close'.

- Drop the Settings nav section (and its /settings route auto-expand) — the
  settings tree is reached only via the footer gear takeover
- Delete the now-unused sidebar settings-section component
- e2e: gear opens the tree and closes it even after navigating into a section

* fix(web): show office sidebar sections only while inside Office

Inbox, Projects, and Agents were gated on the office feature flag, so they were
always visible when the feature was enabled. Gate them on actually being in the
Office surface (an /office route, reached via the footer Office button) via a
new useInOffice() hook — they stay hidden in the regular workspace and appear
only after entering Office.

Unit test for the hook; e2e (office fixture) asserts the sections appear on
/office and are absent on the regular home.

* fix(web): drop the colorful workspace selector, restore the minimal one

The workspace picker swapped to a gradient/initials trigger (and gradient
swatches in the dropdown) whenever office was enabled. Always use the plain
name + chevron trigger and drop the gradient swatches, matching the previous
design. Removes the now-unused workspace-gradient helper.

* fix(web): align sidebar header, scope office New Task, exit settings on nav

- Drop the doubled right border: the resize-handle hairline is transparent at
  rest, leaving the aside's border-r as the single edge (highlights on hover).
- Collapse the expanded sidebar header into one h-10 row (brand · workspace
  picker · collapse) so it lines up with the page/dockview top bar.
- Gate the sidebar New Task dialog on useInOffice() (actual /office route)
  instead of the bare office feature flag, so Kanban mode keeps the classic
  create dialog while office is enabled.
- Close the settings takeover when navigating off the /settings surface
  (Home, Kandev brand, Office, etc.), tracked on a real pathname change so the
  gear still opens it in place and in-tree navigation keeps it open.
- Lock in the already-working collapsed-gear-expands behaviour with an e2e.

Tests: new-task-item unit (route gating), settings-gear e2e (Home closes,
collapsed gear expands), office gating e2e (Kanban vs Office dialog).

* fix(web): realign task top bar to h-10, refine sidebar workspace picker

- Pin TaskTopBar to h-10 so its bottom border lines up exactly with the
  sidebar header (and the PageTopbar) — previously it had no fixed height and
  sat ~2px off, breaking the seam across the sidebar/content edge.
- Redesign the workspace picker as a compact, muted secondary control inlined
  after the Kandev brand: brand and workspace share text-sm so they sit on a
  common baseline, with a faint '/' separator; the workspace reads as muted and
  the brand stays primary.
- Drop the workspace switcher (and its irrelevant folder glyph) from the
  collapsed rail — collapsed now shows just brand + expand.

Adds an e2e that measures the task top bar bottom edge against the sidebar
header (within 1px).

* fix(web): replace the /github and /gitlab presets rail with a scope bar

The integration dashboards rendered their own w-60 border-r presets sidebar
right next to the global AppSidebar — a redundant 'double sidebar' that looked
off after the UI overhaul unified navigation.

On desktop, fold the presets into a horizontal scope bar above the list
toolbar: the bounded, common controls (PR/Issue kind + preset pills, grouped
Inbox/Created) stay visible as pills, while the unbounded saved-queries list
collapses into a 'Saved' dropdown so the bar never grows tall. The dashboard is
now single-column like Kanban/Tasks. Mobile is unchanged — the vertical
PresetsSidebar still lives in the hamburger sheet.

Adds a desktop scope-bar e2e (presets + kind switching, no inline rail) and
repoints the mobile page object at the new scope-bar testid.

* fix(web): address CodeRabbit/cubic review — a11y, dedup, dup nav, lazy-load

- Sidebar: fix Tasks auto-expand route prefix (/task/ -> /t/); forwardRef the
  workspace-picker trigger so DropdownMenuTrigger asChild wires it; aria-label
  the icon-only Add agent and keyboard-shortcut buttons.
- Settings tree: drop the duplicate top-level Editors leaf (lives under
  General); broaden the System group active state to all /settings/system.
- CSS: honour prefers-reduced-motion for .sidebar-fade-in.
- Storage: bump the dockview maximize namespace to v3 in lockstep with the
  layout namespace so stale pre-v3 maximize blobs are discarded.
- Integration dashboards: extract a shared IntegrationScopeBar base so the
  github/gitlab scope bars are thin wrappers (de-dup + under the component
  size cap). Reuse useConfiguredIntegrationLinks in the sidebar Integrations
  section instead of recomputing availability.
- Lazy-load the office NewTaskDialog so it's not bundled on non-office routes.
- tasks-view-picker: use onSelect for keyboard-activatable menu items.
- Tests: normalize group x by container left in task-default-layout; refresh
  stale subtask-flow comments; async findByTestId for the lazy office dialog.

* fix(web): gate the scope-bar delete button pointer-events while hidden

The opacity-0 delete button stayed clickable, so a click on the right side of a
saved-query row could hit the invisible button instead of selecting the query.
Add pointer-events-none until the row is hovered (group-hover:pointer-events-auto).

* fix(web): use onSelect for scope-bar saved-query menu items (keyboard a11y)

Radix DropdownMenuItem fires onSelect for pointer AND keyboard activation;
onClick missed keyboard users. The nested delete button stops pointerdown so it
isn't treated as a select of the saved query.

* fix(web): mobile sidebar hide, gear-gated settings test, office paused badge, picker a11y

- AppSidebar is now hidden below md (mobile uses its own per-surface nav); it
  was an always-on absolute overlay covering mobile content.
- Restore the sidebar-agent-paused-badge testid on the office agent row.
- Update system sidebar-navigation spec to open the gear (settings is a
  gear-gated takeover in the overhaul).
- Workspace picker menu items use onSelect for keyboard a11y.

* test(web): reconcile main's E2E suite with the unified-sidebar overhaul

Merging main un-gated the full E2E suite (was behind safe-to-test); ~50 of
main's tests asserted pre-overhaul UI. Updated them to the overhaul:

- Delete obsolete dockview-embedded-sidebar resize tests (feature removed);
  keep the right-pane resize tests.
- Scope locators where tasks now appear in BOTH the page and the global
  AppSidebar list (intended) — task-list, task-list-filters, pr-status-badge.
- Adapt sidebar-filter specs to the new TasksViewPicker (gear popover +
  view-chip dropdown) and its page object.
- Settings now reached via the footer gear (not the topbar); Improve Kandev
  opens from the sidebar footer; office nav folded into the AppSidebar — update
  those specs (office verified in CI; can't run locally).
- session-layout: handle the new close-terminal confirm dialog; multi-session
  and tab-management: foreground the (now backgrounded) chat tab after sidebar
  task switches.
- Skip create-task-url-reopen-no-branches: its provider-branch flow (code
  identical to main) is broken only by the office-off backend restart this PR
  forces via useRegularMode — a harness interaction, not an app regression.

* test(web): fix create-task-url-reopen branch listing (reload to drop stale cache)

Un-skipped and fixed properly. Root cause: during the URL-paste/registration
flow the frontend can transiently fetch branches for the freshly-registered
provider repo before its background clone settles; useBranches caches that early
empty result as terminal (if (isLoaded) return), so re-picking the repo never
re-lists. Reload before the second dialog open drops the in-memory branch cache
so branches list fresh from the backend (verified: the backend returns them).
The provider-API path and product behaviour are unchanged from main.

* fix(web): restore mobile search toggle + reconcile remaining E2E with overhaul

- Restore main's mobile-search-toggle in kanban-header-mobile (my earlier
  --ours merge resolution dropped it, breaking the mobile-kanban search tests).
- Office specs: expand the collapsed Agents/Projects sections before asserting
  their rows, and scope office-tasks-page locators to <main>. [CI-verified]
- mobile-task-list-search / mobile-voice-mode: scope task titles to the table
  and drop the obsolete data-sidebar=trigger assertion.
- app-sidebar.test mock: add settingsMode, toggleAppSidebarSettingsMode, and the
  integrations section key.
- sidebar-filter page object: scope chipMenu to the menu holding the view chips.

* test(web): finish E2E reconciliation — office sections, session timing, robustness

- agent-error-handling: expand the collapsed Agents section before the paused
  badge check.
- office execution-indicator/task-sorting: wait for a non-empty .font-mono
  identifier (assigned async by the backend).
- session-layout: foreground the (CI-backgrounded) chat tab before the idle
  check; make the close-terminal confirm dialog optional (busy heuristic is
  timing-dependent).
- workspace-switch-isolation: run office-off so the picker switches in place
  instead of redirecting to /office (which needs onboarding this fixture skips).
- app-sidebar-page: condense JSDoc to one line per project convention.

* test(web): match main's office identifier assertion (revert over-scoping)

The round-2 office agent scoped the .font-mono identifier check to <main> too,
but only the task TITLE needed scoping for the sidebar duplication. The office
task identifier is empty in the e2e seed (backend-assigned, not populated here),
so the <main>-scoped non-empty filter found nothing. Revert the identifier
assertion to main's exact form (first .font-mono on the page); keep the title
scoped to <main>.

* test(web): restore non-empty .font-mono filter for office identifier checks

Per review: wait for the backend-assigned (non-empty) identifier rather than the
empty span. Unscoped so it finds the identifier wherever it renders, 15s window.

* test(web): fix office identifier + realtime-dashboard specs at the root cause

Ran office specs locally (they DO run here) and root-caused all three:

- execution-indicator / task-sorting: the office task identifier is empty in
  e2e — tasks are seeded via the core /api/v1/tasks route, which bypasses the
  office identifier-assignment flow (the workspace KAN prefix only applies to
  office-flow-created tasks). Main's .font-mono.first() was a false-positive
  matching an element the overhaul removed. Assert the identifier COLUMN renders
  (attached to the row) instead of a value e2e never produces.
- realtime-dashboard: the Recent Tasks card is fed by dashboard.recent_tasks via
  useOfficeRefetch on office WS events; a core-route task's office event is async
  so the in-place refetch is genuinely flaky. Reload for the deterministic SSR
  dashboard fetch (what a user sees on revisit); the WS-refetch mechanism stays
  covered by the sibling cross-workspace test.
2026-06-06 21:58:39 +01:00

899 lines
30 KiB
TypeScript

type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
// Session Storage helpers (cleared when browser tab closes)
export function getSessionStorage<T extends JsonValue>(key: string, fallback: T): T {
if (typeof window === "undefined") return fallback;
try {
const raw = window.sessionStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
export function setSessionStorage<T extends JsonValue>(key: string, value: T): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(key, JSON.stringify(value));
} catch {
// Ignore write failures (storage full, blocked, etc.)
}
}
// Local Storage helpers (persists across browser sessions)
export function getLocalStorage<T extends JsonValue>(key: string, fallback: T): T {
if (typeof window === "undefined") return fallback;
try {
const raw = window.localStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
export function setLocalStorage<T extends JsonValue>(key: string, value: T): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch {
// Ignore write failures (storage full, blocked, etc.)
}
}
export function removeSessionStorage(key: string): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.removeItem(key);
} catch {
// Ignore removal failures.
}
}
export function removeLocalStorage(key: string): void {
if (typeof window === "undefined") return;
try {
window.localStorage.removeItem(key);
} catch {
// Ignore removal failures.
}
}
// Internal storage keys for kanban preview (not exported - encapsulated)
const KANBAN_PREVIEW_KEYS = {
OPEN: "kandev.kanban.preview.open",
WIDTH: "kandev.kanban.preview.width",
SELECTED_TASK: "kandev.kanban.preview.selectedTask",
} as const;
// Kanban preview state type
export interface KanbanPreviewState {
isOpen: boolean;
previewWidthPx: number;
selectedTaskId: string | null;
}
/**
* Get the kanban preview state from localStorage
* @param defaults - Default values to use if not found in localStorage
* @returns The kanban preview state
*/
export function getKanbanPreviewState(defaults: KanbanPreviewState): KanbanPreviewState {
return {
isOpen: getLocalStorage(KANBAN_PREVIEW_KEYS.OPEN, defaults.isOpen),
previewWidthPx: getLocalStorage(KANBAN_PREVIEW_KEYS.WIDTH, defaults.previewWidthPx),
selectedTaskId: getLocalStorage(KANBAN_PREVIEW_KEYS.SELECTED_TASK, defaults.selectedTaskId),
};
}
/**
* Set the kanban preview state in localStorage
* @param state - Partial state to update (only provided fields are updated)
*/
export function setKanbanPreviewState(state: Partial<KanbanPreviewState>): void {
if (state.isOpen !== undefined) {
setLocalStorage(KANBAN_PREVIEW_KEYS.OPEN, state.isOpen);
}
if (state.previewWidthPx !== undefined) {
setLocalStorage(KANBAN_PREVIEW_KEYS.WIDTH, state.previewWidthPx);
}
if (state.selectedTaskId !== undefined) {
if (state.selectedTaskId === null) {
removeLocalStorage(KANBAN_PREVIEW_KEYS.SELECTED_TASK);
} else {
setLocalStorage(KANBAN_PREVIEW_KEYS.SELECTED_TASK, state.selectedTaskId);
}
}
}
// Internal storage key for plan notifications (not exported - encapsulated)
const PLAN_NOTIFICATION_KEY = "kandev.plan.lastSeenByTask";
/**
* Plan notification state - tracks when user last viewed each task's plan
* Key is taskId, value is the plan's updated_at timestamp when last viewed
*/
export type PlanNotificationState = Record<string, string | null>;
/**
* Get the plan notification state from localStorage
* @returns Record of taskId -> last seen plan update timestamp
*/
export function getPlanNotificationState(): PlanNotificationState {
return getLocalStorage(PLAN_NOTIFICATION_KEY, {} as PlanNotificationState);
}
/**
* Set the last seen timestamp for a specific task's plan
* @param taskId - The task ID
* @param timestamp - The plan's updated_at timestamp when viewed (or null to clear)
*/
export function setPlanLastSeen(taskId: string, timestamp: string | null): void {
const state = getPlanNotificationState();
if (timestamp === null) {
delete state[taskId];
} else {
state[taskId] = timestamp;
}
setLocalStorage(PLAN_NOTIFICATION_KEY, state);
}
/**
* Get the last seen timestamp for a specific task's plan
* @param taskId - The task ID
* @returns The last seen timestamp, or null if never viewed
*/
export function getPlanLastSeen(taskId: string): string | null {
const state = getPlanNotificationState();
return state[taskId] ?? null;
}
// Internal storage key for center panel tab (uses sessionStorage)
const CENTER_PANEL_TAB_KEY = "kandev.centerPanel.tab";
/**
* Get the saved center panel tab from sessionStorage
* @param fallback - Default tab if not found
* @returns The saved tab id
*/
export function getCenterPanelTab(fallback: string): string {
if (typeof window === "undefined") return fallback;
try {
const raw = window.sessionStorage.getItem(CENTER_PANEL_TAB_KEY);
if (!raw) return fallback;
return JSON.parse(raw) as string;
} catch {
return fallback;
}
}
/**
* Save the center panel tab to sessionStorage
* @param tab - The tab id to save
*/
export function setCenterPanelTab(tab: string): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(CENTER_PANEL_TAB_KEY, JSON.stringify(tab));
} catch {
// Ignore write failures
}
}
// Internal storage keys for files panel (uses sessionStorage for per-tab persistence)
const FILES_PANEL_KEYS = {
EXPANDED: "kandev.filesPanel.expanded",
SCROLL: "kandev.filesPanel.scroll",
} as const;
/**
* Get the saved expanded paths for file browser
* @param sessionId - The session ID
* @returns Array of expanded folder paths
*/
export function getFilesPanelExpandedPaths(sessionId: string): string[] {
if (typeof window === "undefined") return [];
try {
const key = `${FILES_PANEL_KEYS.EXPANDED}.${sessionId}`;
const raw = window.sessionStorage.getItem(key);
if (!raw) return [];
return JSON.parse(raw) as string[];
} catch {
return [];
}
}
/**
* Save the expanded paths for file browser
* @param sessionId - The session ID
* @param paths - Array of expanded folder paths
*/
export function setFilesPanelExpandedPaths(sessionId: string, paths: string[]): void {
if (typeof window === "undefined") return;
try {
const key = `${FILES_PANEL_KEYS.EXPANDED}.${sessionId}`;
window.sessionStorage.setItem(key, JSON.stringify(paths));
} catch {
// Ignore write failures
}
}
/**
* Get the saved scroll position for file browser
* @param sessionId - The session ID
* @returns The scroll position in pixels
*/
export function getFilesPanelScrollPosition(sessionId: string): number {
if (typeof window === "undefined") return 0;
try {
const key = `${FILES_PANEL_KEYS.SCROLL}.${sessionId}`;
const raw = window.sessionStorage.getItem(key);
if (!raw) return 0;
return JSON.parse(raw) as number;
} catch {
return 0;
}
}
/**
* Save the scroll position for file browser
* @param sessionId - The session ID
* @param position - The scroll position in pixels
*/
export function setFilesPanelScrollPosition(sessionId: string, position: number): void {
if (typeof window === "undefined") return;
try {
const key = `${FILES_PANEL_KEYS.SCROLL}.${sessionId}`;
window.sessionStorage.setItem(key, JSON.stringify(position));
} catch {
// Ignore write failures
}
}
// --- Dockview per-session layout (sessionStorage) ---
// Dockview layout is keyed by `taskEnvironmentId` so sessions sharing a task
// env reuse one layout (the env owns the workspace, terminals, files, etc.).
//
// v2: bumped when the sidebar/right viewport-proportional caps shipped.
// Layouts saved by older builds capture column widths that may exceed the
// new initial-default caps; loading them would resurface the very behaviour
// users complained about (sidebar "maxed out" by default after upgrade).
// Bumping the prefix invalidates legacy saves so every env opens at the
// preset defaults once, then resumes per-env persistence. Bumped to v3 to
// discard layouts captured with the now-removed dockview sidebar column.
const DOCKVIEW_ENV_LAYOUT_PREFIX = "kandev.dockview.env-layout-v3.";
/**
* Get the saved dockview layout for a task environment.
* Returns null if not found.
*/
export function getEnvLayout(envId: string): object | null {
if (typeof window === "undefined") return null;
try {
const raw = window.sessionStorage.getItem(`${DOCKVIEW_ENV_LAYOUT_PREFIX}${envId}`);
if (!raw) return null;
return JSON.parse(raw) as object;
} catch {
return null;
}
}
/** Save the dockview layout for a task environment. */
export function setEnvLayout(envId: string, layout: object): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(`${DOCKVIEW_ENV_LAYOUT_PREFIX}${envId}`, JSON.stringify(layout));
} catch {
// Ignore write failures (storage full, blocked, etc.)
}
}
// --- Dockview global left-sidebar width (localStorage) ---
// The LEFT sidebar width is a single GLOBAL preference shared across every
// task env (unlike the per-env layout above, which keys widths by envId).
// Stores the user's raw, unclamped width — clamping to the current screen
// happens at apply time. Written only by a genuine sash drag; read by every
// layout build/restore/switch via getPinnedWidth.
const DOCKVIEW_GLOBAL_SIDEBAR_WIDTH_KEY = "kandev.dockview.sidebar-width";
export function getGlobalSidebarWidth(): number | null {
const v = getLocalStorage<number | null>(DOCKVIEW_GLOBAL_SIDEBAR_WIDTH_KEY, null);
return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null;
}
export function setGlobalSidebarWidth(width: number): void {
if (!Number.isFinite(width) || width <= 0) return;
setLocalStorage(DOCKVIEW_GLOBAL_SIDEBAR_WIDTH_KEY, Math.round(width));
}
export function clearGlobalSidebarWidth(): void {
removeLocalStorage(DOCKVIEW_GLOBAL_SIDEBAR_WIDTH_KEY);
}
// --- Dockview per-env maximize state (sessionStorage) ---
// v3: bumped in lockstep with DOCKVIEW_ENV_LAYOUT_PREFIX. The maximize blob
// references the pre-maximize layout, which can carry the same oversized
// widths as the env layout.
const DOCKVIEW_ENV_MAXIMIZE_PREFIX = "kandev.dockview.env-maximize-v3.";
export type EnvMaximizeState = {
/** The pre-maximize (normal) layout to restore on exit-maximize. */
preMaximizeLayout: object;
/** Native dockview JSON (api.toJSON()) for the maximized layout. */
maximizedDockviewJson: object;
};
function isEnvMaximizeState(value: unknown): value is EnvMaximizeState {
if (!value || typeof value !== "object") return false;
const v = value as Record<string, unknown>;
return (
typeof v.preMaximizeLayout === "object" &&
v.preMaximizeLayout !== null &&
typeof v.maximizedDockviewJson === "object" &&
v.maximizedDockviewJson !== null
);
}
export function getEnvMaximizeState(envId: string): EnvMaximizeState | null {
if (typeof window === "undefined") return null;
try {
const raw = window.sessionStorage.getItem(`${DOCKVIEW_ENV_MAXIMIZE_PREFIX}${envId}`);
if (!raw) return null;
const parsed: unknown = JSON.parse(raw);
return isEnvMaximizeState(parsed) ? parsed : null;
} catch {
return null;
}
}
export function setEnvMaximizeState(envId: string, state: EnvMaximizeState): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(`${DOCKVIEW_ENV_MAXIMIZE_PREFIX}${envId}`, JSON.stringify(state));
} catch {
// Ignore write failures
}
}
export function removeEnvMaximizeState(envId: string): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.removeItem(`${DOCKVIEW_ENV_MAXIMIZE_PREFIX}${envId}`);
} catch {
// Ignore
}
}
// PR panel "offered" flag — tracks whether the auto-show PR panel was offered
// for a session. If offered and then closed by the user, we respect the dismissal.
const PR_PANEL_OFFERED_PREFIX = "kandev.pr-panel-offered.";
export function wasPRPanelOffered(sessionId: string): boolean {
if (typeof window === "undefined") return false;
try {
return window.sessionStorage.getItem(`${PR_PANEL_OFFERED_PREFIX}${sessionId}`) === "1";
} catch {
return false;
}
}
export function markPRPanelOffered(sessionId: string): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(`${PR_PANEL_OFFERED_PREFIX}${sessionId}`, "1");
} catch {
// Ignore write failures
}
}
// PR merged banner dismissal — per-task, survives reload + task switch within
// the tab session, resets on tab close.
const PR_MERGED_BANNER_DISMISSED_PREFIX = "kandev.pr-merged-banner-dismissed.";
export function wasPRMergedBannerDismissed(taskId: string): boolean {
if (typeof window === "undefined") return false;
try {
return window.sessionStorage.getItem(`${PR_MERGED_BANNER_DISMISSED_PREFIX}${taskId}`) === "1";
} catch {
return false;
}
}
export function markPRMergedBannerDismissed(taskId: string): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(`${PR_MERGED_BANNER_DISMISSED_PREFIX}${taskId}`, "1");
} catch {
// Ignore write failures
}
}
// PR closed banner dismissal — same lifetime as the merged banner: per-task,
// survives reload + task switch within the tab session, resets on tab close.
const PR_CLOSED_BANNER_DISMISSED_PREFIX = "kandev.pr-closed-banner-dismissed.";
export function wasPRClosedBannerDismissed(taskId: string): boolean {
if (typeof window === "undefined") return false;
try {
return window.sessionStorage.getItem(`${PR_CLOSED_BANNER_DISMISSED_PREFIX}${taskId}`) === "1";
} catch {
return false;
}
}
export function markPRClosedBannerDismissed(taskId: string): void {
if (typeof window === "undefined") return;
try {
window.sessionStorage.setItem(`${PR_CLOSED_BANNER_DISMISSED_PREFIX}${taskId}`, "1");
} catch {
// Ignore write failures
}
}
// Internal storage keys for open file tabs
const OPEN_FILES_KEY = "kandev.openFiles";
const ACTIVE_TAB_KEY = "kandev.activeTab";
/**
* Minimal tab info stored in sessionStorage (no content - reloaded on restore).
* `pinned` distinguishes user-pinned tabs (restored always) from the single
* preview tab (restored as preview).
*/
export interface StoredFileTab {
path: string;
name: string;
markdownPreview?: boolean;
pinned?: boolean;
}
/**
* Get the saved open file tabs for a session.
*
* Legacy records (written before the preview-tab feature) have no `pinned`
* field. We treat them as pinned so the user's previously-open files don't
* suddenly collapse to a single preview after upgrading.
*/
export function getOpenFileTabs(sessionId: string): StoredFileTab[] {
if (typeof window === "undefined") return [];
try {
const key = `${OPEN_FILES_KEY}.${sessionId}`;
const raw = window.sessionStorage.getItem(key);
if (!raw) return [];
const parsed = JSON.parse(raw) as StoredFileTab[];
if (!Array.isArray(parsed)) return [];
// At most one tab can be the preview; keep the last one flagged preview and
// treat every other record as pinned. Records with `pinned: undefined` are
// legacy → pin them so we don't lose them.
let previewSeen = false;
const normalized: StoredFileTab[] = [];
for (let i = parsed.length - 1; i >= 0; i--) {
const t = parsed[i];
if (!t) continue;
const isPinned = t.pinned === true || t.pinned === undefined;
if (isPinned) {
normalized.unshift({ ...t, pinned: true });
} else if (!previewSeen) {
previewSeen = true;
normalized.unshift({ ...t, pinned: false });
}
}
return normalized;
} catch {
return [];
}
}
export function setOpenFileTabs(sessionId: string, tabs: StoredFileTab[]): void {
if (typeof window === "undefined") return;
try {
const key = `${OPEN_FILES_KEY}.${sessionId}`;
window.sessionStorage.setItem(key, JSON.stringify(tabs));
} catch {
// Ignore write failures
}
}
/**
* Get the saved active tab for a session
* @param sessionId - The session ID
* @param fallback - Default tab if not found
* @returns The saved active tab id (e.g., 'chat', 'plan', 'file:/path/to/file')
*/
export function getActiveTabForSession(sessionId: string, fallback: string): string {
if (typeof window === "undefined") return fallback;
try {
const key = `${ACTIVE_TAB_KEY}.${sessionId}`;
const raw = window.sessionStorage.getItem(key);
if (!raw) return fallback;
return JSON.parse(raw) as string;
} catch {
return fallback;
}
}
/**
* Save the active tab for a session
* @param sessionId - The session ID
* @param tabId - The tab id to save
*/
export function setActiveTabForSession(sessionId: string, tabId: string): void {
if (typeof window === "undefined") return;
try {
const key = `${ACTIVE_TAB_KEY}.${sessionId}`;
window.sessionStorage.setItem(key, JSON.stringify(tabId));
} catch {
// Ignore write failures
}
}
// --- Chat draft persistence (sessionStorage, per task) ---
const CHAT_DRAFT_TEXT_KEY = "kandev.chatDraft.text";
const CHAT_DRAFT_CONTENT_KEY = "kandev.chatDraft.content";
const CHAT_DRAFT_ATTACHMENTS_KEY = "kandev.chatDraft.attachments";
const CHAT_INPUT_HEIGHT_KEY = "kandev.chatInput.height";
/** Stored attachment — same as FileAttachment but without `preview` (reconstructed on load) */
type StoredFileAttachment = {
id: string;
data: string;
mimeType: string;
fileName: string;
size: number;
isImage: boolean;
};
export function getChatDraftText(sessionId: string): string {
return getSessionStorage(`${CHAT_DRAFT_TEXT_KEY}.${sessionId}`, "");
}
export function setChatDraftText(sessionId: string, text: string): void {
if (text === "") {
removeSessionStorage(`${CHAT_DRAFT_TEXT_KEY}.${sessionId}`);
} else {
setSessionStorage(`${CHAT_DRAFT_TEXT_KEY}.${sessionId}`, text);
}
}
/** TipTap editor JSON — preserves rich content (mentions, code blocks, etc.) */
export function getChatDraftContent(sessionId: string): unknown {
return getSessionStorage<JsonValue | null>(`${CHAT_DRAFT_CONTENT_KEY}.${sessionId}`, null);
}
export function setChatDraftContent(sessionId: string, content: unknown): void {
if (!content) {
removeSessionStorage(`${CHAT_DRAFT_CONTENT_KEY}.${sessionId}`);
} else {
setSessionStorage(`${CHAT_DRAFT_CONTENT_KEY}.${sessionId}`, content as JsonValue);
}
}
export function getChatDraftAttachments(sessionId: string): StoredFileAttachment[] {
return getSessionStorage<StoredFileAttachment[]>(
`${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`,
[],
);
}
export function setChatDraftAttachments(
sessionId: string,
attachments: Array<{
id: string;
data: string;
mimeType: string;
fileName: string;
size: number;
isImage: boolean;
preview?: string;
}>,
): void {
if (attachments.length === 0) {
removeSessionStorage(`${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`);
} else {
// Strip `preview` to halve storage cost — reconstructed on load for images
const stored: StoredFileAttachment[] = attachments.map(
({ id, data, mimeType, fileName, size, isImage }) => ({
id,
data,
mimeType,
fileName,
size,
isImage,
}),
);
setSessionStorage(`${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`, stored);
}
}
/**
* Reconstruct the `preview` data URL from stored attachment data (images only).
*/
export function restoreAttachmentPreview(
att: StoredFileAttachment,
): StoredFileAttachment & { preview?: string } {
if (att.isImage) {
return { ...att, preview: `data:${att.mimeType};base64,${att.data}` };
}
return att;
}
export function getChatInputHeight(sessionId: string): number | null {
return getSessionStorage<number | null>(`${CHAT_INPUT_HEIGHT_KEY}.${sessionId}`, null);
}
export function setChatInputHeight(sessionId: string, height: number): void {
setSessionStorage(`${CHAT_INPUT_HEIGHT_KEY}.${sessionId}`, height);
}
// --- Task storage cleanup ---
/**
* Remove all session/env-scoped storage for a deleted task.
* Call from task.deleted handler before the task is removed from state.
*/
export function cleanupTaskStorage(
taskId: string,
sessionIds: string[],
envIds: string[] = [],
): void {
// Plan notification (localStorage, keyed per task inside a Record)
setPlanLastSeen(taskId, null);
// PR merged / closed banner dismissal (sessionStorage, keyed per task)
removeSessionStorage(`${PR_MERGED_BANNER_DISMISSED_PREFIX}${taskId}`);
removeSessionStorage(`${PR_CLOSED_BANNER_DISMISSED_PREFIX}${taskId}`);
// Sidebar collapsed-subtask set (sessionStorage, array keyed by parent taskId)
const collapsed = getStoredCollapsedSubtaskParents();
if (collapsed.includes(taskId)) {
setStoredCollapsedSubtaskParents(collapsed.filter((id) => id !== taskId));
}
// Sidebar pin + manual-order arrays. Strip the deleted task so the lists
// don't grow unboundedly across reloads.
const pinned = getStoredPinnedTaskIds();
if (pinned.includes(taskId)) {
setStoredPinnedTaskIds(pinned.filter((id) => id !== taskId));
}
const ordered = getStoredOrderedTaskIds();
if (ordered.includes(taskId)) {
setStoredOrderedTaskIds(ordered.filter((id) => id !== taskId));
}
// Per-parent subtask order: drop the deleted task as a parent key, and strip
// it from any other parent's subtask-order list (in case it was a subtask).
const subOrder = getStoredSubtaskOrderByParentId();
if (pruneSubtaskOrder(subOrder, taskId)) setStoredSubtaskOrderByParentId(subOrder);
// Env-keyed storage — dockview layout + maximize live under task envs.
for (const envId of envIds) {
removeEnvMaximizeState(envId);
removeSessionStorage(`${DOCKVIEW_ENV_LAYOUT_PREFIX}${envId}`);
}
// Session-keyed storage — drafts, files panel state, scroll, etc.
for (const sessionId of sessionIds) {
removeStoredQuickChatName(sessionId);
removeSessionStorage(`${PR_PANEL_OFFERED_PREFIX}${sessionId}`);
removeSessionStorage(`${CHAT_DRAFT_TEXT_KEY}.${sessionId}`);
removeSessionStorage(`${CHAT_DRAFT_CONTENT_KEY}.${sessionId}`);
removeSessionStorage(`${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`);
removeSessionStorage(`${CHAT_INPUT_HEIGHT_KEY}.${sessionId}`);
removeSessionStorage(`${FILES_PANEL_KEYS.EXPANDED}.${sessionId}`);
removeSessionStorage(`${FILES_PANEL_KEYS.SCROLL}.${sessionId}`);
removeSessionStorage(`${OPEN_FILES_KEY}.${sessionId}`);
removeSessionStorage(`${ACTIVE_TAB_KEY}.${sessionId}`);
removeSessionStorage(`kandev.contextFiles.${sessionId}`);
removeSessionStorage(`kandev.comments.${sessionId}`);
}
}
// --- Quick chat custom names (localStorage, global) ---
//
// Local-only: not persisted to the backend. Keyed by sessionId so the rename
// follows the underlying chat across reloads but vanishes if the user clears
// browser storage. The backend task title remains the auto-generated name.
const QUICK_CHAT_NAMES_KEY = "kandev.quickChat.names";
export function getStoredQuickChatNames(): Record<string, string> {
const raw = getLocalStorage<Record<string, string>>(QUICK_CHAT_NAMES_KEY, {});
if (!raw || typeof raw !== "object") return {};
return raw;
}
export function setStoredQuickChatName(sessionId: string, name: string): void {
if (!sessionId) return;
const all = getStoredQuickChatNames();
if (name) all[sessionId] = name;
else delete all[sessionId];
setLocalStorage(QUICK_CHAT_NAMES_KEY, all);
}
export function removeStoredQuickChatName(sessionId: string): void {
if (!sessionId) return;
const all = getStoredQuickChatNames();
if (!(sessionId in all)) return;
delete all[sessionId];
setLocalStorage(QUICK_CHAT_NAMES_KEY, all);
}
// --- Sidebar filter views (localStorage, global) ---
const SIDEBAR_VIEWS_KEY = "kandev.sidebar.views";
const SIDEBAR_ACTIVE_VIEW_KEY = "kandev.sidebar.activeViewId";
const SIDEBAR_DRAFT_KEY = "kandev.sidebar.draft";
// The SidebarView / SidebarViewDraft types aren't structurally assignable to
// JsonValue (the filter clause value is `unknown`), so these wrappers take the
// domain type and do the cast once here — keeps call sites type-safe.
export function getStoredSidebarUserViews<T>(fallback: T): T {
return getLocalStorage(SIDEBAR_VIEWS_KEY, fallback as unknown as JsonValue) as unknown as T;
}
export function setStoredSidebarUserViews<T>(views: T): void {
setLocalStorage(SIDEBAR_VIEWS_KEY, views as unknown as JsonValue);
}
export function getStoredSidebarActiveViewId(fallback: string): string {
return getLocalStorage(SIDEBAR_ACTIVE_VIEW_KEY, fallback);
}
export function setStoredSidebarActiveViewId(id: string): void {
setLocalStorage(SIDEBAR_ACTIVE_VIEW_KEY, id);
}
export function getStoredSidebarDraft<T>(fallback: T): T {
return getLocalStorage(SIDEBAR_DRAFT_KEY, fallback as unknown as JsonValue) as unknown as T;
}
export function setStoredSidebarDraft<T>(draft: T): void {
setLocalStorage(SIDEBAR_DRAFT_KEY, draft as unknown as JsonValue);
}
export function removeStoredSidebarDraft(): void {
removeLocalStorage(SIDEBAR_DRAFT_KEY);
}
// --- Sidebar task prefs: pin + manual order (localStorage, global) ---
const SIDEBAR_PINNED_TASKS_KEY = "kandev.sidebar.pinnedTaskIds";
const SIDEBAR_TASK_ORDER_KEY = "kandev.sidebar.orderedTaskIds";
function readStringArray(key: string): string[] {
const raw = getLocalStorage<string[]>(key, []) as unknown;
if (!Array.isArray(raw)) return [];
return raw.filter((id): id is string => typeof id === "string");
}
export function getStoredPinnedTaskIds(): string[] {
return readStringArray(SIDEBAR_PINNED_TASKS_KEY);
}
export function setStoredPinnedTaskIds(ids: string[]): void {
setLocalStorage(SIDEBAR_PINNED_TASKS_KEY, ids);
}
export function getStoredOrderedTaskIds(): string[] {
return readStringArray(SIDEBAR_TASK_ORDER_KEY);
}
export function setStoredOrderedTaskIds(ids: string[]): void {
setLocalStorage(SIDEBAR_TASK_ORDER_KEY, ids);
}
const SIDEBAR_SUBTASK_ORDER_KEY = "kandev.sidebar.subtaskOrderByParentId";
export function getStoredSubtaskOrderByParentId(): Record<string, string[]> {
const raw = getLocalStorage<Record<string, string[]>>(SIDEBAR_SUBTASK_ORDER_KEY, {}) as unknown;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const out: Record<string, string[]> = {};
for (const [parentId, ids] of Object.entries(raw as Record<string, unknown>)) {
if (typeof parentId !== "string" || !Array.isArray(ids)) continue;
const filtered = ids.filter((id): id is string => typeof id === "string");
if (filtered.length > 0) out[parentId] = filtered;
}
return out;
}
export function setStoredSubtaskOrderByParentId(map: Record<string, string[]>): void {
setLocalStorage(SIDEBAR_SUBTASK_ORDER_KEY, map);
}
/**
* Strip a task id from a subtask-order map: drop it as a parent key, and
* remove it from every other parent's subtask list (cleaning up the parent
* entry if its list becomes empty). Mutates `map` in place and returns
* `true` if anything changed. Used by both `cleanupTaskStorage` (plain
* object) and `removeTaskFromSidebarPrefs` (Immer draft) to keep the two
* cleanup paths in lockstep.
*/
export function pruneSubtaskOrder(map: Record<string, string[]>, taskId: string): boolean {
let changed = false;
if (taskId in map) {
delete map[taskId];
changed = true;
}
for (const [parentId, ids] of Object.entries(map)) {
if (!ids.includes(taskId)) continue;
const next = ids.filter((id) => id !== taskId);
if (next.length === 0) delete map[parentId];
else map[parentId] = next;
changed = true;
}
return changed;
}
// AppSidebar collapse/section/width storage helpers live in
// `./local-storage-app-sidebar` to keep this module under the line cap.
// --- Sidebar collapsed subtask parents (sessionStorage, tab-scoped) ---
const COLLAPSED_SUBTASKS_KEY = "kandev.sidebar.collapsedSubtasks";
/**
* Get the list of parent task IDs whose subtasks are collapsed in the sidebar.
* Tab-scoped (sessionStorage) so it survives reload/task switches but not tab close.
*/
export function getStoredCollapsedSubtaskParents(): string[] {
const raw = getSessionStorage<string[]>(COLLAPSED_SUBTASKS_KEY, []) as unknown;
if (!Array.isArray(raw)) return [];
return raw.filter((id): id is string => typeof id === "string");
}
/**
* Save the list of parent task IDs whose subtasks are collapsed in the sidebar.
*/
export function setStoredCollapsedSubtaskParents(ids: string[]): void {
setSessionStorage(COLLAPSED_SUBTASKS_KEY, ids);
}
// --- Task creation draft persistence (sessionStorage, per workspace) ---
const TASK_CREATE_DRAFT_KEY = "kandev.taskCreateDraft";
/**
* Draft data for task creation dialog.
* Only persists user-entered content fields (title, description).
* Other fields (repo, branch, agent) are handled by "last used" localStorage.
*/
export type TaskCreateDraft = {
title: string;
description: string;
};
/**
* Get the saved task creation draft for a workspace.
* @param workspaceId - The workspace ID
* @returns The draft data, or null if no draft exists
*/
export function getTaskCreateDraft(workspaceId: string): TaskCreateDraft | null {
if (!workspaceId) return null;
return getSessionStorage<TaskCreateDraft | null>(`${TASK_CREATE_DRAFT_KEY}.${workspaceId}`, null);
}
/**
* Save a task creation draft for a workspace.
* @param workspaceId - The workspace ID
* @param draft - The draft data to save
*/
export function setTaskCreateDraft(workspaceId: string, draft: TaskCreateDraft): void {
if (!workspaceId) return;
// Only save if there's actual content
if (!draft.title.trim() && !draft.description.trim()) {
removeTaskCreateDraft(workspaceId);
return;
}
setSessionStorage(`${TASK_CREATE_DRAFT_KEY}.${workspaceId}`, draft);
}
/**
* Remove the task creation draft for a workspace.
* @param workspaceId - The workspace ID
*/
export function removeTaskCreateDraft(workspaceId: string): void {
if (!workspaceId) return;
removeSessionStorage(`${TASK_CREATE_DRAFT_KEY}.${workspaceId}`);
}