f6f45b5777
* feat(web): add sidebar view types and apply-view engine
Introduces the typed representation of a sidebar view (filter clauses,
sort spec, group key) and the pure engine that applies a view to a list
of tasks to produce a filtered, sorted, grouped result.
* feat(web): add built-in sidebar view presets
Provides the four shipped presets (All tasks, No PR reviews, Active,
Archived). The 'No PR reviews' preset filters out PR-watcher tasks that
would otherwise crowd the sidebar.
* feat(web): persist sidebar views in ui store
Adds sidebar view state to the ui slice with draft semantics for saved
views, localStorage persistence of active view + user-created views, and
root store wiring.
* feat(web): add filter dimension registry and clause editor
Registry of filterable task dimensions (status, workspace, workflow, task
type, etc.) plus the primitive UI pieces — clause editor, sort picker,
group picker, and a hook that supplies operator and value options for a
selected dimension.
* feat(web): add sidebar filter bar, popover, and view manager
Composes the filter primitives into the user-facing surfaces: the top
filter bar, the popover that hosts clause editing and sort/group
selection, the chips that switch between views, and the manager for
saving, renaming, and deleting user views.
* refactor(web): extract NewTaskButton component
Pulls the Create Task button and its command-palette registration into a
standalone memoized component in preparation for reuse across sidebar
surfaces.
* feat(web): integrate filter/view system into task sidebar
Wires the filter bar, view chips, and apply-view engine into the task
sidebar (desktop and mobile sheet). Updates task-switcher to consume the
grouped list from the engine and adds mock data for tests and previews.
* test(web): add e2e coverage for sidebar filter/view system
Page object for the filter popover plus Playwright specs covering built-in
presets, clause editing, sort/group, saved-view draft semantics, and
persistence across reloads.
* refactor(web): trim sidebar built-in views to a single seeded default
Drop the "No PR reviews", "Active", and "Archived" built-in view presets
and the isBuiltIn protection flag. The sidebar now seeds a single "All
tasks" view on first load; users can rename, overwrite, or delete it like
any other view. Deletion is guarded against removing the last remaining
view so the user can never lock themselves out.
* fix(web): humanize executor type labels in sidebar filter and grouping
The executor-type filter dropdown and group-by label were rendering raw
backend identifiers like "worktree" and "local_docker". Route both
through the existing getExecutorLabel() helper so the sidebar shows
"Worktree" and "Local Docker" like the rest of the app.
* feat(web): replace "Has PR" filter with "Is PR review"
The old dimension matched any task with an associated PR, including
tasks a user manually linked. The new dimension isolates tasks created
by the GitHub PR-review watcher specifically, which is what the filter
is useful for — hiding a wall of auto-generated review tasks.
The flag is derived from the review_watch_id metadata key the backend
already stamps onto watcher-created tasks, threaded through the kanban
snapshot and into the sidebar TaskSwitcherItem. A small migration drops
unknown dimensions (including the old "hasPR") from stored views so the
popover does not crash when reading legacy data.
* fix(web): tighten sidebar filter popover layout
Reduce the popover width (w-96 → w-[22rem]), trim section padding
(p-3 → p-2.5) and label margins (mb-2 → mb-1.5), and drop the
"No filters applied." placeholder. Extract a shared SectionLabel to
keep the three section headers visually aligned.
* feat(web): show workflow step color dot in sidebar filter dropdown
Surface the step color on the workflow-step filter's value dropdown so
each option renders with the same coloured circle used elsewhere (task
switcher, kanban column, command panel). Adds an optional color field
on filter value options; only workflow-step options populate it today.
* feat(web): replace cramped in/not-in filter editor with a multiselect dropdown
The previous "in/not in" value input rendered selected values as tiny
10px pills inside a fixed-height row that overflowed and truncated as
the list of options grew. Replace it with a combobox-style multiselect
(Popover + Command) that shows a compact summary ("N selected" or the
single label with its color dot) and opens a searchable, scrollable
list with check indicators on click.
* fix(web): show workflow and step names (not UUIDs) in sidebar grouping
Group-by Workflow and Workflow Step rendered raw UUID strings as group
headers because `TaskSwitcherItem` did not carry the resolved names.
Pass `workflowName` and `workflowStepTitle` through `toSidebarItem` and
prefer them in the group extractors.
* fix(web): drop redundant true/false selector on boolean sidebar filters
Boolean dimensions (PR review, Archived, Has diff) previously exposed
both an operator (is / is not) and a value selector (true / false),
which gives four user inputs for two real states. Hide the value input
for boolean clauses and always store `true`; negation is expressed via
the operator. Rename "Is PR review" to "PR review" since the dimension
label no longer needs to read as a question.
* refactor(web): drop Sort by Repository and relabel State to Status
Sorting by repository duplicates what Group by Repository already
offers, and "State" leaks a backend term into the picker. Remove the
repository sort key (comparator, type, picker option) and rename the
state option to "Status". Stored views referencing the removed key are
migrated back to `state` at load time so the popover does not crash.
* fix(web): tighten sidebar filter popover section spacing
The FILTERS, SORT, and GROUP BY section labels each sat above their
controls with both padded containers (p-2.5) and a 6px bottom margin,
leaving visible dead space above each header. Reduce container padding
to p-2 and label margin to mb-1 so sections read as a compact stack.
* chore(web): apply prettier formatting drift in sidebar-filter area
* revert(web): undo store.ts prettier reformat to stay under max-lines cap
The packed single-line UIA declaration in store.ts is load-bearing for
the 600-line ESLint cap: the previous chore commit unpacked it to 9
lines and pushed the file to 609 lines, turning the max-lines warning
into a lint failure. Restore the packed layout (the /* prettier-ignore */
comment is there for exactly this reason).
* refactor(web): label boolean filter ops as Show/Hide instead of is/is not
* fix(web): pull section labels flush to sidebar filter popover borders
* refactor(web): inline rename and save-as into sidebar view header row
* refactor(web): split ViewHeaderRow into mode, display, and action subcomponents
* feat(backend): persist sidebar views in user settings
Adds a SidebarViews field to UserSettings (stored in the existing
users.settings JSON blob) plus validation in the service layer:
views are capped at 50, ids and names must be non-empty and unique.
* feat(web): hydrate and sync sidebar views to backend
Moves the source of truth for saved sidebar views from localStorage
to the user settings endpoint. Views hydrate from SSR on first load;
create/rename/overwrite/delete/duplicate/toggle-collapsed all PATCH
the backend with optimistic updates and revert-on-failure. The
active view id and draft remain per-device in localStorage. A
sync bridge surfaces PATCH errors as toasts and runs a one-time
migration to upload any pre-existing local views.
As a side effect, localStorage writes and PATCH side effects are
moved out of immer producers to avoid proxy-serialization risk.
* chore(web): apply prettier to store.ts sidebar actions block
* fix(web): run migrateView on SSR-hydrated sidebar views
Defensively drop clauses with unknown dimensions and reset stale sort
keys when views come from the backend, matching the localStorage load
path. Also notes the default-state module and sidebar views in the
store structure docs.
* docs: note default-state module and sidebar views in store structure
* fix(web): type sidebar view storage wrappers properly
Drop the as-unknown-as-SidebarView and as-never casts at call sites by
making the local-storage getters/setters accept the domain type and do
the JsonValue cast once inside the wrapper.
* refactor(web): stop PATCHing on sidebar group collapse toggles
collapsedGroups is per-device visual state; routing it through
mutateViews made every expand/collapse click fire a user-settings
PATCH. Keep it local (in-memory + localStorage cache); the next real
view mutation picks up whatever state is current.
* fix(web): skip sidebar view migration when settings hydrated from server
After SSR hydration the in-memory views are already the backend's
truth, so migrating re-POSTs the same data every page load. Gate the
one-shot migration on userSettings.loaded — only run if the server
didn't answer and the slice fell back to localStorage.
613 lines
22 KiB
TypeScript
613 lines
22 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useState, memo } from "react";
|
|
import type { TaskState, TaskSession, TaskSessionState, Repository } from "@/lib/types/http";
|
|
import type { TaskPR } from "@/lib/types/github";
|
|
import type { KanbanState } from "@/lib/state/slices";
|
|
import type { GitStatusEntry } from "@/lib/state/slices/session-runtime/types";
|
|
import { TaskSwitcher } from "./task-switcher";
|
|
import { applyView } from "@/lib/sidebar/apply-view";
|
|
import { SidebarFilterBar } from "./sidebar-filter/sidebar-filter-bar";
|
|
import { MOCK_ITEMS, MOCK_SIDEBAR } from "./sidebar-mock-data";
|
|
import { TaskRenameDialog } from "./task-rename-dialog";
|
|
import { TaskArchiveConfirmDialog } from "./task-archive-confirm-dialog";
|
|
import { PanelRoot, PanelBody } from "./panel-primitives";
|
|
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
|
import { replaceTaskUrl } from "@/lib/links";
|
|
import { useAllWorkflowSnapshots } from "@/hooks/domains/kanban/use-all-workflow-snapshots";
|
|
import { useTaskActions, useArchiveAndSwitchTask } from "@/hooks/use-task-actions";
|
|
import { useTaskRemoval } from "@/hooks/use-task-removal";
|
|
import { performLayoutSwitch, useDockviewStore } from "@/lib/state/dockview-store";
|
|
import { INTENT_PR_REVIEW } from "@/lib/state/layout-manager";
|
|
import { launchSession } from "@/lib/services/session-launch-service";
|
|
import { buildPrepareRequest } from "@/lib/services/session-launch-helpers";
|
|
import { getSessionInfoForTask } from "@/lib/utils/session-info";
|
|
import { getWebSocketClient } from "@/lib/ws/connection";
|
|
import { useArchivedTaskState } from "./task-archived-context";
|
|
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
|
import { useWorkspacePRs } from "@/hooks/domains/github/use-task-pr";
|
|
|
|
/** Find a task across all workflow snapshots */
|
|
function findTaskInSnapshots(
|
|
snapshots: Record<string, { tasks: KanbanState["tasks"] }>,
|
|
taskId: string,
|
|
): KanbanState["tasks"][number] | undefined {
|
|
for (const snapshot of Object.values(snapshots)) {
|
|
const task = snapshot.tasks.find((t: KanbanState["tasks"][number]) => t.id === taskId);
|
|
if (task) return task;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/** Look up git status directly via primarySessionId, bypassing the session list. */
|
|
function getGitStatusForTask(
|
|
task: { primarySessionId?: string | null },
|
|
envIdBySessionId: Record<string, string>,
|
|
gitStatusByEnvId: Record<string, GitStatusEntry>,
|
|
): GitStatusEntry | undefined {
|
|
if (!task.primarySessionId) return undefined;
|
|
const envKey = envIdBySessionId[task.primarySessionId] ?? task.primarySessionId;
|
|
return gitStatusByEnvId[envKey];
|
|
}
|
|
|
|
/** Resolve diff stats for a task, falling back to direct git status when sessions aren't loaded. */
|
|
function resolveDiffStats(
|
|
sessionDiffStats: { additions: number; deletions: number } | undefined,
|
|
task: { primarySessionId?: string | null },
|
|
envIdBySessionId: Record<string, string>,
|
|
gitStatusByEnvId: Record<string, GitStatusEntry>,
|
|
): { additions: number; deletions: number } | undefined {
|
|
if (sessionDiffStats) return sessionDiffStats;
|
|
if (!task.primarySessionId) return undefined;
|
|
const gs = getGitStatusForTask(task, envIdBySessionId, gitStatusByEnvId);
|
|
if (!gs) return undefined;
|
|
const a = gs.branch_additions ?? 0;
|
|
const d = gs.branch_deletions ?? 0;
|
|
return a > 0 || d > 0 ? { additions: a, deletions: d } : undefined;
|
|
}
|
|
|
|
/** Format PR info for display, capitalising the state. */
|
|
function toPrInfo(pr: TaskPR | undefined): { number: number; state: string } | undefined {
|
|
if (!pr?.state) return undefined;
|
|
return { number: pr.pr_number, state: pr.state[0].toUpperCase() + pr.state.slice(1) };
|
|
}
|
|
|
|
/** Map a kanban task to a sidebar item with session info and repository metadata. */
|
|
function toSidebarItem(
|
|
task: KanbanState["tasks"][number] & { _workflowId: string },
|
|
ctx: {
|
|
sessionsByTaskId: Record<string, TaskSession[]>;
|
|
gitStatusByEnvId: Record<string, GitStatusEntry>;
|
|
envIdBySessionId: Record<string, string>;
|
|
repositorySlugById: Map<string, string | undefined>;
|
|
taskPRsByTaskId: Record<string, TaskPR | undefined>;
|
|
titleById: Map<string, string>;
|
|
workflowNameById: Map<string, string>;
|
|
stepTitleById: Map<string, string>;
|
|
},
|
|
) {
|
|
const sessionInfo = getSessionInfoForTask(
|
|
task.id,
|
|
ctx.sessionsByTaskId,
|
|
ctx.gitStatusByEnvId,
|
|
ctx.envIdBySessionId,
|
|
);
|
|
const resolvedSessionState =
|
|
sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined);
|
|
const repoSlug = task.repositoryId ? ctx.repositorySlugById.get(task.repositoryId) : undefined;
|
|
const pr = ctx.taskPRsByTaskId[task.id];
|
|
|
|
const diffStats = resolveDiffStats(
|
|
sessionInfo.diffStats,
|
|
task,
|
|
ctx.envIdBySessionId,
|
|
ctx.gitStatusByEnvId,
|
|
);
|
|
|
|
return {
|
|
id: task.id,
|
|
title: task.title,
|
|
state: task.state as TaskState | undefined,
|
|
sessionState: resolvedSessionState,
|
|
description: task.description,
|
|
workflowId: task._workflowId,
|
|
workflowName: ctx.workflowNameById.get(task._workflowId),
|
|
workflowStepId: task.workflowStepId as string | undefined,
|
|
workflowStepTitle: task.workflowStepId
|
|
? ctx.stepTitleById.get(task.workflowStepId as string)
|
|
: undefined,
|
|
repositoryPath: pr ? `${pr.owner}/${pr.repo}` : repoSlug,
|
|
diffStats,
|
|
isRemoteExecutor: task.isRemoteExecutor,
|
|
remoteExecutorType: task.primaryExecutorType ?? undefined,
|
|
remoteExecutorName: task.primaryExecutorName ?? undefined,
|
|
primarySessionId: task.primarySessionId ?? null,
|
|
updatedAt: sessionInfo.updatedAt ?? task.updatedAt ?? task.createdAt,
|
|
createdAt: task.createdAt,
|
|
isArchived: false as boolean,
|
|
parentTaskTitle: task.parentTaskId ? ctx.titleById.get(task.parentTaskId) : undefined,
|
|
parentTaskId: task.parentTaskId ?? undefined,
|
|
prInfo: toPrInfo(pr),
|
|
isPRReview: task.isPRReview ?? false,
|
|
};
|
|
}
|
|
|
|
type TaskSessionSidebarProps = {
|
|
workspaceId: string | null;
|
|
workflowId: string | null;
|
|
};
|
|
|
|
type StepInfo = { id: string; title: string; color: string; position: number };
|
|
type SidebarItem = Omit<ReturnType<typeof toSidebarItem>, "workflowId"> & { workflowId?: string };
|
|
|
|
function buildArchivedItem(s: ReturnType<typeof useArchivedTaskState>): SidebarItem {
|
|
return {
|
|
id: s.archivedTaskId!,
|
|
title: s.archivedTaskTitle ?? "Archived task",
|
|
state: undefined,
|
|
sessionState: undefined,
|
|
description: undefined,
|
|
workflowId: undefined,
|
|
workflowName: undefined,
|
|
workflowStepId: undefined,
|
|
workflowStepTitle: undefined,
|
|
repositoryPath: s.archivedTaskRepositoryPath,
|
|
diffStats: undefined,
|
|
isRemoteExecutor: false,
|
|
remoteExecutorType: undefined,
|
|
remoteExecutorName: undefined,
|
|
primarySessionId: null,
|
|
updatedAt: s.archivedTaskUpdatedAt,
|
|
createdAt: undefined,
|
|
isArchived: true,
|
|
parentTaskTitle: undefined,
|
|
parentTaskId: undefined,
|
|
prInfo: undefined,
|
|
isPRReview: false,
|
|
};
|
|
}
|
|
|
|
function useSidebarData(workspaceId: string | null) {
|
|
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
|
|
const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
|
|
const sessionsById = useAppStore((state) => state.taskSessions.items);
|
|
const sessionsByTaskId = useAppStore((state) => state.taskSessionsByTask.itemsByTaskId);
|
|
const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId);
|
|
const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId);
|
|
const snapshots = useAppStore((state) => state.kanbanMulti.snapshots);
|
|
const isMultiLoading = useAppStore((state) => state.kanbanMulti.isLoading);
|
|
const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId);
|
|
const taskPRsByTaskId = useAppStore((state) => state.taskPRs.byTaskId);
|
|
const archivedState = useArchivedTaskState();
|
|
|
|
const selectedTaskId = useMemo(() => {
|
|
if (activeSessionId) return sessionsById[activeSessionId]?.task_id ?? activeTaskId;
|
|
return activeTaskId;
|
|
}, [activeSessionId, activeTaskId, sessionsById]);
|
|
|
|
const isLoadingWorkflow = isMultiLoading && Object.keys(snapshots).length === 0;
|
|
|
|
const { allTasks, allSteps, stepsByWorkflowId } = useMemo(() => {
|
|
const tasks: Array<KanbanState["tasks"][number] & { _workflowId: string }> = [];
|
|
const stepMap = new Map<string, StepInfo>();
|
|
const wfSteps: Record<string, StepInfo[]> = {};
|
|
for (const [wfId, snapshot] of Object.entries(snapshots)) {
|
|
for (const step of snapshot.steps) if (!stepMap.has(step.id)) stepMap.set(step.id, step);
|
|
wfSteps[wfId] = [...snapshot.steps].sort((a, b) => a.position - b.position);
|
|
tasks.push(...snapshot.tasks.map((t) => ({ ...t, _workflowId: wfId })));
|
|
}
|
|
const sortedSteps = [...stepMap.values()].sort((a, b) => a.position - b.position);
|
|
return { allTasks: tasks, allSteps: sortedSteps, stepsByWorkflowId: wfSteps };
|
|
}, [snapshots]);
|
|
|
|
const tasksWithRepositories = useMemo(() => {
|
|
const repositories = workspaceId ? (repositoriesByWorkspace[workspaceId] ?? []) : [];
|
|
const repositorySlugById = new Map(
|
|
repositories.map((repo: Repository) => [
|
|
repo.id,
|
|
repo.provider_owner && repo.provider_name
|
|
? `${repo.provider_owner}/${repo.provider_name}`
|
|
: repo.local_path,
|
|
]),
|
|
);
|
|
const titleById = new Map(allTasks.map((t) => [t.id, t.title]));
|
|
const workflowNameById = new Map(
|
|
Object.entries(snapshots).map(([wfId, snap]) => [wfId, snap.workflowName]),
|
|
);
|
|
const stepTitleById = new Map(allSteps.map((s) => [s.id, s.title]));
|
|
const mapCtx = {
|
|
sessionsByTaskId,
|
|
gitStatusByEnvId,
|
|
envIdBySessionId,
|
|
repositorySlugById,
|
|
taskPRsByTaskId: taskPRsByTaskId as Record<string, TaskPR | undefined>,
|
|
titleById,
|
|
workflowNameById,
|
|
stepTitleById,
|
|
};
|
|
const items: SidebarItem[] = allTasks.map((task) => toSidebarItem(task, mapCtx));
|
|
if (
|
|
archivedState.isArchived &&
|
|
archivedState.archivedTaskId &&
|
|
!items.some((t) => t.id === archivedState.archivedTaskId)
|
|
) {
|
|
items.unshift(buildArchivedItem(archivedState));
|
|
}
|
|
return items;
|
|
}, [
|
|
repositoriesByWorkspace,
|
|
allTasks,
|
|
allSteps,
|
|
snapshots,
|
|
workspaceId,
|
|
sessionsByTaskId,
|
|
gitStatusByEnvId,
|
|
envIdBySessionId,
|
|
taskPRsByTaskId,
|
|
archivedState,
|
|
]);
|
|
|
|
// Stable list of primary session IDs for the bulk-subscribe effect.
|
|
// Derived from kanban tasks (always available) rather than sessionsByTaskId (loaded on-demand).
|
|
const primarySessionIds = useMemo(
|
|
() => allTasks.map((t) => t.primarySessionId).filter((id): id is string => id != null),
|
|
[allTasks],
|
|
);
|
|
|
|
return {
|
|
activeTaskId,
|
|
selectedTaskId,
|
|
allSteps,
|
|
stepsByWorkflowId,
|
|
isLoadingWorkflow,
|
|
tasksWithRepositories,
|
|
primarySessionIds,
|
|
};
|
|
}
|
|
|
|
type StoreApi = ReturnType<typeof useAppStoreApi>;
|
|
type SwitchFn = (
|
|
taskId: string,
|
|
sessionId: string,
|
|
oldSessionId: string | null | undefined,
|
|
) => void;
|
|
|
|
function buildSwitchToSession(
|
|
setActiveSession: (taskId: string, sessionId: string) => void,
|
|
): SwitchFn {
|
|
return (taskId, sessionId, oldSessionId) => {
|
|
setActiveSession(taskId, sessionId);
|
|
performLayoutSwitch(oldSessionId ?? null, sessionId);
|
|
};
|
|
}
|
|
|
|
async function prepareAndSwitchTask(
|
|
taskId: string,
|
|
store: StoreApi,
|
|
switchToSession: SwitchFn,
|
|
setPreparingTaskId: (id: string | null) => void,
|
|
): Promise<boolean> {
|
|
setPreparingTaskId(taskId);
|
|
// Capture before the async launch — WS events may update activeSessionId
|
|
// by the time launchSession resolves, causing the layout switch to use the
|
|
// wrong "old" session and leave stale panels (e.g. plan panel) visible.
|
|
const oldSessionId = store.getState().tasks.activeSessionId;
|
|
try {
|
|
const { request } = buildPrepareRequest(taskId);
|
|
const resp = await launchSession(request);
|
|
if (resp.session_id) {
|
|
switchToSession(taskId, resp.session_id, oldSessionId);
|
|
// Apply PR review layout if the task has PR metadata
|
|
if (store.getState().taskPRs.byTaskId[taskId]) {
|
|
const { api, buildDefaultLayout } = useDockviewStore.getState();
|
|
if (api) buildDefaultLayout(api, INTENT_PR_REVIEW);
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
} catch {
|
|
return false;
|
|
} finally {
|
|
setPreparingTaskId(null);
|
|
}
|
|
}
|
|
|
|
function useMoveToStep(store: StoreApi) {
|
|
const { moveTaskById } = useTaskActions();
|
|
|
|
return useCallback(
|
|
async (taskId: string, workflowId: string, targetStepId: string) => {
|
|
const state = store.getState();
|
|
const snapshot = state.kanbanMulti.snapshots[workflowId];
|
|
if (!snapshot) return;
|
|
|
|
const originalTask = snapshot.tasks.find((t) => t.id === taskId);
|
|
if (!originalTask) return;
|
|
|
|
const targetTasks = snapshot.tasks
|
|
.filter((t) => t.workflowStepId === targetStepId && t.id !== taskId)
|
|
.sort((a, b) => a.position - b.position);
|
|
const nextPosition = targetTasks.length;
|
|
|
|
// Optimistic update
|
|
state.setWorkflowSnapshot(workflowId, {
|
|
...snapshot,
|
|
tasks: snapshot.tasks.map((t) =>
|
|
t.id === taskId ? { ...t, workflowStepId: targetStepId, position: nextPosition } : t,
|
|
),
|
|
});
|
|
|
|
try {
|
|
await moveTaskById(taskId, {
|
|
workflow_id: workflowId,
|
|
workflow_step_id: targetStepId,
|
|
position: nextPosition,
|
|
});
|
|
} catch (error) {
|
|
// Rollback only the moved task, and only if it still has the optimistic values
|
|
const cur = store.getState().kanbanMulti.snapshots[workflowId];
|
|
const curTask = cur?.tasks.find((t) => t.id === taskId);
|
|
if (cur && curTask?.workflowStepId === targetStepId && curTask.position === nextPosition) {
|
|
store.getState().setWorkflowSnapshot(workflowId, {
|
|
...cur,
|
|
tasks: cur.tasks.map((t) =>
|
|
t.id === taskId
|
|
? {
|
|
...t,
|
|
workflowStepId: originalTask.workflowStepId,
|
|
position: originalTask.position,
|
|
}
|
|
: t,
|
|
),
|
|
});
|
|
}
|
|
console.error("Failed to move task:", error);
|
|
}
|
|
},
|
|
[store, moveTaskById],
|
|
);
|
|
}
|
|
|
|
function useArchiveActions(store: StoreApi) {
|
|
const archiveAndSwitch = useArchiveAndSwitchTask({ useLayoutSwitch: true });
|
|
const [archivingTask, setArchivingTask] = useState<{ id: string; title: string } | null>(null);
|
|
const [isArchiving, setIsArchiving] = useState(false);
|
|
|
|
const handleArchiveTask = useCallback(
|
|
(taskId: string) => {
|
|
const task = findTaskInSnapshots(store.getState().kanbanMulti.snapshots, taskId);
|
|
setArchivingTask({ id: taskId, title: task?.title ?? "this task" });
|
|
},
|
|
[store],
|
|
);
|
|
|
|
const handleArchiveConfirm = useCallback(async () => {
|
|
if (!archivingTask) return;
|
|
setIsArchiving(true);
|
|
try {
|
|
await archiveAndSwitch(archivingTask.id);
|
|
} catch (error) {
|
|
console.error("Failed to archive task:", error);
|
|
} finally {
|
|
setIsArchiving(false);
|
|
setArchivingTask(null);
|
|
}
|
|
}, [archivingTask, archiveAndSwitch]);
|
|
|
|
return { archivingTask, setArchivingTask, isArchiving, handleArchiveTask, handleArchiveConfirm };
|
|
}
|
|
|
|
function useSidebarActions(store: StoreApi) {
|
|
const setActiveTask = useAppStore((state) => state.setActiveTask);
|
|
const setActiveSession = useAppStore((state) => state.setActiveSession);
|
|
const [deletingTaskId, setDeletingTaskId] = useState<string | null>(null);
|
|
const [preparingTaskId, setPreparingTaskId] = useState<string | null>(null);
|
|
const { deleteTaskById, renameTaskById } = useTaskActions();
|
|
const { removeTaskFromBoard, loadTaskSessionsForTask } = useTaskRemoval({
|
|
store,
|
|
useLayoutSwitch: true,
|
|
});
|
|
|
|
const switchToSession = useMemo(() => buildSwitchToSession(setActiveSession), [setActiveSession]);
|
|
|
|
const handleSelectTask = useCallback(
|
|
(taskId: string) => {
|
|
const oldSessionId = store.getState().tasks.activeSessionId;
|
|
const task = findTaskInSnapshots(store.getState().kanbanMulti.snapshots, taskId);
|
|
if (task?.primarySessionId) {
|
|
switchToSession(taskId, task.primarySessionId, oldSessionId);
|
|
loadTaskSessionsForTask(taskId);
|
|
replaceTaskUrl(taskId);
|
|
return;
|
|
}
|
|
loadTaskSessionsForTask(taskId).then(async (sessions) => {
|
|
const currentOldSessionId = store.getState().tasks.activeSessionId;
|
|
const primary = sessions.find((s: { is_primary?: boolean }) => s.is_primary);
|
|
const sessionId = primary?.id ?? sessions[0]?.id ?? null;
|
|
if (sessionId) {
|
|
switchToSession(taskId, sessionId, currentOldSessionId);
|
|
replaceTaskUrl(taskId);
|
|
return;
|
|
}
|
|
// No session — prepare workspace and switch to it
|
|
const switched = await prepareAndSwitchTask(
|
|
taskId,
|
|
store,
|
|
switchToSession,
|
|
setPreparingTaskId,
|
|
);
|
|
if (!switched) setActiveTask(taskId);
|
|
replaceTaskUrl(taskId);
|
|
});
|
|
},
|
|
[loadTaskSessionsForTask, switchToSession, setActiveTask, store],
|
|
);
|
|
|
|
const archiveActions = useArchiveActions(store);
|
|
|
|
const handleDeleteTask = useCallback(
|
|
async (taskId: string) => {
|
|
setDeletingTaskId(taskId);
|
|
const { activeTaskId: wasActiveTaskId, activeSessionId: wasActiveSessionId } =
|
|
store.getState().tasks;
|
|
try {
|
|
await deleteTaskById(taskId);
|
|
await removeTaskFromBoard(taskId, { wasActiveTaskId, wasActiveSessionId });
|
|
} finally {
|
|
setDeletingTaskId(null);
|
|
}
|
|
},
|
|
[deleteTaskById, removeTaskFromBoard, store],
|
|
);
|
|
|
|
const [renamingTask, setRenamingTask] = useState<{ id: string; title: string } | null>(null);
|
|
|
|
const handleRenameTask = useCallback((taskId: string, currentTitle: string) => {
|
|
setRenamingTask({ id: taskId, title: currentTitle });
|
|
}, []);
|
|
|
|
const handleRenameSubmit = useCallback(
|
|
async (newTitle: string) => {
|
|
if (!renamingTask) return;
|
|
try {
|
|
await renameTaskById(renamingTask.id, newTitle);
|
|
} catch (error) {
|
|
console.error("Failed to rename task:", error);
|
|
}
|
|
setRenamingTask(null);
|
|
},
|
|
[renamingTask, renameTaskById],
|
|
);
|
|
|
|
const handleMoveToStep = useMoveToStep(store);
|
|
|
|
return {
|
|
deletingTaskId,
|
|
preparingTaskId,
|
|
handleSelectTask,
|
|
handleDeleteTask,
|
|
handleMoveToStep,
|
|
renamingTask,
|
|
setRenamingTask,
|
|
handleRenameTask,
|
|
handleRenameSubmit,
|
|
...archiveActions,
|
|
};
|
|
}
|
|
|
|
function useBulkGitStatusSubscription(primarySessionIds: string[]) {
|
|
const connectionStatus = useAppStore((state) => state.connection.status);
|
|
useEffect(() => {
|
|
if (connectionStatus !== "connected" || primarySessionIds.length === 0) return;
|
|
const client = getWebSocketClient();
|
|
if (!client) return;
|
|
const unsubscribes = primarySessionIds.map((id) => client.subscribeSession(id));
|
|
return () => unsubscribes.forEach((u) => u());
|
|
}, [primarySessionIds, connectionStatus]);
|
|
}
|
|
|
|
function useEffectiveSidebarView() {
|
|
const sidebarSlice = useAppStore((state) => state.sidebarViews);
|
|
return useMemo(() => {
|
|
const active = sidebarSlice.views.find((v) => v.id === sidebarSlice.activeViewId);
|
|
if (!active) return sidebarSlice.views[0];
|
|
const d = sidebarSlice.draft;
|
|
if (!d || d.baseViewId !== active.id) return active;
|
|
return { ...active, filters: d.filters, sort: d.sort, group: d.group };
|
|
}, [sidebarSlice.views, sidebarSlice.activeViewId, sidebarSlice.draft]);
|
|
}
|
|
|
|
export const TaskSessionSidebar = memo(function TaskSessionSidebar({
|
|
workspaceId,
|
|
}: TaskSessionSidebarProps) {
|
|
const store = useAppStoreApi();
|
|
useAllWorkflowSnapshots(workspaceId);
|
|
useRepositories(workspaceId);
|
|
useWorkspacePRs(workspaceId);
|
|
|
|
const {
|
|
activeTaskId,
|
|
selectedTaskId,
|
|
stepsByWorkflowId,
|
|
isLoadingWorkflow,
|
|
tasksWithRepositories,
|
|
primarySessionIds,
|
|
} = useSidebarData(workspaceId);
|
|
|
|
useBulkGitStatusSubscription(primarySessionIds);
|
|
|
|
const {
|
|
deletingTaskId,
|
|
preparingTaskId,
|
|
handleSelectTask,
|
|
handleArchiveTask,
|
|
handleDeleteTask,
|
|
handleMoveToStep,
|
|
renamingTask,
|
|
setRenamingTask,
|
|
handleRenameTask,
|
|
handleRenameSubmit,
|
|
archivingTask,
|
|
setArchivingTask,
|
|
isArchiving,
|
|
handleArchiveConfirm,
|
|
} = useSidebarActions(store);
|
|
|
|
const displayTasks = useMemo(() => {
|
|
if (MOCK_SIDEBAR) return MOCK_ITEMS;
|
|
return preparingTaskId
|
|
? tasksWithRepositories.map((t) =>
|
|
t.id === preparingTaskId ? { ...t, sessionState: "STARTING" as TaskSessionState } : t,
|
|
)
|
|
: tasksWithRepositories;
|
|
}, [tasksWithRepositories, preparingTaskId]);
|
|
|
|
const toggleSidebarGroupCollapsed = useAppStore((state) => state.toggleSidebarGroupCollapsed);
|
|
const effectiveView = useEffectiveSidebarView();
|
|
const grouped = useMemo(
|
|
() => applyView(displayTasks, effectiveView),
|
|
[displayTasks, effectiveView],
|
|
);
|
|
|
|
return (
|
|
<PanelRoot data-testid="task-sidebar">
|
|
<SidebarFilterBar />
|
|
<PanelBody className="space-y-4 p-0">
|
|
<TaskSwitcher
|
|
grouped={grouped}
|
|
stepsByWorkflowId={stepsByWorkflowId}
|
|
activeTaskId={activeTaskId}
|
|
selectedTaskId={selectedTaskId}
|
|
collapsedGroupKeys={effectiveView.collapsedGroups}
|
|
onToggleGroup={(groupKey) => toggleSidebarGroupCollapsed(effectiveView.id, groupKey)}
|
|
onSelectTask={handleSelectTask}
|
|
onRenameTask={handleRenameTask}
|
|
onArchiveTask={handleArchiveTask}
|
|
onDeleteTask={handleDeleteTask}
|
|
onMoveToStep={handleMoveToStep}
|
|
deletingTaskId={deletingTaskId}
|
|
isLoading={isLoadingWorkflow}
|
|
totalTaskCount={displayTasks.length}
|
|
/>
|
|
</PanelBody>
|
|
<TaskRenameDialog
|
|
open={renamingTask !== null}
|
|
onOpenChange={(open) => {
|
|
if (!open) setRenamingTask(null);
|
|
}}
|
|
currentTitle={renamingTask?.title ?? ""}
|
|
onSubmit={handleRenameSubmit}
|
|
/>
|
|
<TaskArchiveConfirmDialog
|
|
open={archivingTask !== null}
|
|
onOpenChange={(open) => {
|
|
if (!open) setArchivingTask(null);
|
|
}}
|
|
taskTitle={archivingTask?.title ?? ""}
|
|
isArchiving={isArchiving}
|
|
onConfirm={handleArchiveConfirm}
|
|
/>
|
|
</PanelRoot>
|
|
);
|
|
});
|