feat(ui): configure sidebar task-row presentation (#2955)

This commit is contained in:
Carlos Florêncio
2026-08-24 23:33:49 +00:00
committed by GitHub
parent 29289520c7
commit 6c76ed84c2
67 changed files with 3686 additions and 467 deletions
@@ -741,6 +741,7 @@ func mapSidebarViews(views []usermodels.SidebarView) []map[string]any {
"sort": view.Sort,
"group": view.Group,
"collapsedGroups": stringSlice(view.CollapsedGroups),
"taskRow": mapSidebarTaskRow(view.TaskRow),
})
}
return result
@@ -756,6 +757,19 @@ func mapSidebarDraft(draft *usermodels.SidebarViewDraft) map[string]any {
"filters": draft.Filters,
"sort": draft.Sort,
"group": draft.Group,
"taskRow": mapSidebarTaskRow(draft.TaskRow),
}
}
func mapSidebarTaskRow(value *usermodels.SidebarTaskRowPresentation) map[string]any {
if value == nil {
return nil
}
return map[string]any{
"detailsEnabled": value.DetailsEnabled,
"detailOrder": stringSlice(value.DetailOrder),
"visibleDetails": stringSlice(value.VisibleDetails),
"trailing": value.Trailing,
}
}
@@ -95,11 +95,23 @@ func TestMapUserSettingsStateIncludesPortableTaskAndSidebarSettings(t *testing.T
SidebarViews: []usermodels.SidebarView{{
ID: "view-1",
Name: "My view",
TaskRow: &usermodels.SidebarTaskRowPresentation{
DetailsEnabled: true,
DetailOrder: []string{"repository", "relative_time"},
VisibleDetails: []string{"repository"},
Trailing: "relative_time",
},
}},
SidebarActiveViewID: "view-1",
SidebarDraft: &usermodels.SidebarViewDraft{
BaseViewID: "view-1",
Group: "repository",
TaskRow: &usermodels.SidebarTaskRowPresentation{
DetailsEnabled: false,
DetailOrder: []string{"relative_time", "repository", "pull_request_number"},
VisibleDetails: []string{},
Trailing: "none",
},
},
SidebarTaskPrefs: usermodels.SidebarTaskPrefs{
PinnedTaskIDs: []string{"task-1"},
@@ -123,6 +135,18 @@ func TestMapUserSettingsStateIncludesPortableTaskAndSidebarSettings(t *testing.T
if !ok || draft["baseViewId"] != "view-1" || draft["group"] != "repository" {
t.Fatalf("sidebarDraft = %#v, want mapped draft", state["sidebarDraft"])
}
view, ok := state["sidebarViews"].([]map[string]any)
if !ok || len(view) != 1 {
t.Fatalf("sidebarViews = %#v, want one mapped view", state["sidebarViews"])
}
viewTaskRow, ok := view[0]["taskRow"].(map[string]any)
if !ok || viewTaskRow["trailing"] != "relative_time" {
t.Fatalf("sidebarViews taskRow = %#v, want relative_time trailing", view[0]["taskRow"])
}
draftTaskRow, ok := draft["taskRow"].(map[string]any)
if !ok || draftTaskRow["detailsEnabled"] != false || draftTaskRow["trailing"] != "none" {
t.Fatalf("sidebarDraft taskRow = %#v, want disabled none presentation", draft["taskRow"])
}
prefs, ok := state["sidebarTaskPrefs"].(map[string]any)
if !ok || len(prefs["pinnedTaskIds"].([]string)) != 1 {
t.Fatalf("sidebarTaskPrefs = %#v, want mapped preferences", state["sidebarTaskPrefs"])
+32 -10
View File
@@ -171,12 +171,13 @@ type SavedLayout struct {
// The payload is stored and returned as-is; the server does not interpret
// clause values beyond passing them through.
type SidebarView struct {
ID string `json:"id"`
Name string `json:"name"`
Filters []SidebarViewClause `json:"filters"`
Sort SidebarViewSort `json:"sort"`
Group string `json:"group"`
CollapsedGroups []string `json:"collapsed_groups"`
ID string `json:"id"`
Name string `json:"name"`
Filters []SidebarViewClause `json:"filters"`
Sort SidebarViewSort `json:"sort"`
Group string `json:"group"`
CollapsedGroups []string `json:"collapsed_groups"`
TaskRow *SidebarTaskRowPresentation `json:"task_row,omitempty"`
}
type SidebarViewClause struct {
@@ -192,10 +193,31 @@ type SidebarViewSort struct {
}
type SidebarViewDraft struct {
BaseViewID string `json:"base_view_id"`
Filters []SidebarViewClause `json:"filters"`
Sort SidebarViewSort `json:"sort"`
Group string `json:"group"`
BaseViewID string `json:"base_view_id"`
Filters []SidebarViewClause `json:"filters"`
Sort SidebarViewSort `json:"sort"`
Group string `json:"group"`
TaskRow *SidebarTaskRowPresentation `json:"task_row,omitempty"`
}
// SidebarTaskRowPresentation controls the optional metadata and trailing
// presentation for a task row in a saved sidebar view.
type SidebarTaskRowPresentation struct {
DetailsEnabled bool `json:"details_enabled"`
DetailOrder []string `json:"detail_order"`
VisibleDetails []string `json:"visible_details"`
Trailing string `json:"trailing"`
}
// DefaultSidebarTaskRowPresentation returns the presentation used by the
// original sidebar layout.
func DefaultSidebarTaskRowPresentation() *SidebarTaskRowPresentation {
return &SidebarTaskRowPresentation{
DetailsEnabled: true,
DetailOrder: []string{"relative_time", "repository", "pull_request_number"},
VisibleDetails: []string{"relative_time", "repository", "pull_request_number"},
Trailing: "git_changes",
}
}
type SidebarTaskPrefs struct {
@@ -712,6 +712,7 @@ func DefaultSidebarViews() []models.SidebarView {
Sort: models.SidebarViewSort{Key: "state", Direction: "asc"},
Group: "repository",
CollapsedGroups: []string{},
TaskRow: models.DefaultSidebarTaskRowPresentation(),
}}
}
@@ -167,6 +167,7 @@ func TestScanUserSettingsSidebarDefaults(t *testing.T) {
Sort: models.SidebarViewSort{Key: "state", Direction: "asc"},
Group: "repository",
CollapsedGroups: []string{},
TaskRow: models.DefaultSidebarTaskRowPresentation(),
}
tests := []struct {
@@ -1273,6 +1274,20 @@ func TestSQLiteRepositorySidebarViewStateRoundTrip(t *testing.T) {
t.Fatalf("get defaults: %v", err)
}
settings.SidebarActiveViewID = "view-1"
settings.SidebarViews = []models.SidebarView{{
ID: "view-1",
Name: "Custom",
Filters: []models.SidebarViewClause{},
Sort: models.SidebarViewSort{Key: "updatedAt", Direction: "desc"},
Group: "workflow",
CollapsedGroups: []string{},
TaskRow: &models.SidebarTaskRowPresentation{
DetailsEnabled: false,
DetailOrder: []string{"repository", "relative_time", "pull_request_number"},
VisibleDetails: []string{"repository"},
Trailing: "none",
},
}}
settings.SidebarTaskPrefs = models.SidebarTaskPrefs{
PinnedTaskIDs: []string{"task-1"},
OrderedTaskIDs: []string{"task-2", "task-1"},
@@ -1305,6 +1320,9 @@ func TestSQLiteRepositorySidebarViewStateRoundTrip(t *testing.T) {
if got.SidebarActiveViewID != "view-1" {
t.Fatalf("expected active view to round-trip, got %q", got.SidebarActiveViewID)
}
if got.SidebarViews[0].TaskRow == nil || got.SidebarViews[0].TaskRow.Trailing != "none" {
t.Fatalf("expected sidebar view task row to round-trip, got %+v", got.SidebarViews)
}
if got.SidebarDraft == nil || got.SidebarDraft.Group != "workflow" {
t.Fatalf("expected sidebar draft to round-trip, got %+v", got.SidebarDraft)
}
+7 -4
View File
@@ -2,9 +2,10 @@ import * as React from "react";
import { cn } from "./lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => (
<input
ref={ref}
type={type}
data-slot="input"
className={cn(
@@ -13,7 +14,9 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
)}
{...props}
/>
);
}
),
);
Input.displayName = "Input";
export { Input };
@@ -0,0 +1,51 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { ChangeRequestTaskStatusSummary } from "./change-request-task-status-summary";
describe("ChangeRequestTaskStatusSummary layout", () => {
it("aligns labels, status icons, and values on one shared grid", () => {
render(
<ChangeRequestTaskStatusSummary
summaries={[
{
number: 42,
title: "Align review details",
rows: [
{ kind: "review", status: "approved", tone: "success" },
{
kind: "ci",
status: "passed",
tone: "success",
detail: { key: "github:checksPassed", values: { count: 3 } },
},
{ kind: "merge", status: "mergeable", tone: "success" },
],
},
]}
/>,
);
const rows = screen.getByTestId("pr-task-status-rows");
expect(rows.className).toContain("grid-cols-[minmax(0,max-content)_auto_minmax(0,1fr)]");
expect(screen.getByTestId("pr-task-status-review-value")).toBeTruthy();
expect(screen.getByTestId("pr-task-status-ci-detail")).toBeTruthy();
});
it("keeps translated labels shrinkable when the value column is narrow", () => {
render(
<ChangeRequestTaskStatusSummary
summaries={[
{
number: 7,
title: "Narrow summary",
rows: [{ kind: "review", status: "approved", tone: "success" }],
},
]}
/>,
);
const label = screen.getAllByText("Review").at(-1)!;
expect(label.className).toContain("min-w-0");
expect(label.className).toContain("[overflow-wrap:anywhere]");
});
});
@@ -185,16 +185,17 @@ function SummaryRow({
}) {
const { t } = useTranslation();
return (
<div
data-testid={`${presentation.rowTestIdPrefix}-${row.kind}`}
className="grid grid-cols-[min-content_minmax(0,1fr)] items-start gap-x-3"
>
<span className="text-muted-foreground">{t(presentation.rowLabelKeys[row.kind])}</span>
<div className="min-w-0">
<div data-testid={`${presentation.rowTestIdPrefix}-${row.kind}`} className="contents">
<span className="min-w-0 text-muted-foreground [overflow-wrap:anywhere]">
{t(presentation.rowLabelKeys[row.kind])}
</span>
<span className={cn("flex items-center", TONE_CLASSES[row.tone])}>
<SummaryStatusIcon status={row.status} />
</span>
<div data-testid={`${presentation.rowTestIdPrefix}-${row.kind}-value`} className="min-w-0">
<span
className={cn("flex min-w-0 items-center gap-1.5 font-medium", TONE_CLASSES[row.tone])}
>
<SummaryStatusIcon status={row.status} />
<span className="min-w-0 break-words">{getStatusText(row, presentation, t)}</span>
</span>
{row.detail && (
@@ -255,7 +256,10 @@ export function ChangeRequestTaskStatusSummary({
</div>
</div>
{summary.rows.length > 0 && (
<div className="mt-2.5 space-y-1.5 pl-6">
<div
data-testid={`${presentation.rowTestIdPrefix}-rows`}
className="mt-2.5 grid grid-cols-[minmax(0,max-content)_auto_minmax(0,1fr)] items-start gap-x-3 gap-y-1.5 pl-6"
>
{summary.rows.map((row) => (
<SummaryRow key={row.kind} row={row} presentation={presentation} />
))}
@@ -15,6 +15,7 @@ export function buildMobileTaskSwitcherProps(
onReorderSubtasks: (parentTaskId: string, orderedSubtaskIds: string[]) => void;
pinnedTaskIds: string[];
showActivityTime: boolean;
taskRowPresentation: TaskSwitcherProps["taskRowPresentation"];
},
): TaskSwitcherProps {
return {
@@ -25,6 +26,7 @@ export function buildMobileTaskSwitcherProps(
selectedTaskId: props.selectedTaskId,
collapsedGroupKeys: helpers.collapsedGroupKeys,
showActivityTime: helpers.showActivityTime,
taskRowPresentation: helpers.taskRowPresentation,
onToggleGroup: helpers.onToggleGroup,
collapsedSubtaskParentIds: helpers.collapsedSubtaskParentIds,
onToggleSubtasks: helpers.onToggleSubtasks,
@@ -146,6 +146,7 @@ export function MobileTaskList(props: MobileTaskListProps) {
onReorderSubtasks: handleReorderSubtasks,
pinnedTaskIds,
showActivityTime: view.sort.key === "lastActivityAt",
taskRowPresentation: view.taskRow,
});
return <TaskSwitcher {...switcherProps} />;
}
@@ -7,13 +7,37 @@ import { useTranslation } from "react-i18next";
// `labelKey` holds a catalog key, not copy: this table is module scope, so a
// resolved `t()` here would freeze at the boot locale. `key` is a persisted
// grouping value and stays in English.
const GROUP_OPTIONS: Array<{ key: GroupKey; labelKey: string }> = [
{ key: "none", labelKey: "task:groupNone" },
{ key: "repository", labelKey: "task:groupRepository" },
{ key: "workflow", labelKey: "task:groupWorkflow" },
{ key: "workflowStep", labelKey: "task:groupWorkflowStep" },
{ key: "executorType", labelKey: "task:groupExecutorType" },
{ key: "state", labelKey: "task:groupState" },
const GROUP_OPTIONS: Array<{ key: GroupKey; labelKey: string; descriptionKey: string }> = [
{
key: "none",
labelKey: "task:groupNone",
descriptionKey: "task:groupNoneDescription",
},
{
key: "repository",
labelKey: "task:groupRepository",
descriptionKey: "task:groupRepositoryDescription",
},
{
key: "workflow",
labelKey: "task:groupWorkflow",
descriptionKey: "task:groupWorkflowDescription",
},
{
key: "workflowStep",
labelKey: "task:groupWorkflowStep",
descriptionKey: "task:groupWorkflowStepDescription",
},
{
key: "executorType",
labelKey: "task:groupExecutorType",
descriptionKey: "task:groupExecutorTypeDescription",
},
{
key: "state",
labelKey: "task:groupState",
descriptionKey: "task:groupStateDescription",
},
];
type Props = {
@@ -29,11 +53,20 @@ export function GroupPicker({ value, onChange }: Props) {
<SelectValue />
</SelectTrigger>
<SelectContent>
{GROUP_OPTIONS.map((opt) => (
<SelectItem key={opt.key} value={opt.key} className="text-xs">
{t(opt.labelKey)}
</SelectItem>
))}
{GROUP_OPTIONS.map((opt) => {
const label = t(opt.labelKey);
return (
<SelectItem
key={opt.key}
value={opt.key}
className="text-xs"
aria-label={label}
description={t(opt.descriptionKey)}
>
{label}
</SelectItem>
);
})}
</SelectContent>
</Select>
);
@@ -0,0 +1,106 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { SidebarView } from "@/lib/state/slices/ui/sidebar-view-types";
import { SidebarFilterPopover } from "./sidebar-filter-popover";
const VIEW: SidebarView = {
id: "view-all",
name: "All tasks",
filters: [],
sort: { key: "state", direction: "asc" },
group: "repository",
collapsedGroups: [],
taskRow: {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
},
};
const state = {
sidebarViews: {
views: [VIEW],
activeViewId: VIEW.id,
draft: null,
},
updateSidebarDraft: vi.fn(),
saveSidebarDraftAs: vi.fn(),
saveSidebarDraftOverwrite: vi.fn(),
discardSidebarDraft: vi.fn(),
deleteSidebarView: vi.fn(),
renameSidebarView: vi.fn(),
};
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (value: typeof state) => unknown) => selector(state),
}));
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe("SidebarFilterPopover task-row editor", () => {
it("keeps the editor collapsed until the user opens it", () => {
render(
<SidebarFilterPopover
trigger={<button type="button">Open</button>}
open
onOpenChange={vi.fn()}
/>,
);
expect(screen.getByTestId("task-row-settings-toggle")).toBeTruthy();
expect(screen.queryByTestId("task-row-details-toggle")).toBeNull();
fireEvent.click(screen.getByTestId("task-row-settings-toggle"));
expect(screen.getByTestId("task-row-details-toggle")).toBeTruthy();
expect(state.updateSidebarDraft).not.toHaveBeenCalled();
});
it("describes every group-by and right-side option", () => {
const renderEditor = () =>
render(
<SidebarFilterPopover
trigger={<button type="button">Open</button>}
open
onOpenChange={vi.fn()}
/>,
);
renderEditor();
fireEvent.click(screen.getByTestId("group-key-select"));
for (const { label, description } of [
{ label: "None", description: "Keep all tasks in one list." },
{ label: "Repository", description: "Separate tasks by repository." },
{ label: "Workflow", description: "Separate tasks by workflow." },
{ label: "Workflow step", description: "Separate tasks by workflow step." },
{ label: "Executor type", description: "Separate tasks by executor type." },
{ label: "State", description: "Separate tasks by state." },
]) {
const option = screen.getByRole("option", { name: label });
const descriptionId = option.getAttribute("aria-describedby");
expect(descriptionId).toBeTruthy();
expect(screen.getByText(description, { exact: true })).toBeTruthy();
}
cleanup();
renderEditor();
fireEvent.click(screen.getByTestId("task-row-settings-toggle"));
fireEvent.click(screen.getByTestId("task-row-trailing-select"));
for (const { label, description } of [
{ label: "Git changes", description: "Show added and removed lines." },
{ label: "Relative time", description: "Show when the task was last updated." },
{
label: "Change request status",
description: "Show the pull request or merge request status.",
},
{ label: "Nothing", description: "Leave the right side empty." },
]) {
const option = screen.getByRole("option", { name: label });
const descriptionId = option.getAttribute("aria-describedby");
expect(descriptionId).toBeTruthy();
expect(screen.getByText(description, { exact: true })).toBeTruthy();
}
});
});
@@ -1,21 +1,16 @@
"use client";
import { useMemo } from "react";
import { IconPlus } from "@tabler/icons-react";
import type { ComponentProps } from "react";
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerTrigger } from "@kandev/ui/drawer";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { Button } from "@kandev/ui/button";
import { useAppStore } from "@/components/state-provider";
import type {
FilterClause,
GroupKey,
SidebarView,
SidebarViewDraft,
SortSpec,
} from "@/lib/state/slices/ui/sidebar-view-types";
import { DIMENSION_METAS } from "./filter-dimension-registry";
import { FilterClauseEditor } from "./filter-clause-editor";
import { SortPicker } from "./sort-picker";
import { GroupPicker } from "./group-picker";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import type { FilterClause, SidebarView } from "@/lib/state/slices/ui/sidebar-view-types";
import {
SidebarViewEditor,
createSidebarFilterClause,
createSidebarViewEditorCurrent,
} from "./sidebar-view-editor";
import { ViewHeaderRow } from "./view-manager";
import { useTranslation } from "react-i18next";
@@ -27,25 +22,6 @@ type Props = {
onRenameRequestHandled?: (viewId: string) => void;
};
function makeClauseId(): string {
return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
}
type Current = { filters: FilterClause[]; sort: SortSpec; group: GroupKey };
function resolveCurrent(
activeView: SidebarView | undefined,
storedDraft: SidebarViewDraft | null,
): Current {
if (storedDraft && activeView && storedDraft.baseViewId === activeView.id) {
return { filters: storedDraft.filters, sort: storedDraft.sort, group: storedDraft.group };
}
if (!activeView) {
return { filters: [], sort: { key: "state", direction: "asc" }, group: "none" };
}
return { filters: activeView.filters, sort: activeView.sort, group: activeView.group };
}
export function SidebarFilterPopover({
trigger,
open,
@@ -63,126 +39,75 @@ export function SidebarFilterPopover({
const discard = useAppStore((s) => s.discardSidebarDraft);
const deleteView = useAppStore((s) => s.deleteSidebarView);
const renameView = useAppStore((s) => s.renameSidebarView);
const activeView: SidebarView | undefined = useMemo(
() => views.find((v) => v.id === activeViewId),
[views, activeViewId],
);
const current = useMemo(() => resolveCurrent(activeView, storedDraft), [storedDraft, activeView]);
const { usesDesktopWorkbench } = useResponsiveBreakpoint();
const activeView: SidebarView | undefined = views.find((view) => view.id === activeViewId);
const current = createSidebarViewEditorCurrent(activeView, storedDraft);
const hasDraft = !!storedDraft && activeView?.id === storedDraft.baseViewId;
function handleAddFilter() {
const defaultDim = DIMENSION_METAS[0];
const newClause: FilterClause = {
id: makeClauseId(),
dimension: defaultDim.dimension,
op: defaultDim.defaultOp,
value: defaultDim.defaultValue,
};
updateDraft({ filters: [...current.filters, newClause] });
}
function handleChangeClause(next: FilterClause) {
updateDraft({
filters: current.filters.map((c) => (c.id === next.id ? next : c)),
});
}
function handleRemoveClause(id: string) {
updateDraft({ filters: current.filters.filter((c) => c.id !== id) });
}
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
className="max-h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] max-w-[22rem] overflow-y-auto p-0"
align="end"
data-testid="sidebar-filter-popover"
>
<div className="border-b p-2">
<ViewHeaderRow
activeView={activeView}
hasDraft={hasDraft}
canDelete={views.length > 1}
onSaveOverwrite={saveOverwrite}
onSaveAs={saveAs}
onRename={renameView}
onDiscard={discard}
onDelete={() => activeView && deleteView(activeView.id)}
renameRequestedViewId={renameRequestedViewId}
onRenameRequestHandled={onRenameRequestHandled}
/>
</div>
<FilterSection
filters={current.filters}
onAdd={handleAddFilter}
onChange={handleChangeClause}
onRemove={handleRemoveClause}
/>
<div className="border-b px-2 pt-0 pb-2">
<SectionLabel>{t("task:sort")}</SectionLabel>
<SortPicker value={current.sort} onChange={(sort) => updateDraft({ sort })} />
</div>
<div className="px-2 pt-0 pb-2">
<SectionLabel>{t("task:groupBy")}</SectionLabel>
<GroupPicker value={current.group} onChange={(group) => updateDraft({ group })} />
</div>
</PopoverContent>
</Popover>
const headerProps: ComponentProps<typeof ViewHeaderRow> = {
activeView,
hasDraft,
canDelete: views.length > 1,
onSaveOverwrite: saveOverwrite,
onSaveAs: saveAs,
onRename: renameView,
onDiscard: discard,
onDelete: () => activeView && deleteView(activeView.id),
renameRequestedViewId,
onRenameRequestHandled,
};
const editor = (
<SidebarViewEditor
current={current}
isDrawerLayout={!usesDesktopWorkbench}
headerProps={headerProps}
onUpdate={updateDraft}
onAddFilter={() =>
updateDraft({ filters: [...current.filters, createSidebarFilterClause()] })
}
onChangeClause={(next: FilterClause) =>
updateDraft({
filters: current.filters.map((clause) => (clause.id === next.id ? next : clause)),
})
}
onRemoveClause={(id) =>
updateDraft({ filters: current.filters.filter((clause) => clause.id !== id) })
}
/>
);
}
const SECTION_LABEL_CLASS =
"text-[11px] font-medium uppercase leading-none tracking-wide text-muted-foreground";
function SectionLabel({ children }: { children: React.ReactNode }) {
return <span className={`-mt-1 mb-1 block ${SECTION_LABEL_CLASS}`}>{children}</span>;
}
function FilterSection({
filters,
onAdd,
onChange,
onRemove,
}: {
filters: FilterClause[];
onAdd: () => void;
onChange: (next: FilterClause) => void;
onRemove: (id: string) => void;
}) {
const { t } = useTranslation();
return (
<div className="border-b px-2 pt-0 pb-2">
<div className="-mt-1 mb-1 flex items-center justify-between">
<span className={SECTION_LABEL_CLASS}>{t("task:filters")}</span>
<Button
type="button"
size="sm"
variant="ghost"
className="-my-1 h-6 cursor-pointer text-xs"
onClick={onAdd}
data-testid="filter-add-button"
if (usesDesktopWorkbench) {
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
className="max-h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] max-w-[22rem] overflow-y-auto p-0"
align="end"
data-testid="sidebar-filter-popover"
>
<IconPlus className="mr-1 h-3 w-3" />
{t("task:add")}
</Button>
</div>
{filters.length > 0 && (
<div className="space-y-0.5">
{filters.map((clause) => (
<FilterClauseEditor
key={clause.id}
clause={clause}
onChange={onChange}
onRemove={() => onRemove(clause.id)}
/>
))}
{editor}
</PopoverContent>
</Popover>
);
}
return (
<Drawer open={open} onOpenChange={onOpenChange}>
<DrawerTrigger asChild>{trigger}</DrawerTrigger>
<DrawerContent
data-testid="sidebar-filter-drawer"
className="h-[min(90dvh,48rem)] max-h-[calc(100dvh-1rem)] overflow-hidden rounded-t-xl"
>
<DrawerHeader className="shrink-0 border-b px-4 pb-3 pt-5 text-left">
<DrawerTitle>{t("task:sidebarFilters")}</DrawerTitle>
</DrawerHeader>
<div
data-testid="sidebar-filter-popover"
className="min-h-0 flex-1 overflow-y-auto pb-[calc(1rem+env(safe-area-inset-bottom))]"
>
{editor}
</div>
)}
</div>
</DrawerContent>
</Drawer>
);
}
@@ -0,0 +1,165 @@
"use client";
import type { ComponentProps } from "react";
import { IconPlus } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { useTranslation } from "react-i18next";
import type {
FilterClause,
GroupKey,
SidebarView,
SidebarViewDraft,
SortSpec,
} from "@/lib/state/slices/ui/sidebar-view-types";
import { cloneSidebarTaskRowPresentation } from "@/lib/state/slices/ui/sidebar-task-row-presentation";
import { DIMENSION_METAS } from "./filter-dimension-registry";
import { FilterClauseEditor } from "./filter-clause-editor";
import { GroupPicker } from "./group-picker";
import { SortPicker } from "./sort-picker";
import { TaskRowSettings } from "./task-row-settings";
import { ViewHeaderRow } from "./view-manager";
export type SidebarViewEditorCurrent = {
filters: FilterClause[];
sort: SortSpec;
group: GroupKey;
taskRow: NonNullable<SidebarViewDraft["taskRow"]>;
};
type Props = {
current: SidebarViewEditorCurrent;
isDrawerLayout: boolean;
headerProps: ComponentProps<typeof ViewHeaderRow>;
onUpdate: (patch: Partial<SidebarViewEditorCurrent>) => void;
onAddFilter: () => void;
onChangeClause: (next: FilterClause) => void;
onRemoveClause: (id: string) => void;
};
export function SidebarViewEditor({
current,
isDrawerLayout,
headerProps,
onUpdate,
onAddFilter,
onChangeClause,
onRemoveClause,
}: Props) {
const { t } = useTranslation();
return (
<>
<div className="border-b p-2">
<ViewHeaderRow {...headerProps} />
</div>
<FilterSection
filters={current.filters}
isDrawerLayout={isDrawerLayout}
onAdd={onAddFilter}
onChange={onChangeClause}
onRemove={onRemoveClause}
/>
<div className={`border-b px-2 pb-2 ${isDrawerLayout ? "pt-2" : "pt-0"}`}>
<SectionLabel isDrawerLayout={isDrawerLayout}>{t("task:sort")}</SectionLabel>
<SortPicker value={current.sort} onChange={(sort) => onUpdate({ sort })} />
</div>
<div className={`px-2 pb-2 ${isDrawerLayout ? "pt-2" : "pt-0"}`}>
<SectionLabel isDrawerLayout={isDrawerLayout}>{t("task:groupBy")}</SectionLabel>
<GroupPicker value={current.group} onChange={(group) => onUpdate({ group })} />
</div>
<TaskRowSettings
value={current.taskRow}
sort={current.sort}
onChange={(taskRow) => onUpdate({ taskRow })}
/>
</>
);
}
const SECTION_LABEL_CLASS =
"text-[11px] font-medium uppercase leading-none tracking-wide text-muted-foreground";
function SectionLabel({
children,
isDrawerLayout,
}: {
children: React.ReactNode;
isDrawerLayout: boolean;
}) {
return (
<span className={`${isDrawerLayout ? "" : "-mt-1 "}mb-1 block ${SECTION_LABEL_CLASS}`}>
{children}
</span>
);
}
function FilterSection({
filters,
isDrawerLayout,
onAdd,
onChange,
onRemove,
}: {
filters: FilterClause[];
isDrawerLayout: boolean;
onAdd: () => void;
onChange: (next: FilterClause) => void;
onRemove: (id: string) => void;
}) {
const { t } = useTranslation();
return (
<div className={`border-b px-2 pb-2 ${isDrawerLayout ? "pt-2" : "pt-0"}`}>
<div className={`${isDrawerLayout ? "" : "-mt-1 "}mb-1 flex items-center justify-between`}>
<span className={SECTION_LABEL_CLASS}>{t("task:filters")}</span>
<Button
type="button"
size="sm"
variant="ghost"
className={`${isDrawerLayout ? "" : "-my-1 "}h-6 cursor-pointer text-xs`}
onClick={onAdd}
data-testid="filter-add-button"
>
<IconPlus className="mr-1 h-3 w-3" />
{t("task:add")}
</Button>
</div>
{filters.length > 0 && (
<div className="space-y-0.5">
{filters.map((clause) => (
<FilterClauseEditor
key={clause.id}
clause={clause}
onChange={onChange}
onRemove={() => onRemove(clause.id)}
/>
))}
</div>
)}
</div>
);
}
export function createSidebarViewEditorCurrent(
activeView: SidebarView | undefined,
storedDraft: SidebarViewDraft | null,
): SidebarViewEditorCurrent {
const source =
storedDraft && activeView && storedDraft.baseViewId === activeView.id
? storedDraft
: activeView;
return {
filters: source?.filters ?? [],
sort: source?.sort ?? { key: "state", direction: "asc" },
group: source?.group ?? "none",
taskRow: cloneSidebarTaskRowPresentation(source?.taskRow),
};
}
export function createSidebarFilterClause(): FilterClause {
const defaultDim = DIMENSION_METAS[0];
return {
id: `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
dimension: defaultDim.dimension,
op: defaultDim.defaultOp,
value: defaultDim.defaultValue,
};
}
@@ -0,0 +1,93 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { SidebarTaskRowPresentation } from "@/lib/state/slices/ui/sidebar-task-row-presentation";
import { TaskRowSettings, reorderSidebarTaskRowDetails } from "./task-row-settings";
const DEFAULT_VALUE: SidebarTaskRowPresentation = {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
};
const SETTINGS_TOGGLE_TEST_ID = "task-row-settings-toggle";
afterEach(cleanup);
describe("TaskRowSettings", () => {
it("starts collapsed and does not create a draft while opening", () => {
const onChange = vi.fn();
render(
<TaskRowSettings
value={DEFAULT_VALUE}
sort={{ key: "state", direction: "asc" }}
onChange={onChange}
/>,
);
expect(screen.queryByTestId("task-row-details-toggle")).toBeNull();
fireEvent.click(screen.getByTestId(SETTINGS_TOGGLE_TEST_ID));
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByTestId("task-row-details-toggle")).toBeTruthy();
});
it("updates detail visibility without changing the saved order", () => {
const onChange = vi.fn();
render(
<TaskRowSettings
value={DEFAULT_VALUE}
sort={{ key: "lastActivityAt", direction: "desc" }}
onChange={onChange}
/>,
);
fireEvent.click(screen.getByTestId(SETTINGS_TOGGLE_TEST_ID));
fireEvent.click(screen.getByTestId("task-row-detail-toggle-repository"));
expect(onChange).toHaveBeenCalledWith({
...DEFAULT_VALUE,
visibleDetails: ["relative_time", "pull_request_number"],
});
});
it("marks relative time as shown on the right when it is the trailing value", () => {
const onChange = vi.fn();
render(
<TaskRowSettings
value={{ ...DEFAULT_VALUE, trailing: "relative_time" }}
sort={{ key: "state", direction: "asc" }}
onChange={onChange}
/>,
);
fireEvent.click(screen.getByTestId(SETTINGS_TOGGLE_TEST_ID));
expect(screen.getByTestId("task-row-relative-time-shown-on-right").textContent).toBe(
"Shown on right",
);
});
it("keeps the mobile trailing selector touch-sized while matching compact desktop selectors", () => {
const onChange = vi.fn();
render(
<TaskRowSettings
value={DEFAULT_VALUE}
sort={{ key: "state", direction: "asc" }}
onChange={onChange}
/>,
);
fireEvent.click(screen.getByTestId(SETTINGS_TOGGLE_TEST_ID));
expect(screen.getByTestId("task-row-trailing-select").className).toContain("min-h-11");
expect(screen.getByTestId("task-row-trailing-select").className).toContain("md:h-7");
});
it("reorders fields with the same stable keys used by the drag handles", () => {
expect(
reorderSidebarTaskRowDetails(
["relative_time", "repository", "pull_request_number"],
"pull_request_number",
"relative_time",
),
).toEqual(["pull_request_number", "relative_time", "repository"]);
});
});
@@ -0,0 +1,351 @@
"use client";
import { useMemo, useState } from "react";
import {
DndContext,
KeyboardSensor,
PointerSensor,
TouchSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { IconChevronDown, IconGripVertical } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { Switch } from "@kandev/ui/switch";
import { useTranslation } from "react-i18next";
import type { SortSpec } from "@/lib/state/slices/ui/sidebar-view-types";
import {
SIDEBAR_TASK_ROW_TRAILING_KEYS,
type SidebarTaskRowDetail,
type SidebarTaskRowPresentation,
type SidebarTaskRowTrailing,
} from "@/lib/state/slices/ui/sidebar-task-row-presentation";
const DETAIL_LABEL_KEYS: Record<SidebarTaskRowDetail, string> = {
relative_time: "task:taskRowRelativeTime",
repository: "task:taskRowRepository",
pull_request_number: "task:taskRowPullRequestNumber",
};
const TRAILING_LABEL_KEYS: Record<SidebarTaskRowTrailing, string> = {
git_changes: "task:taskRowGitChanges",
relative_time: "task:taskRowRelativeTime",
change_request_status: "task:taskRowChangeRequestStatus",
none: "task:taskRowNothing",
};
const TRAILING_DESCRIPTION_KEYS: Record<SidebarTaskRowTrailing, string> = {
git_changes: "task:taskRowGitChangesDescription",
relative_time: "task:taskRowRelativeTimeDescription",
change_request_status: "task:taskRowChangeRequestStatusDescription",
none: "task:taskRowNothingDescription",
};
function TaskRowSwitch({
id,
checked,
onCheckedChange,
ariaLabel,
testId,
}: {
id: string;
checked: boolean;
onCheckedChange: (checked: boolean) => void;
ariaLabel: string;
testId: string;
}) {
return (
<label
htmlFor={id}
className="flex size-11 shrink-0 cursor-pointer items-center justify-center"
data-testid={testId}
>
<Switch
id={id}
size="sm"
checked={checked}
onCheckedChange={onCheckedChange}
aria-label={ariaLabel}
className="after:-inset-y-4"
/>
</label>
);
}
export function reorderSidebarTaskRowDetails(
order: SidebarTaskRowDetail[],
activeId: SidebarTaskRowDetail,
overId: SidebarTaskRowDetail,
): SidebarTaskRowDetail[] {
const oldIndex = order.indexOf(activeId);
const newIndex = order.indexOf(overId);
if (oldIndex < 0 || newIndex < 0 || oldIndex === newIndex) return order;
return arrayMove(order, oldIndex, newIndex);
}
function SortableDetailRow({
detail,
value,
onToggle,
}: {
detail: SidebarTaskRowDetail;
value: SidebarTaskRowPresentation;
onToggle: (detail: SidebarTaskRowDetail, checked: boolean) => void;
}) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: detail,
});
const label = t(DETAIL_LABEL_KEYS[detail]);
return (
<div
ref={setNodeRef}
data-testid={`task-row-detail-${detail}`}
style={{ transform: CSS.Transform.toString(transform), transition }}
className="flex min-h-11 items-center gap-1 rounded-md border-b border-border/40 last:border-b-0"
data-dragging={isDragging ? "true" : undefined}
>
<button
type="button"
aria-label={t("task:taskRowReorderHandle", { label })}
className="flex min-h-11 min-w-11 shrink-0 touch-none items-center justify-center text-muted-foreground/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
data-testid={`task-row-detail-handle-${detail}`}
{...attributes}
{...listeners}
aria-roledescription={t("task:taskRowReorderable")}
>
<IconGripVertical className="size-4" aria-hidden="true" />
</button>
<label htmlFor={`task-row-detail-${detail}-toggle`} className="min-w-0 flex-1 py-2">
<span className="flex flex-wrap items-baseline gap-x-2 text-xs font-medium">
<span>{label}</span>
{detail === "relative_time" && value.trailing === "relative_time" && (
<span
className="text-[11px] font-normal text-muted-foreground"
data-testid="task-row-relative-time-shown-on-right"
>
{t("task:taskRowShownOnRight")}
</span>
)}
</span>
</label>
<TaskRowSwitch
id={`task-row-detail-${detail}-toggle`}
checked={value.visibleDetails.includes(detail)}
onCheckedChange={(checked) => onToggle(detail, checked)}
ariaLabel={t("task:taskRowToggleDetail", { label })}
testId={`task-row-detail-toggle-${detail}`}
/>
</div>
);
}
function TaskRowDetailsSection({
value,
sort,
onChange,
}: {
value: SidebarTaskRowPresentation;
sort: SortSpec;
onChange: (value: SidebarTaskRowPresentation) => void;
}) {
const { t } = useTranslation();
const [announcement, setAnnouncement] = useState("");
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
const detailOrder = useMemo(() => [...value.detailOrder], [value.detailOrder]);
const relativeTimeDescriptionKey =
sort.key === "lastActivityAt"
? "task:taskRowRelativeTimeLastActivity"
: "task:taskRowRelativeTimeLastUpdate";
function update(next: Partial<SidebarTaskRowPresentation>) {
onChange({ ...value, ...next });
}
function handleDragEnd(event: DragEndEvent) {
const activeId = String(event.active.id) as SidebarTaskRowDetail;
const overId = event.over ? (String(event.over.id) as SidebarTaskRowDetail) : null;
if (!overId) return;
const nextOrder = reorderSidebarTaskRowDetails(detailOrder, activeId, overId);
if (nextOrder === detailOrder) return;
update({ detailOrder: nextOrder });
setAnnouncement(
t("task:taskRowReordered", {
label: t(DETAIL_LABEL_KEYS[activeId]),
position: nextOrder.indexOf(activeId) + 1,
}),
);
}
function handleToggle(detail: SidebarTaskRowDetail, checked: boolean) {
const visibleDetails = checked
? [...new Set([...value.visibleDetails, detail])]
: value.visibleDetails.filter((item) => item !== detail);
update({ visibleDetails });
}
return (
<div className="rounded-md border border-border/60 p-2">
<div className="flex min-h-11 items-center gap-2">
<div className="min-w-0 flex-1">
<span className="block text-xs font-medium">{t("task:taskRowDetails")}</span>
<span className="block text-[11px] text-muted-foreground">
{t("task:taskRowDetailsDescription")}
</span>
</div>
<TaskRowSwitch
id="task-row-details-toggle"
checked={value.detailsEnabled}
onCheckedChange={(detailsEnabled) => update({ detailsEnabled })}
ariaLabel={t("task:taskRowToggleDetails")}
testId="task-row-details-toggle"
/>
</div>
{value.detailsEnabled && (
<>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext items={detailOrder} strategy={verticalListSortingStrategy}>
<div className="mt-1">
{detailOrder.map((detail) => (
<SortableDetailRow
key={detail}
detail={detail}
value={value}
onToggle={handleToggle}
/>
))}
</div>
</SortableContext>
</DndContext>
<p className="px-1 pt-1 text-[11px] text-muted-foreground">
{t(relativeTimeDescriptionKey)}
</p>
</>
)}
<div aria-live="polite" className="sr-only">
{announcement}
</div>
</div>
);
}
function TaskRowTrailingSelect({
value,
onChange,
}: {
value: SidebarTaskRowPresentation;
onChange: (value: SidebarTaskRowPresentation) => void;
}) {
const { t } = useTranslation();
return (
<div className="flex min-h-11 items-center gap-2 rounded-md border border-border/60 p-2">
<label htmlFor="task-row-trailing-select" className="min-w-0 flex-1 text-xs font-medium">
{t("task:taskRowRightSide")}
</label>
<Select
value={value.trailing}
onValueChange={(trailing) =>
onChange({ ...value, trailing: trailing as SidebarTaskRowTrailing })
}
>
<SelectTrigger
id="task-row-trailing-select"
size="sm"
className="min-h-11 w-[9rem] text-xs md:min-h-0 md:h-7"
data-testid="task-row-trailing-select"
aria-label={t("task:taskRowRightSide")}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{SIDEBAR_TASK_ROW_TRAILING_KEYS.map((trailing) => {
const label = t(TRAILING_LABEL_KEYS[trailing]);
return (
<SelectItem
key={trailing}
value={trailing}
className="text-xs"
aria-label={label}
description={t(TRAILING_DESCRIPTION_KEYS[trailing])}
>
{label}
</SelectItem>
);
})}
</SelectContent>
</Select>
</div>
);
}
export function TaskRowSettings({
value,
sort,
onChange,
}: {
value: SidebarTaskRowPresentation;
sort: SortSpec;
onChange: (value: SidebarTaskRowPresentation) => void;
}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const detailCountLabel = t("task:taskRowDetailsCount", {
count: value.visibleDetails.length,
});
const trailingLabel = t(TRAILING_LABEL_KEYS[value.trailing]);
return (
<section className="border-t px-2 pb-2 pt-2" data-testid="task-row-settings">
<Button
type="button"
variant="ghost"
className="flex min-h-11 w-full items-center justify-between px-1 text-left"
aria-expanded={expanded}
aria-controls="task-row-settings-content"
data-testid="task-row-settings-toggle"
onClick={() => setExpanded((current) => !current)}
>
<span className="min-w-0">
<span className="block text-[11px] font-medium uppercase leading-none tracking-wide text-muted-foreground">
{t("task:taskRow")}
</span>
<span className="mt-1 block truncate text-xs text-muted-foreground">
{value.detailsEnabled ? detailCountLabel : t("task:taskRowDetailsHidden")} {" · "}
{trailingLabel}
</span>
</span>
<IconChevronDown
className={`size-4 shrink-0 text-muted-foreground transition-transform ${expanded ? "rotate-180" : ""}`}
aria-hidden="true"
/>
</Button>
{expanded && (
<div id="task-row-settings-content" className="space-y-2 pt-1">
<TaskRowDetailsSection value={value} sort={sort} onChange={onChange} />
<TaskRowTrailingSelect value={value} onChange={onChange} />
</div>
)}
</section>
);
}
@@ -1,6 +1,6 @@
"use client";
import { useLayoutEffect, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Input } from "@kandev/ui/input";
import { Button } from "@kandev/ui/button";
import type { SidebarView } from "@/lib/state/slices/ui/sidebar-view-types";
@@ -150,9 +150,18 @@ function NameInput({
inputRef.current?.select();
}, []);
useEffect(() => {
const frame = requestAnimationFrame(() => {
inputRef.current?.focus();
inputRef.current?.select();
});
return () => cancelAnimationFrame(frame);
}, []);
return (
<Input
ref={inputRef}
autoFocus
aria-label={mode === "rename" ? t("task:viewName") : t("task:newViewName")}
value={value}
onChange={(e) => onChange(e.target.value)}
@@ -0,0 +1,21 @@
import { RegisteredChangeRequestTaskIcon } from "@/components/integrations/registered-change-request-task-icon";
import { TaskContributionIcons } from "./task-contribution-icons";
export function TaskItemChangeRequestStatus({
taskId,
prInfo,
}: {
taskId?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
}) {
if (!taskId && !prInfo) return null;
return (
<span
data-testid="sidebar-task-change-request-status"
className="inline-flex shrink-0 items-center gap-1"
>
<TaskContributionIcons taskId={taskId} prInfo={prInfo} />
{taskId ? <RegisteredChangeRequestTaskIcon taskId={taskId} /> : null}
</span>
);
}
@@ -0,0 +1,49 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { StateProvider } from "@/components/state-provider";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { TaskItem } from "./task-item";
afterEach(() => cleanup());
describe("TaskItem compact layout", () => {
it("centers the title content when the details row is disabled", () => {
render(
<StateProvider>
<TooltipProvider>
<TaskItem
title="Needs answer"
state="REVIEW"
taskRowPresentation={{
detailsEnabled: false,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: [],
trailing: "none",
}}
/>
</TooltipProvider>
</StateProvider>,
);
const row = screen.getByTestId("sidebar-task-item");
expect(row.className).toContain("items-center");
expect(row.className).not.toContain("items-start");
});
it("animates the running status on an HTML wrapper", () => {
render(
<StateProvider>
<TooltipProvider>
<TaskItem title="Needs answer" state="IN_PROGRESS" sessionState="RUNNING" />
</TooltipProvider>
</StateProvider>,
);
const spinner = screen.getByTestId("task-state-running");
expect(spinner.tagName).toBe("SPAN");
expect(spinner.classList.contains("animate-spin")).toBe(true);
const spinnerSvg = spinner.querySelector("svg");
expect(spinnerSvg).not.toBeNull();
expect(spinnerSvg?.classList.contains("animate-spin")).toBe(false);
});
});
@@ -13,6 +13,7 @@ export function TaskItemLeadingBadges({
isPinned,
taskId,
prInfo,
showChangeRequestStatus = true,
issueInfo,
agentErrorMessage,
}: {
@@ -20,6 +21,7 @@ export function TaskItemLeadingBadges({
isPinned?: boolean;
taskId?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
showChangeRequestStatus?: boolean;
issueInfo?: { url: string; number: number };
agentErrorMessage?: string | null;
}) {
@@ -32,8 +34,10 @@ export function TaskItemLeadingBadges({
className="h-3 w-3 shrink-0 text-muted-foreground/60"
/>
)}
<TaskContributionIcons taskId={taskId} prInfo={prInfo} />
{taskId ? <RegisteredChangeRequestTaskIcon taskId={taskId} /> : null}
{showChangeRequestStatus && <TaskContributionIcons taskId={taskId} prInfo={prInfo} />}
{showChangeRequestStatus && taskId ? (
<RegisteredChangeRequestTaskIcon taskId={taskId} />
) : null}
{issueInfo && <IssueTaskIcon issueInfo={issueInfo} />}
{agentErrorMessage && <TaskAgentErrorIcon message={agentErrorMessage} />}
</>
+162 -60
View File
@@ -2,12 +2,17 @@
import { IconClockHour4, IconMail } from "@tabler/icons-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { Fragment, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { useAppStore } from "@/components/state-provider";
import { isDebugUI } from "@/lib/config";
import type { SessionPollMode } from "@/lib/state/slices/session-runtime/types";
import { cn, formatRelativeTime } from "@/lib/utils";
import type { WipQueueStatus } from "@/lib/kanban/wip-queue";
import {
SIDEBAR_TASK_ROW_DETAIL_KEYS,
type SidebarTaskRowDetail,
} from "@/lib/state/slices/ui/sidebar-task-row-presentation";
/** Debug-overlay-only poll-mode legend. Labels resolve through `t()` so the
* pseudo-locale stays complete; the row itself is gated behind `isDebugUI()`. */
@@ -42,6 +47,126 @@ function RepositoryLabel({ label }: { label?: string }) {
);
}
function buildDetailNodes({
updatedAt,
repositoryLabel,
prInfo,
hasRelativeTime,
hasRepository,
hasPullRequestNumber,
}: {
updatedAt?: string;
repositoryLabel?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
hasRelativeTime: boolean;
hasRepository: boolean;
hasPullRequestNumber: boolean;
}): Record<SidebarTaskRowDetail, ReactNode> {
return {
relative_time:
hasRelativeTime && updatedAt ? (
<span
data-testid="sidebar-task-time"
data-time-value={updatedAt}
className="shrink-0 text-muted-foreground/50"
>
{formatRelativeTime(updatedAt)}
</span>
) : null,
repository: hasRepository ? <RepositoryLabel label={repositoryLabel} /> : null,
pull_request_number:
hasPullRequestNumber && prInfo ? (
<span className="shrink-0 text-muted-foreground/50">#{prInfo.number}</span>
) : null,
};
}
function QueuedPromptCount({ count }: { count?: number }) {
const { t } = useTranslation();
if (!count) return null;
const label = t("sidebar:queuedPromptCount", { count });
return (
<span
data-testid="sidebar-task-queued-count"
aria-label={label}
title={label}
className="inline-flex shrink-0 items-center gap-0.5 text-muted-foreground/60"
>
<IconMail className="h-3 w-3" aria-hidden="true" />
{count}
</span>
);
}
function WipQueueIndicator({ wipQueue }: { wipQueue?: WipQueueStatus }) {
const { t } = useTranslation();
if (!wipQueue) return null;
const label = t("sidebar:wipQueuePosition", {
position: wipQueue.position,
total: wipQueue.total,
step: wipQueue.destinationTitle,
});
return (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid="sidebar-task-wip-queue"
tabIndex={0}
aria-label={label}
title={label}
className="inline-flex shrink-0 items-center text-muted-foreground/60 outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<IconClockHour4 className="h-3.5 w-3.5" aria-hidden="true" />
</span>
</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
</Tooltip>
);
}
function PollModeIndicator({
pollMode,
config,
}: {
pollMode: SessionPollMode | null;
config: (typeof POLL_MODE_CONFIG)[SessionPollMode] | null;
}) {
const { t } = useTranslation();
if (!pollMode || !config) return null;
return (
<Tooltip>
<TooltipTrigger asChild>
<span className={cn("font-mono text-[10px] font-semibold", config.color)}>
{config.letter}
</span>
</TooltipTrigger>
<TooltipContent side="right">
{t("task:gitPollMode", { mode: pollMode, label: t(config.labelKey) })}
</TooltipContent>
</Tooltip>
);
}
function hasStatsToRender({
hasRelativeTime,
hasRepository,
hasPullRequestNumber,
pollMode,
queuedCount,
wipQueue,
}: {
hasRelativeTime: boolean;
hasRepository: boolean;
hasPullRequestNumber: boolean;
pollMode: SessionPollMode | null;
queuedCount?: number;
wipQueue?: WipQueueStatus;
}): boolean {
return Boolean(
hasRelativeTime || hasRepository || hasPullRequestNumber || pollMode || queuedCount || wipQueue,
);
}
/**
* The sidebar row's metadata line: relative last-update time, repository, PR number,
* queued-prompt mail badge, WIP queue icon, and (debug UI only) the session
@@ -54,6 +179,10 @@ export function TaskItemStatsRow({
primarySessionId,
queuedCount,
wipQueue,
detailOrder = [...SIDEBAR_TASK_ROW_DETAIL_KEYS],
showRelativeTime = true,
showRepository = true,
showPullRequestNumber = true,
}: {
updatedAt?: string;
/** Repository the task belongs to; already resolved to a slug or name. */
@@ -62,80 +191,53 @@ export function TaskItemStatsRow({
primarySessionId?: string | null;
queuedCount?: number;
wipQueue?: WipQueueStatus;
detailOrder?: SidebarTaskRowDetail[];
showRelativeTime?: boolean;
showRepository?: boolean;
showPullRequestNumber?: boolean;
}) {
const { t } = useTranslation();
const pollMode = useAppStore((s) =>
isDebugUI() && primarySessionId
? (s.sessionPollMode.bySessionId[primarySessionId] ?? null)
: null,
);
if (!updatedAt && !repositoryLabel && !prInfo && !pollMode && !queuedCount && !wipQueue) {
const hasRelativeTime = showRelativeTime && !!updatedAt;
const hasRepository = showRepository && !!repositoryLabel;
const hasPullRequestNumber = showPullRequestNumber && !!prInfo;
if (
!hasStatsToRender({
hasRelativeTime,
hasRepository,
hasPullRequestNumber,
pollMode,
queuedCount,
wipQueue,
})
) {
return null;
}
const modeConfig = pollMode ? POLL_MODE_CONFIG[pollMode] : null;
const modeLabel = modeConfig ? t(modeConfig.labelKey) : "";
const wipQueueLabel = wipQueue
? t("sidebar:wipQueuePosition", {
position: wipQueue.position,
total: wipQueue.total,
step: wipQueue.destinationTitle,
})
: "";
const detailNodes = buildDetailNodes({
updatedAt,
repositoryLabel,
prInfo,
hasRelativeTime,
hasRepository,
hasPullRequestNumber,
});
return (
<span className="flex min-w-0 items-center gap-1.5 text-[11px]">
{updatedAt && (
<span
data-testid="sidebar-task-time"
data-time-value={updatedAt}
className="shrink-0 text-muted-foreground/50"
>
{formatRelativeTime(updatedAt)}
</span>
)}
<RepositoryLabel label={repositoryLabel} />
{prInfo && <span className="shrink-0 text-muted-foreground/50">#{prInfo.number}</span>}
{queuedCount ? (
<span
data-testid="sidebar-task-queued-count"
aria-label={t("sidebar:queuedPromptCount", { count: queuedCount })}
title={t("sidebar:queuedPromptCount", { count: queuedCount })}
className="inline-flex shrink-0 items-center gap-0.5 text-muted-foreground/60"
>
<IconMail className="h-3 w-3" aria-hidden="true" />
{queuedCount}
</span>
) : null}
{wipQueue ? (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid="sidebar-task-wip-queue"
tabIndex={0}
aria-label={wipQueueLabel}
title={wipQueueLabel}
className="inline-flex shrink-0 items-center text-muted-foreground/60 outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<IconClockHour4 className="h-3.5 w-3.5" aria-hidden="true" />
</span>
</TooltipTrigger>
<TooltipContent side="right">{wipQueueLabel}</TooltipContent>
</Tooltip>
) : null}
{modeConfig && (
<Tooltip>
<TooltipTrigger asChild>
<span className={cn("font-mono text-[10px] font-semibold", modeConfig.color)}>
{modeConfig.letter}
</span>
</TooltipTrigger>
<TooltipContent side="right">
{t("task:gitPollMode", { mode: pollMode, label: modeLabel })}
</TooltipContent>
</Tooltip>
{detailOrder.map((detail) =>
detailNodes[detail] ? <Fragment key={detail}>{detailNodes[detail]}</Fragment> : null,
)}
<QueuedPromptCount count={queuedCount} />
<WipQueueIndicator wipQueue={wipQueue} />
<PollModeIndicator
pollMode={pollMode}
config={pollMode ? POLL_MODE_CONFIG[pollMode] : null}
/>
</span>
);
}
@@ -0,0 +1,23 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { TaskItemTrailing } from "./task-item-trailing";
afterEach(cleanup);
describe("TaskItemTrailing relative time", () => {
it("uses the outer task-row menu disclosure hover and focus selectors", () => {
render(
<TaskItemTrailing
trailing="relative_time"
menuOpen={false}
effectiveMenuOpen={false}
relativeTime="2026-07-24T00:00:00Z"
/>,
);
const relativeTime = screen.getByTestId("sidebar-task-trailing-time");
expect(relativeTime.className).toContain("group-hover:opacity-0");
expect(relativeTime.className).toContain("group-focus-within/actions:opacity-0");
expect(relativeTime.className).not.toContain("group-hover/actions:opacity-0");
});
});
@@ -0,0 +1,87 @@
import { TaskMenuButton } from "./task-item-menu-button";
import { TaskItemChangeRequestStatus } from "./task-item-change-request-status";
import type { SidebarTaskRowTrailing } from "@/lib/state/slices/ui/sidebar-task-row-presentation";
import { cn, formatRelativeTime } from "@/lib/utils";
type DiffStats = { additions: number; deletions: number };
function DiffStatsRight({ diffStats, menuOpen }: { diffStats: DiffStats; menuOpen: boolean }) {
return (
<div
data-testid="sidebar-task-diff-stats"
className={cn(
"mobile-task-diff-stats shrink-0 self-center font-mono text-[11px] transition-opacity duration-100",
menuOpen
? "opacity-0"
: "[@media(hover:hover)]:group-hover:opacity-0 group-focus-within/actions:opacity-0",
)}
>
<span className="text-emerald-500">+{diffStats.additions}</span>{" "}
<span className="text-rose-500">-{diffStats.deletions}</span>
</div>
);
}
export function TaskItemTrailing({
trailing,
diffStats,
menuOpen,
effectiveMenuOpen,
relativeTime,
taskId,
prInfo,
}: {
trailing: SidebarTaskRowTrailing;
diffStats?: DiffStats;
menuOpen: boolean;
effectiveMenuOpen: boolean;
relativeTime?: string;
taskId?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
}) {
const hasDiffStats = !!diffStats && (diffStats.additions > 0 || diffStats.deletions > 0);
if (trailing === "git_changes" && hasDiffStats) {
return (
<div className="mobile-task-actions-with-stats group/actions relative flex shrink-0 items-center self-center">
<DiffStatsRight diffStats={diffStats} menuOpen={effectiveMenuOpen} />
<div className="mobile-task-actions-slot absolute inset-0 flex items-center justify-end">
<TaskMenuButton visible={effectiveMenuOpen} expanded={menuOpen} />
</div>
</div>
);
}
if (trailing === "relative_time" && relativeTime) {
return (
<div className="group/actions relative flex shrink-0 items-center self-center">
<span
data-testid="sidebar-task-trailing-time"
data-time-value={relativeTime}
className={cn(
"shrink-0 text-[11px] text-muted-foreground/50 transition-opacity duration-100",
effectiveMenuOpen && "opacity-0",
!effectiveMenuOpen &&
"[@media(hover:hover)]:group-hover:opacity-0 group-focus-within/actions:opacity-0",
)}
>
{formatRelativeTime(relativeTime)}
</span>
<div className="mobile-task-actions-slot absolute inset-0 flex items-center justify-end">
<TaskMenuButton visible={effectiveMenuOpen} expanded={menuOpen} />
</div>
</div>
);
}
if (trailing === "change_request_status") {
return (
<div className="flex shrink-0 items-center gap-1 self-center">
<TaskItemChangeRequestStatus taskId={taskId} prInfo={prInfo} />
<TaskMenuButton visible={effectiveMenuOpen} expanded={menuOpen} rowFocus />
</div>
);
}
return <TaskMenuButton visible={effectiveMenuOpen} expanded={menuOpen} rowFocus />;
}
+23 -13
View File
@@ -115,19 +115,6 @@ function expectPreparingSpinner(): void {
expect(icon.classList.contains(SLOW_SPIN_CLASS)).toBe(true);
}
describe("TaskItem status icon", () => {
it("animates the running status on an HTML wrapper", () => {
renderTaskItem({ state: "IN_PROGRESS", sessionState: "RUNNING" });
const spinner = screen.getByTestId(RUNNING_ICON_TEST_ID);
expect(spinner.tagName).toBe("SPAN");
expect(spinner.classList.contains(SPIN_CLASS)).toBe(true);
const spinnerSvg = spinner.querySelector("svg");
expect(spinnerSvg).not.toBeNull();
expect(spinnerSvg?.classList.contains(SPIN_CLASS)).toBe(false);
});
});
describe("TaskItem status icon states", () => {
it("shows the autopilot icon with an accessible description", () => {
renderTaskItem({ autopilot: true });
@@ -624,6 +611,29 @@ describe("TaskItem activity timestamp", () => {
});
});
describe("TaskItem task-row presentation", () => {
it("moves relative time to the trailing slot and hides the details row", () => {
renderTaskItem({
taskId: "t1",
updatedAt: "2026-07-24T00:00:00Z",
repositoryPath: "acme/api",
showRepository: true,
diffStats: { additions: 2, deletions: 1 },
taskRowPresentation: {
detailsEnabled: false,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: [],
trailing: "relative_time",
},
});
expect(screen.queryByTestId("sidebar-task-time")).toBeNull();
expect(screen.queryByTestId("sidebar-task-repository")).toBeNull();
expect(screen.queryByTestId("sidebar-task-diff-stats")).toBeNull();
expect(screen.getByTestId("sidebar-task-trailing-time")).toBeTruthy();
});
});
describe("TaskItem contribution badges", () => {
it("renders the PR badge before the MR badge when the task has both (AC2)", () => {
renderTaskItem(
+146 -100
View File
@@ -29,8 +29,12 @@ import { ScrollOnOverflow } from "@kandev/ui/scroll-on-overflow";
import { useTranslation } from "react-i18next";
import { TaskItemComparisonUnavailable } from "./task-item-comparison-unavailable";
import type { WipQueueStatus } from "@/lib/kanban/wip-queue";
import { TaskMenuButton } from "./task-item-menu-button";
import { TaskItemLeadingBadges } from "./task-item-leading-badges";
import {
resolveTaskRowPresentation,
type ResolvedTaskRowPresentation,
} from "./task-row-presentation";
import { TaskItemTrailing } from "./task-item-trailing";
import { CompositorSpin } from "@kandev/ui/compositor-spin";
type DiffStats = {
@@ -115,6 +119,7 @@ type TaskItemProps = {
issueInfo?: { url: string; number: number };
isPinned?: boolean;
agentErrorMessage?: string | null;
taskRowPresentation?: import("@/lib/state/slices/ui/sidebar-task-row-presentation").SidebarTaskRowPresentation;
};
// Delegates to the shared classifier in task-switcher so the sidebar bucket
@@ -159,9 +164,11 @@ function taskItemRowClassName(
isSelected: boolean,
isMultiSelected: boolean,
isRoot: boolean,
hasDetails: boolean,
): string {
return cn(
"group relative flex w-full items-start gap-2 py-2 pr-3 text-left text-sm outline-none cursor-pointer",
"group relative flex w-full gap-2 py-2 pr-3 text-left text-sm outline-none cursor-pointer",
hasDetails ? "items-start" : "items-center",
"transition-colors duration-75 hover:bg-foreground/[0.05]",
isSelected && "bg-primary/10",
// When a row is both the active task and multi-selected, keep the stronger
@@ -320,23 +327,6 @@ function TaskStateIcon({
);
}
function DiffStatsRight({ diffStats, menuOpen }: { diffStats: DiffStats; menuOpen: boolean }) {
return (
<div
data-testid="sidebar-task-diff-stats"
className={cn(
"mobile-task-diff-stats shrink-0 self-center font-mono text-[11px] transition-opacity duration-100",
menuOpen
? "opacity-0"
: "[@media(hover:hover)]:group-hover:opacity-0 group-focus-within/actions:opacity-0",
)}
>
<span className="text-emerald-500">+{diffStats.additions}</span>{" "}
<span className="text-rose-500">-{diffStats.deletions}</span>
</div>
);
}
function TaskItemTitle({ title }: { title: string }) {
return <ScrollOnOverflow className="min-w-0 w-full">{title}</ScrollOnOverflow>;
}
@@ -353,16 +343,14 @@ function TaskItemContent({
isArchived,
isPinned,
repositoryPath,
showRepository,
updatedAt,
lastActivityAt,
showActivityTime,
prInfo,
queuedCount,
wipQueue,
issueInfo,
agentErrorMessage,
comparisonUnavailable,
resolvedTaskRow,
relativeTime,
}: {
title: string;
autopilot?: boolean;
@@ -375,16 +363,14 @@ function TaskItemContent({
isArchived?: boolean;
isPinned?: boolean;
repositoryPath?: string;
showRepository: boolean;
updatedAt?: string;
lastActivityAt?: string;
showActivityTime?: boolean;
prInfo?: { number: number; state: string; aggregateState?: string };
queuedCount?: number;
wipQueue?: WipQueueStatus;
issueInfo?: { url: string; number: number };
agentErrorMessage?: string | null;
comparisonUnavailable?: boolean;
resolvedTaskRow: ResolvedTaskRowPresentation;
relativeTime?: string;
}) {
const { t } = useTranslation();
return (
@@ -396,6 +382,7 @@ function TaskItemContent({
isPinned={isPinned}
taskId={taskId}
prInfo={prInfo}
showChangeRequestStatus={resolvedTaskRow.trailing !== "change_request_status"}
issueInfo={issueInfo}
agentErrorMessage={agentErrorMessage}
/>
@@ -415,129 +402,188 @@ function TaskItemContent({
</span>
)}
</span>
{taskId && (
{taskId && resolvedTaskRow.detailsEnabled && (
<TaskRowMetadata
taskId={taskId}
workflowStepId={workflowStepId ?? null}
surface="sidebar"
/>
)}
<TaskItemStatsRow
updatedAt={showActivityTime ? (lastActivityAt ?? updatedAt) : updatedAt}
repositoryLabel={showRepository ? repositoryPath : undefined}
prInfo={prInfo}
primarySessionId={primarySessionId}
queuedCount={queuedCount}
wipQueue={wipQueue}
/>
{resolvedTaskRow.detailsEnabled && (
<TaskItemStatsRow
updatedAt={relativeTime}
repositoryLabel={resolvedTaskRow.showRepository ? repositoryPath : undefined}
prInfo={resolvedTaskRow.showPullRequestNumber ? prInfo : undefined}
primarySessionId={primarySessionId}
queuedCount={queuedCount}
wipQueue={wipQueue}
detailOrder={resolvedTaskRow.detailOrder}
showRelativeTime={resolvedTaskRow.showRelativeTime}
showRepository={resolvedTaskRow.showRepository}
showPullRequestNumber={resolvedTaskRow.showPullRequestNumber}
/>
)}
</div>
);
}
function TaskItemActions({
archiveConfirmation,
resolvedTaskRow,
diffStats,
hasDiffStats,
menuOpen,
effectiveMenuOpen,
relativeTime,
taskId,
prInfo,
}: {
archiveConfirmation?: ReactNode;
resolvedTaskRow: ResolvedTaskRowPresentation;
diffStats?: DiffStats;
hasDiffStats: boolean;
menuOpen: boolean;
effectiveMenuOpen: boolean;
relativeTime?: string;
taskId?: string;
prInfo?: { number: number; state: string; aggregateState?: string };
}) {
if (archiveConfirmation) {
return (
<div className="min-w-0 basis-full flex items-center justify-end">{archiveConfirmation}</div>
);
}
if (hasDiffStats) {
return (
<div className="mobile-task-actions-with-stats group/actions relative shrink-0 self-center flex items-center">
<DiffStatsRight diffStats={diffStats!} menuOpen={effectiveMenuOpen} />
<div className="mobile-task-actions-slot absolute inset-0 flex items-center justify-end">
<TaskMenuButton visible={effectiveMenuOpen} expanded={menuOpen} />
</div>
</div>
);
}
return <TaskMenuButton visible={effectiveMenuOpen} expanded={menuOpen} rowFocus />;
return (
<TaskItemTrailing
trailing={resolvedTaskRow.trailing}
diffStats={diffStats}
menuOpen={menuOpen}
effectiveMenuOpen={effectiveMenuOpen}
relativeTime={relativeTime}
taskId={taskId}
prInfo={prInfo}
/>
);
}
export const TaskItem = memo(function TaskItem(props: TaskItemProps) {
const isSelected = props.isSelected ?? false;
const isMultiSelected = props.isMultiSelected ?? false;
const menuOpen = props.menuOpen ?? false;
const effectiveMenuOpen = menuOpen || props.isDeleting === true;
const hasDiffStats =
!!props.diffStats && (props.diffStats.additions > 0 || props.diffStats.deletions > 0);
const taskColor = useTaskColor(props.taskId);
const indent = computeRowIndent(resolveRowDepth(props.depth, props.isSubTask));
// eslint-disable-next-line max-lines-per-function
export const TaskItem = memo(function TaskItem({
title,
autopilot,
state,
sessionState,
foregroundActivity,
isArchived,
isSelected = false,
isMultiSelected = false,
onClick,
onSelect,
diffStats,
archiveConfirmation,
comparisonUnavailable,
isRemoteExecutor,
remoteExecutorType,
remoteExecutorName,
updatedAt,
lastActivityAt,
showActivityTime = false,
menuOpen = false,
isDeleting,
taskId,
workflowStepId,
primarySessionId,
hasPendingClarification,
hasPendingPermission,
interrupted,
isSubTask,
depth,
subtaskCount,
subtasksCollapsed,
onToggleSubtasks,
repositoryPath,
showRepository = true,
prInfo,
queuedCount,
wipQueue,
issueInfo,
isPinned,
agentErrorMessage,
isOnLastWorkflowStep = false,
taskRowPresentation,
}: TaskItemProps) {
const effectiveMenuOpen = menuOpen || isDeleting === true;
const resolvedTaskRow = resolveTaskRowPresentation(taskRowPresentation, { showRepository });
const relativeTime = showActivityTime ? (lastActivityAt ?? updatedAt) : updatedAt;
const taskColor = useTaskColor(taskId);
const indent = computeRowIndent(resolveRowDepth(depth, isSubTask));
return (
<div
role="button"
tabIndex={0}
data-testid="sidebar-task-item"
data-task-row-id={props.taskId}
data-task-row-id={taskId}
{...taskItemStateAttrs(isSelected, isMultiSelected)}
onClick={taskItemRowClick(props.onSelect, props.onClick)}
onKeyDown={(e) => handleTaskItemKeyDown(e, props.onSelect, props.onClick)}
onClick={taskItemRowClick(onSelect, onClick)}
onKeyDown={(e) => handleTaskItemKeyDown(e, onSelect, onClick)}
style={indent.depth > 0 ? { paddingLeft: indent.paddingLeftPx } : undefined}
className={cn(
taskItemRowClassName(isSelected, isMultiSelected, indent.depth === 0),
props.archiveConfirmation && "flex-wrap",
taskItemRowClassName(
isSelected,
isMultiSelected,
indent.depth === 0,
resolvedTaskRow.detailsEnabled,
),
archiveConfirmation && "flex-wrap",
)}
>
<SelectionBar isSelected={isSelected} color={taskColor} />
<RowConnector depth={indent.depth} leftPx={indent.connectorLeftPx} />
<TaskStateIcon
sessionState={props.sessionState}
state={props.state}
foregroundActivity={props.foregroundActivity}
isInProgress={computeIsInProgress(props.state, props.sessionState)}
hasPendingClarification={props.hasPendingClarification}
hasPendingPermission={props.hasPendingPermission}
interrupted={props.interrupted}
isOnLastWorkflowStep={props.isOnLastWorkflowStep ?? false}
sessionState={sessionState}
state={state}
foregroundActivity={foregroundActivity}
isInProgress={computeIsInProgress(state, sessionState)}
hasPendingClarification={hasPendingClarification}
hasPendingPermission={hasPendingPermission}
interrupted={interrupted}
isOnLastWorkflowStep={isOnLastWorkflowStep}
/>
<TaskItemContent
title={props.title}
autopilot={props.autopilot}
taskId={props.taskId}
workflowStepId={props.workflowStepId}
isRemoteExecutor={props.isRemoteExecutor}
remoteExecutorType={props.remoteExecutorType}
remoteExecutorName={props.remoteExecutorName}
primarySessionId={props.primarySessionId}
isArchived={props.isArchived}
isPinned={props.isPinned}
repositoryPath={props.repositoryPath}
showRepository={props.showRepository ?? true}
updatedAt={props.updatedAt}
lastActivityAt={props.lastActivityAt}
showActivityTime={props.showActivityTime ?? false}
prInfo={props.prInfo}
queuedCount={props.queuedCount}
wipQueue={props.wipQueue}
issueInfo={props.issueInfo}
agentErrorMessage={props.agentErrorMessage}
comparisonUnavailable={props.comparisonUnavailable}
title={title}
autopilot={autopilot}
taskId={taskId}
workflowStepId={workflowStepId}
isRemoteExecutor={isRemoteExecutor}
remoteExecutorType={remoteExecutorType}
remoteExecutorName={remoteExecutorName}
primarySessionId={primarySessionId}
isArchived={isArchived}
isPinned={isPinned}
repositoryPath={repositoryPath}
prInfo={prInfo}
queuedCount={queuedCount}
wipQueue={wipQueue}
issueInfo={issueInfo}
agentErrorMessage={agentErrorMessage}
comparisonUnavailable={comparisonUnavailable}
resolvedTaskRow={resolvedTaskRow}
relativeTime={relativeTime}
/>
<TaskItemActions
archiveConfirmation={props.archiveConfirmation}
diffStats={props.diffStats}
hasDiffStats={hasDiffStats}
archiveConfirmation={archiveConfirmation}
resolvedTaskRow={resolvedTaskRow}
diffStats={diffStats}
menuOpen={menuOpen}
effectiveMenuOpen={effectiveMenuOpen}
relativeTime={relativeTime}
taskId={taskId}
prInfo={prInfo}
/>
{!!props.subtaskCount && props.subtaskCount > 0 && !!props.onToggleSubtasks && (
{!!subtaskCount && subtaskCount > 0 && !!onToggleSubtasks && (
<SubtaskToggle
taskId={props.taskId}
count={props.subtaskCount}
collapsed={!!props.subtasksCollapsed}
onToggle={props.onToggleSubtasks}
taskId={taskId}
count={subtaskCount}
collapsed={!!subtasksCollapsed}
onToggle={onToggleSubtasks}
/>
)}
</div>
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { resolveTaskRowPresentation } from "./task-row-presentation";
describe("resolveTaskRowPresentation", () => {
it("keeps the configured order while hiding disabled details", () => {
expect(
resolveTaskRowPresentation(
{
detailsEnabled: true,
detailOrder: ["pull_request_number", "repository", "relative_time"],
visibleDetails: ["repository", "relative_time"],
trailing: "git_changes",
},
{ showRepository: true },
),
).toMatchObject({
detailOrder: ["repository", "relative_time"],
showRepository: true,
showRelativeTime: true,
showPullRequestNumber: false,
});
});
it("suppresses repository metadata when the view groups by repository", () => {
const resolved = resolveTaskRowPresentation(undefined, { showRepository: false });
expect(resolved.showRepository).toBe(false);
expect(resolved.showPullRequestNumber).toBe(true);
});
it("moves relative time to the trailing slot without duplicating it", () => {
const resolved = resolveTaskRowPresentation(
{
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "relative_time",
},
{ showRepository: true },
);
expect(resolved.showRelativeTime).toBe(false);
expect(resolved.detailOrder).toContain("relative_time");
expect(resolved.trailing).toBe("relative_time");
});
});
@@ -0,0 +1,36 @@
import {
normalizeSidebarTaskRowPresentation,
type SidebarTaskRowDetail,
type SidebarTaskRowPresentation,
type SidebarTaskRowTrailing,
} from "@/lib/state/slices/ui/sidebar-task-row-presentation";
export type ResolvedTaskRowPresentation = {
detailsEnabled: boolean;
detailOrder: SidebarTaskRowDetail[];
showRelativeTime: boolean;
showRepository: boolean;
showPullRequestNumber: boolean;
trailing: SidebarTaskRowTrailing;
};
/** Resolves saved row settings against view-specific repository grouping. */
export function resolveTaskRowPresentation(
value: SidebarTaskRowPresentation | undefined,
options: { showRepository: boolean },
): ResolvedTaskRowPresentation {
const presentation = normalizeSidebarTaskRowPresentation(value);
const visible = new Set(presentation.visibleDetails);
const detailOrder = presentation.detailOrder.filter((detail) => visible.has(detail));
const detailsEnabled = presentation.detailsEnabled;
return {
detailsEnabled,
detailOrder,
showRelativeTime:
detailsEnabled && visible.has("relative_time") && presentation.trailing !== "relative_time",
showRepository: detailsEnabled && options.showRepository && visible.has("repository"),
showPullRequestNumber: detailsEnabled && visible.has("pull_request_number"),
trailing: presentation.trailing,
};
}
@@ -20,6 +20,7 @@ export function buildTaskSwitcherProps(args: {
effectiveView: {
collapsedGroups: TaskSwitcherComponentProps["collapsedGroupKeys"];
sort: { key: string };
taskRow?: TaskSwitcherComponentProps["taskRowPresentation"];
};
handleToggleGroup: TaskSwitcherComponentProps["onToggleGroup"];
collapsedSubtaskParents: TaskSwitcherComponentProps["collapsedSubtaskParentIds"];
@@ -47,6 +48,7 @@ export function buildTaskSwitcherProps(args: {
selectedTaskId: args.highlightedSelectedTaskId,
collapsedGroupKeys: args.effectiveView.collapsedGroups,
showActivityTime: args.effectiveView.sort.key === "lastActivityAt",
taskRowPresentation: args.effectiveView.taskRow,
onToggleGroup: args.handleToggleGroup,
collapsedSubtaskParentIds: args.collapsedSubtaskParents,
onToggleSubtasks: args.toggleSubtaskCollapsed,
@@ -6,6 +6,7 @@ import { TaskItem } from "./task-item";
import { TaskItemWithContextMenu } from "./task-switcher-context-menu";
import { dispatchSidebarRowClick } from "./task-switcher-click";
import type { TaskMoveWorkflow } from "@/components/task/task-move-context-menu";
import type { SidebarTaskRowPresentation } from "@/lib/state/slices/ui/sidebar-task-row-presentation";
export type SubtaskToggleInfo = {
subtaskCount: number;
@@ -25,6 +26,7 @@ export type TaskRowProps = {
showActivityTime?: boolean;
/** False when the list is grouped by repository and the header already names it. */
showRepository?: boolean;
taskRowPresentation?: SidebarTaskRowPresentation;
onSelectTask: (taskId: string) => void;
onEditTask?: (task: TaskSwitcherItem) => void;
onRenameTask?: (taskId: string, currentTitle: string) => void;
@@ -100,6 +102,7 @@ type TaskRowItemProps = Pick<
| "selectedTaskId"
| "showActivityTime"
| "showRepository"
| "taskRowPresentation"
| "onSelectTask"
| "selectedTaskIds"
| "onToggleSelectTask"
@@ -118,6 +121,7 @@ function TaskRowItem({
selectedTaskId,
showActivityTime,
showRepository,
taskRowPresentation,
onSelectTask,
selectedTaskIds,
onToggleSelectTask,
@@ -172,6 +176,7 @@ function TaskRowItem({
showActivityTime={showActivityTime}
repositoryPath={task.repositoryPath}
showRepository={showRepository}
taskRowPresentation={taskRowPresentation}
prInfo={task.prInfo}
queuedCount={task.queuedCount}
wipQueue={task.wipQueue}
@@ -2,6 +2,7 @@ import type { ForegroundActivity, TaskSessionState, TaskState } from "@/lib/type
import type { GroupedSidebarList } from "@/lib/sidebar/apply-view";
import type { TaskMoveWorkflow } from "@/components/task/task-move-context-menu";
import type { WipQueueStatus } from "@/lib/kanban/wip-queue";
import type { SidebarTaskRowPresentation } from "@/lib/state/slices/ui/sidebar-task-row-presentation";
export type StepDef = {
id: string;
@@ -96,6 +97,7 @@ export type TaskSwitcherProps = {
retryLabel?: string;
totalTaskCount?: number;
showActivityTime?: boolean;
taskRowPresentation?: SidebarTaskRowPresentation;
// Multi-select (cmd/shift click). When the selection is non-empty, plain
// clicks toggle instead of navigating; the context menu acts on the selection.
selectedTaskIds?: Set<string>;
@@ -30,6 +30,7 @@ function buildTaskRowProps(props: TaskSwitcherProps): TaskRowBaseProps {
activeTaskId: props.activeTaskId,
selectedTaskId: props.selectedTaskId,
showActivityTime: props.showActivityTime,
taskRowPresentation: props.taskRowPresentation,
showRepository: shouldShowRowRepository(props.grouped),
onSelectTask: props.onSelectTask,
onEditTask: props.onEditTask,
@@ -6,6 +6,7 @@ import { Popover, PopoverAnchor, PopoverContent } from "@kandev/ui/popover";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { useTaskSubtasks, type TaskSubtask } from "@/hooks/domains/kanban/use-task-subtasks";
import { useHoverPopover } from "@/components/integrations/use-hover-popover";
import { cn } from "@/lib/utils";
import { TaskSubtaskRow } from "./task-subtask-row";
const MAX_VISIBLE_SUBTASKS = 12;
@@ -47,12 +48,14 @@ function DesktopTaskTitlePreview({
subtasks,
side,
align,
triggerClassName,
}: {
title: string;
children: ReactNode;
subtasks: TaskSubtask[];
side: "top" | "right" | "bottom" | "left";
align: "start" | "center" | "end";
triggerClassName?: string;
}) {
const triggerRef = useRef<HTMLButtonElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
@@ -92,7 +95,10 @@ function DesktopTaskTitlePreview({
event.stopPropagation();
}}
onClick={handleTriggerClick}
className="min-w-0 max-w-full cursor-pointer text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
className={cn(
"min-w-0 max-w-full cursor-pointer text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
triggerClassName,
)}
>
{children}
</button>
@@ -143,12 +149,14 @@ export function TaskTitleHoverCard({
children,
side = "bottom",
align = "start",
triggerClassName,
}: {
taskId: string;
title: string;
children: ReactNode;
side?: "top" | "right" | "bottom" | "left";
align?: "start" | "center" | "end";
triggerClassName?: string;
}) {
const { isFinePointer } = useResponsiveBreakpoint();
const subtasks = useTaskSubtasks(taskId);
@@ -156,7 +164,13 @@ export function TaskTitleHoverCard({
if (!isFinePointer || subtasks.length === 0) return <>{children}</>;
return (
<DesktopTaskTitlePreview title={title} subtasks={subtasks} side={side} align={align}>
<DesktopTaskTitlePreview
title={title}
subtasks={subtasks}
side={side}
align={align}
triggerClassName={triggerClassName}
>
{children}
</DesktopTaskTitlePreview>
);
@@ -183,6 +183,35 @@ export class SidebarFilterPopoverPage {
await this.page.getByRole("option", { name: groupLabel, exact: true }).click();
}
get taskRowSettings(): Locator {
return this.popover.getByTestId("task-row-settings");
}
async openTaskRowSettings(): Promise<void> {
const toggle = this.taskRowSettings.getByTestId("task-row-settings-toggle");
if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
await expect(this.taskRowSettings.getByTestId("task-row-details-toggle")).toBeVisible();
}
async setTaskRowTrailing(label: string): Promise<void> {
await this.taskRowSettings.getByTestId("task-row-trailing-select").click();
await this.page.getByRole("option", { name: label, exact: true }).click();
}
async toggleTaskRowDetail(detail: string): Promise<void> {
await this.taskRowSettings.getByTestId(`task-row-detail-toggle-${detail}`).click();
}
async taskRowDetailOrder(): Promise<string[]> {
return this.taskRowSettings
.locator("div[data-testid^='task-row-detail-']")
.evaluateAll((rows) =>
rows
.map((row) => row.getAttribute("data-testid")?.replace("task-row-detail-", ""))
.filter((value): value is string => !!value),
);
}
async saveAs(name: string): Promise<void> {
await this.popover.getByTestId("view-save-as-button").click();
await this.popover.getByTestId("view-save-as-name-input").fill(name);
@@ -368,6 +368,19 @@ test.describe("PR status badge", () => {
seedData.repositoryId,
taskTitle,
);
const settings = await apiClient.getUserSettings();
const sidebarViews = settings.settings.sidebar_views as Array<Record<string, unknown>>;
await apiClient.saveUserSettings({
sidebar_views: sidebarViews.map((view) => ({
...view,
task_row: {
details_enabled: true,
detail_order: ["relative_time", "repository", "pull_request_number"],
visible_details: ["relative_time", "repository", "pull_request_number"],
trailing: "change_request_status",
},
})),
});
const kanban = new KanbanPage(testPage);
await kanban.goto();
@@ -395,6 +408,8 @@ test.describe("PR status badge", () => {
const taskRow = testPage.getByTestId("sidebar-task-item").filter({ hasText: taskTitle });
await expect(taskRow).toBeVisible({ timeout: 15_000 });
const trailingStatus = taskRow.getByTestId("sidebar-task-change-request-status");
await expect(trailingStatus).toBeVisible();
const icon = taskRow.getByTestId(`pr-task-icon-${task.id}`);
await expect(icon).toHaveAttribute("data-pr-ready-to-merge", "true");
await icon.hover();
@@ -12,6 +12,7 @@
import { test, expect, type SeedData } from "../../fixtures/test-base";
import type { Page, Locator } from "@playwright/test";
import type { ApiClient } from "../../helpers/api-client";
import { dwell } from "../../helpers/causal-waits";
import { SessionPage } from "../../pages/session-page";
async function seedAndOpenSheet(
@@ -65,6 +66,43 @@ async function taskRowOrder(sheet: Locator, taskIds: string[]) {
return order;
}
async function touchDrag(page: Page, source: Locator, target: Locator): Promise<void> {
const sourceBox = await source.boundingBox();
const targetBox = await target.boundingBox();
expect(sourceBox).not.toBeNull();
expect(targetBox).not.toBeNull();
const client = await page.context().newCDPSession(page);
const start = {
x: sourceBox!.x + sourceBox!.width / 2,
y: sourceBox!.y + sourceBox!.height / 2,
};
const end = {
x: targetBox!.x + targetBox!.width / 2,
y: targetBox!.y + targetBox!.height / 2,
};
await client.send("Input.dispatchTouchEvent", {
type: "touchStart",
touchPoints: [{ id: 1, x: start.x, y: start.y }],
});
await dwell(300, "library-timer", "dnd-kit TouchSensor waits 250ms before activating");
for (let step = 1; step <= 12; step += 1) {
const progress = step / 12;
await client.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [
{
id: 1,
x: start.x + (end.x - start.x) * progress,
y: start.y + (end.y - start.y) * progress,
},
],
});
}
await client.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await client.detach();
}
test.describe("Mobile sidebar — view system", () => {
test("direct creation stays touch-reachable, viewport-safe, and persists", async ({
testPage,
@@ -150,6 +188,7 @@ test.describe("Mobile sidebar — view system", () => {
await expect(sheet.getByText("Update deps")).toBeVisible();
await addTitleFilter(testPage, sheet, "auth");
const filterEditor = testPage.getByTestId("sidebar-filter-popover");
// Draft is active — the gear shows its unsaved indicator. Scope to the sheet:
// the globally-mounted (hidden on mobile) AppSidebar TasksViewPicker renders
// the same testid, so a page-level query is a strict-mode collision.
@@ -157,6 +196,10 @@ test.describe("Mobile sidebar — view system", () => {
const blockedNewView = sheet.getByTestId("sidebar-new-view");
await expect(blockedNewView).toHaveAttribute("aria-disabled", "true");
await expect(blockedNewView).toHaveAttribute("aria-label", /save or discard changes/i);
// The filter editor is a modal drawer on coarse pointers. Close it before
// invoking the fixed-bar action underneath it.
await testPage.keyboard.press("Escape");
await expect(filterEditor).toBeHidden();
// aria-disabled communicates the blocked state, but this action remains
// clickable so touch/keyboard users can get the concrete reason toast.
await blockedNewView.click({ force: true });
@@ -348,6 +391,202 @@ test.describe("Mobile sidebar — view system", () => {
await expect.poll(() => taskRowOrder(reloadedSheet, taskIds)).toEqual(taskIds);
});
test("keeps mobile section labels clear of separator lines", async ({
testPage,
apiClient,
seedData,
}) => {
const sheet = await seedAndOpenSheet(testPage, apiClient, seedData, [
"Mobile separator spacing",
]);
await sheet.getByTestId("sidebar-filter-gear").click();
const popover = testPage.getByTestId("sidebar-filter-popover");
await expect(popover).toBeVisible();
for (const { label, sectionLevel } of [
{ label: "Filters", sectionLevel: 2 },
{ label: "Sort", sectionLevel: 1 },
{ label: "Group by", sectionLevel: 1 },
]) {
const heading = popover.getByText(label, { exact: true });
const section =
sectionLevel === 2 ? heading.locator("..").locator("..") : heading.locator("..");
const [headingBox, sectionBox] = await Promise.all([
heading.boundingBox(),
section.boundingBox(),
]);
expect(headingBox).not.toBeNull();
expect(sectionBox).not.toBeNull();
expect(headingBox!.y).toBeGreaterThan(sectionBox!.y + 3);
}
});
test("keeps mobile section separators inside the drawer surface", async ({
testPage,
apiClient,
seedData,
}) => {
const sheet = await seedAndOpenSheet(testPage, apiClient, seedData, [
"Mobile separator containment",
]);
await sheet.getByTestId("sidebar-filter-gear").tap();
const drawer = testPage.getByTestId("sidebar-filter-drawer");
const popover = testPage.getByTestId("sidebar-filter-popover");
await expect(drawer).toBeVisible();
await expect(popover).toBeVisible();
const [drawerBox, popoverBox] = await Promise.all([
drawer.boundingBox(),
popover.boundingBox(),
]);
expect(drawerBox).not.toBeNull();
expect(popoverBox).not.toBeNull();
expect(popoverBox!.x).toBeGreaterThan(drawerBox!.x);
expect(popoverBox!.x + popoverBox!.width).toBeLessThan(drawerBox!.x + drawerBox!.width);
});
test("task row settings use the drawer, touch targets, and persisted preview", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
const taskTitle = "Mobile task row layout";
const sheet = await seedAndOpenSheet(testPage, apiClient, seedData, [taskTitle]);
const gear = sheet.getByTestId("sidebar-filter-gear");
await gear.tap();
const drawer = testPage.getByTestId("sidebar-filter-drawer");
const popover = testPage.getByTestId("sidebar-filter-popover");
await expect(drawer).toBeVisible();
await expect(popover).toBeVisible();
await popover.getByTestId("group-key-select").tap();
for (const { label, description } of [
{ label: "None", description: "Keep all tasks in one list." },
{ label: "Repository", description: "Separate tasks by repository." },
{ label: "Workflow", description: "Separate tasks by workflow." },
{ label: "Workflow step", description: "Separate tasks by workflow step." },
{ label: "Executor type", description: "Separate tasks by executor type." },
{ label: "State", description: "Separate tasks by state." },
]) {
const option = testPage.getByRole("option", { name: label, exact: true });
const descriptionId = await option.getAttribute("aria-describedby");
expect(descriptionId).toBeTruthy();
await expect(testPage.locator(`[id="${descriptionId}"]`)).toHaveText(description);
}
await testPage.getByRole("option", { name: "Repository", exact: true }).tap();
const settings = popover.getByTestId("task-row-settings");
await expect(settings.getByTestId("task-row-details-toggle")).toHaveCount(0);
await settings.getByTestId("task-row-settings-toggle").tap();
await expect(settings.getByTestId("task-row-details-toggle")).toBeVisible();
await settings.getByTestId("task-row-trailing-select").tap();
for (const { label, description } of [
{ label: "Git changes", description: "Show added and removed lines." },
{ label: "Relative time", description: "Show when the task was last updated." },
{
label: "Change request status",
description: "Show the pull request or merge request status.",
},
{ label: "Nothing", description: "Leave the right side empty." },
]) {
const option = testPage.getByRole("option", { name: label, exact: true });
const descriptionId = await option.getAttribute("aria-describedby");
expect(descriptionId).toBeTruthy();
await expect(testPage.locator(`[id="${descriptionId}"]`)).toHaveText(description);
}
await testPage.getByRole("option", { name: "Git changes", exact: true }).tap();
for (const control of [
"task-row-details-toggle",
"task-row-detail-handle-relative_time",
"task-row-detail-toggle-relative_time",
]) {
const box = await settings.getByTestId(control).boundingBox();
expect(box?.height).toBeGreaterThanOrEqual(40);
expect(box?.width).toBeGreaterThanOrEqual(40);
}
const trailingSelectBox = await settings.getByTestId("task-row-trailing-select").boundingBox();
expect(trailingSelectBox).not.toBeNull();
expect(trailingSelectBox!.height).toBeGreaterThanOrEqual(44);
const pullRequestHandle = settings.getByTestId("task-row-detail-handle-pull_request_number");
const relativeTimeHandle = settings.getByTestId("task-row-detail-handle-relative_time");
await touchDrag(testPage, pullRequestHandle, relativeTimeHandle);
await expect
.poll(async () =>
settings
.locator("div[data-testid^='task-row-detail-']")
.evaluateAll((rows) =>
rows.map((row) => row.getAttribute("data-testid")?.replace("task-row-detail-", "")),
),
)
.toEqual(["pull_request_number", "relative_time", "repository"]);
await settings.getByTestId("task-row-detail-toggle-repository").tap();
await settings.getByTestId("task-row-details-toggle").tap();
const compactRow = sheet.getByTestId("sidebar-task-item").filter({ hasText: taskTitle });
const compactRowBox = await compactRow.boundingBox();
const compactTitleBox = await compactRow
.getByText(taskTitle, { exact: true })
.first()
.boundingBox();
expect(compactRowBox).not.toBeNull();
expect(compactTitleBox).not.toBeNull();
expect(
Math.abs(
compactTitleBox!.y +
compactTitleBox!.height / 2 -
(compactRowBox!.y + compactRowBox!.height / 2),
),
).toBeLessThanOrEqual(1);
await settings.getByTestId("task-row-trailing-select").tap();
await testPage.getByRole("option", { name: "Relative time", exact: true }).tap();
await popover.getByTestId("view-save-as-button").tap();
await popover.getByTestId("view-save-as-name-input").fill("Mobile task rows");
await popover.getByTestId("view-save-as-confirm").tap();
const row = compactRow;
await expect(row).toBeVisible();
await expect(row.getByTestId("sidebar-task-trailing-time")).toBeVisible();
await expect(row.getByTestId("sidebar-task-time")).toHaveCount(0);
await prCapture.screenshot("mobile-task-row-settings", {
caption: "Mobile task-row settings in the inset bottom drawer",
});
await expect(popover).toHaveCSS("overflow-y", "auto");
const drawerBox = await drawer.boundingBox();
const viewport = testPage.viewportSize();
expect(drawerBox).not.toBeNull();
expect(viewport).not.toBeNull();
expect(drawerBox!.x).toBeGreaterThanOrEqual(0);
expect(drawerBox!.x + drawerBox!.width).toBeLessThanOrEqual(viewport!.width);
expect(
await testPage.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
),
).toBe(true);
await testPage.keyboard.press("Escape");
await expect(popover).toBeHidden();
await testPage.reload();
await new SessionPage(testPage).waitForLoad();
await testPage.getByTestId("mobile-session-menu").tap();
const reloadedSheet = testPage.getByRole("dialog", { name: "Tasks" });
await expect(
reloadedSheet.getByTestId("sidebar-view-chip").filter({ hasText: "Mobile task rows" }),
).toHaveAttribute("data-active", "true");
await reloadedSheet.getByTestId("sidebar-filter-gear").tap();
const reloadedPopover = testPage.getByTestId("sidebar-filter-popover");
await expect(reloadedPopover.getByTestId("task-row-details-toggle")).toHaveCount(0);
await reloadedPopover.getByTestId("task-row-settings-toggle").tap();
await expect(reloadedPopover.getByTestId("task-row-trailing-select")).toContainText(
"Relative time",
);
await testPage.keyboard.press("Escape");
});
test("many saved views scroll without covering fixed actions", async ({
testPage,
apiClient,
+159 -1
View File
@@ -302,7 +302,21 @@ test.describe("Sidebar filter — group + sort", () => {
test("Group by none hides group headers", async ({ testPage, apiClient, seedData }) => {
const { session, filters } = await openWithSeed(testPage, apiClient, seedData, ["One", "Two"]);
await filters.open();
await filters.setGroup("None");
await filters.popover.getByTestId("group-key-select").click();
for (const { label, description } of [
{ label: "None", description: "Keep all tasks in one list." },
{ label: "Repository", description: "Separate tasks by repository." },
{ label: "Workflow", description: "Separate tasks by workflow." },
{ label: "Workflow step", description: "Separate tasks by workflow step." },
{ label: "Executor type", description: "Separate tasks by executor type." },
{ label: "State", description: "Separate tasks by state." },
]) {
const option = testPage.getByRole("option", { name: label, exact: true });
const descriptionId = await option.getAttribute("aria-describedby");
expect(descriptionId).toBeTruthy();
await expect(testPage.locator(`[id="${descriptionId}"]`)).toHaveText(description);
}
await testPage.getByRole("option", { name: "None", exact: true }).click();
await filters.close();
await expect(session.sidebar.locator("[data-testid='sidebar-group-header']")).toHaveCount(0);
});
@@ -699,6 +713,150 @@ test.describe("Sidebar filter — repository dimension (#1213)", () => {
});
});
test.describe("Sidebar filter — task-row presentation", () => {
test("previews, saves, discards, and reloads an independent task row layout", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
const taskTitle = "Desktop task row layout";
const { session, filters } = await openWithSeed(testPage, apiClient, seedData, [taskTitle]);
const row = session.sidebar.getByTestId("sidebar-task-item").filter({ hasText: taskTitle });
await expect(row).toBeVisible();
await expect(row.getByTestId("sidebar-task-time")).toBeVisible();
await filters.open();
await expect(filters.taskRowSettings.getByTestId("task-row-settings-toggle")).toBeVisible();
await expect(filters.taskRowSettings.getByTestId("task-row-details-toggle")).toHaveCount(0);
await expect(filters.popover.getByTestId("sidebar-filter-dirty-indicator")).toHaveCount(0);
await filters.openTaskRowSettings();
await expect(filters.popover.getByTestId("sidebar-filter-dirty-indicator")).toHaveCount(0);
await filters.taskRowSettings.getByTestId("task-row-trailing-select").click();
for (const { label, description } of [
{ label: "Git changes", description: "Show added and removed lines." },
{ label: "Relative time", description: "Show when the task was last updated." },
{
label: "Change request status",
description: "Show the pull request or merge request status.",
},
{ label: "Nothing", description: "Leave the right side empty." },
]) {
const option = testPage.getByRole("option", { name: label, exact: true });
const descriptionId = await option.getAttribute("aria-describedby");
expect(descriptionId).toBeTruthy();
await expect(testPage.locator(`[id="${descriptionId}"]`)).toHaveText(description);
}
await testPage.keyboard.press("Escape");
await prCapture.screenshot("desktop-task-row-settings", {
caption: "Desktop task-row presentation settings with the section expanded",
});
const pullRequestHandle = filters.taskRowSettings.getByTestId(
"task-row-detail-handle-pull_request_number",
);
const relativeTimeHandle = filters.taskRowSettings.getByTestId(
"task-row-detail-handle-relative_time",
);
const sourceBox = await pullRequestHandle.boundingBox();
const targetBox = await relativeTimeHandle.boundingBox();
expect(sourceBox).not.toBeNull();
expect(targetBox).not.toBeNull();
await testPage.mouse.move(
sourceBox!.x + sourceBox!.width / 2,
sourceBox!.y + sourceBox!.height / 2,
);
await testPage.mouse.down();
await testPage.mouse.move(
sourceBox!.x + sourceBox!.width / 2,
sourceBox!.y + sourceBox!.height / 2 + 12,
{ steps: 4 },
);
await testPage.mouse.move(targetBox!.x + targetBox!.width / 2, targetBox!.y + 2, {
steps: 16,
});
await testPage.mouse.up();
await expect
.poll(() => filters.taskRowDetailOrder())
.toEqual(["pull_request_number", "relative_time", "repository"]);
await filters.toggleTaskRowDetail("repository");
await expect(row.getByTestId("sidebar-task-repository")).toHaveCount(0);
const detailsToggle = filters.taskRowSettings.getByTestId("task-row-details-toggle");
await detailsToggle.click();
await expect(row.getByTestId("sidebar-task-time")).toHaveCount(0);
await expect(row.getByText(taskTitle, { exact: true })).toBeVisible();
const compactRowBox = await row.boundingBox();
const compactTitleBox = await row.getByText(taskTitle, { exact: true }).first().boundingBox();
expect(compactRowBox).not.toBeNull();
expect(compactTitleBox).not.toBeNull();
expect(
Math.abs(
compactTitleBox!.y +
compactTitleBox!.height / 2 -
(compactRowBox!.y + compactRowBox!.height / 2),
),
).toBeLessThanOrEqual(1);
await filters.saveAs("Compact task rows");
await filters.expectActiveViewChip("Compact task rows");
const savedSettings = await apiClient.getUserSettings();
const savedViews = savedSettings.settings.sidebar_views as Array<{
name?: string;
task_row?: { details_enabled?: boolean };
}>;
expect(savedViews.find((view) => view.name === "Compact task rows")?.task_row).toMatchObject({
details_enabled: false,
});
await filters.setTaskRowTrailing("Relative time");
await filters.saveOverwrite();
await expect(row.getByTestId("sidebar-task-trailing-time")).toBeVisible();
await filters.openTaskRowSettings();
await detailsToggle.click();
await expect(filters.popover.getByTestId("sidebar-filter-dirty-indicator")).toBeVisible();
await filters.discard();
await expect(row.getByTestId("sidebar-task-time")).toHaveCount(0);
await expect(row.getByTestId("sidebar-task-trailing-time")).toBeVisible();
await filters.close();
await filters.selectViewByName("All tasks");
await expect(
session.sidebar.getByTestId("sidebar-task-item").filter({ hasText: taskTitle }),
).toBeVisible();
await expect(
session.sidebar
.getByTestId("sidebar-task-item")
.filter({ hasText: taskTitle })
.getByTestId("sidebar-task-time"),
).toBeVisible();
await filters.selectViewByName("Compact task rows");
await expect
.poll(async () => {
const compactRow = session.sidebar
.getByTestId("sidebar-task-item")
.filter({ hasText: taskTitle });
return (await compactRow.getByTestId("sidebar-task-trailing-time").count()) === 1;
})
.toBe(true);
await testPage.reload();
await new SessionPage(testPage).waitForLoad();
const reloadedFilters = new SidebarFilterPopoverPage(testPage);
await reloadedFilters.expectActiveViewChip("Compact task rows");
const reloadedRow = testPage.getByTestId("sidebar-task-item").filter({ hasText: taskTitle });
await expect(reloadedRow.getByTestId("sidebar-task-time")).toHaveCount(0);
await expect(reloadedRow.getByTestId("sidebar-task-trailing-time")).toBeVisible();
await expect(
await testPage.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth,
),
).toBe(true);
});
});
test.describe("Sidebar filter — draft semantics", () => {
test("dirty indicator appears after edits, clears on discard", async ({
testPage,
@@ -1,5 +1,6 @@
import { useMemo } from "react";
import { useAppStore } from "@/components/state-provider";
import { cloneSidebarTaskRowPresentation } from "@/lib/state/slices/ui/sidebar-task-row-presentation";
/**
* Active sidebar view merged with any in-flight draft. Used by both desktop
@@ -13,6 +14,12 @@ export function useEffectiveSidebarView() {
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 };
return {
...active,
filters: d.filters,
sort: d.sort,
group: d.group,
taskRow: cloneSidebarTaskRowPresentation(d.taskRow ?? active.taskRow),
};
}, [sidebarSlice.views, sidebarSlice.activeViewId, sidebarSlice.draft]);
}
+6
View File
@@ -426,6 +426,12 @@ describe("mapUserSettingsResponse", () => {
filters: [],
sort: { key: "updatedAt", direction: "desc" },
group: "workflow",
taskRow: {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
},
});
});
});
@@ -9,6 +9,12 @@ import type { AppState } from "@/lib/state/store";
import type { MCPAttachmentHistory } from "@/lib/state/slices/session-runtime/types";
const TERMINAL_TAB_ID = "terminal-1";
const DEFAULT_TASK_ROW = {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
};
/** Builds an AppState draft carrying only the default UI slice for hydrateUI tests. */
function makeDraft(): AppState {
@@ -449,6 +455,7 @@ describe("hydrateState — sidebar views from user settings", () => {
filters: [],
sort: { key: "updatedAt", direction: "desc" },
group: "workflow",
taskRow: DEFAULT_TASK_ROW,
});
});
@@ -0,0 +1,90 @@
export const SIDEBAR_TASK_ROW_DETAIL_KEYS = [
"relative_time",
"repository",
"pull_request_number",
] as const;
export type SidebarTaskRowDetail = (typeof SIDEBAR_TASK_ROW_DETAIL_KEYS)[number];
export const SIDEBAR_TASK_ROW_TRAILING_KEYS = [
"git_changes",
"relative_time",
"change_request_status",
"none",
] as const;
export type SidebarTaskRowTrailing = (typeof SIDEBAR_TASK_ROW_TRAILING_KEYS)[number];
export type SidebarTaskRowPresentation = {
detailsEnabled: boolean;
detailOrder: SidebarTaskRowDetail[];
visibleDetails: SidebarTaskRowDetail[];
trailing: SidebarTaskRowTrailing;
};
export const DEFAULT_SIDEBAR_TASK_ROW_PRESENTATION: SidebarTaskRowPresentation = {
detailsEnabled: true,
detailOrder: [...SIDEBAR_TASK_ROW_DETAIL_KEYS],
visibleDetails: [...SIDEBAR_TASK_ROW_DETAIL_KEYS],
trailing: "git_changes",
};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isDetail(value: unknown): value is SidebarTaskRowDetail {
return (
typeof value === "string" && (SIDEBAR_TASK_ROW_DETAIL_KEYS as readonly string[]).includes(value)
);
}
function isTrailing(value: unknown): value is SidebarTaskRowTrailing {
return (
typeof value === "string" &&
(SIDEBAR_TASK_ROW_TRAILING_KEYS as readonly string[]).includes(value)
);
}
function normalizeDetails(value: unknown, fallback: readonly SidebarTaskRowDetail[]) {
if (!Array.isArray(value)) return [...fallback];
const seen = new Set<SidebarTaskRowDetail>();
const normalized = value.filter(isDetail).filter((detail) => {
if (seen.has(detail)) return false;
seen.add(detail);
return true;
});
return normalized;
}
/** Normalizes persisted or boot-provided task-row data without mutating it. */
export function normalizeSidebarTaskRowPresentation(value: unknown): SidebarTaskRowPresentation {
const input = isRecord(value) ? value : {};
const detailOrder = normalizeDetails(input.detailOrder, SIDEBAR_TASK_ROW_DETAIL_KEYS);
for (const detail of SIDEBAR_TASK_ROW_DETAIL_KEYS) {
if (!detailOrder.includes(detail)) detailOrder.push(detail);
}
const visibleDetails = Array.isArray(input.visibleDetails)
? normalizeDetails(input.visibleDetails, [])
: [...SIDEBAR_TASK_ROW_DETAIL_KEYS];
return {
detailsEnabled: typeof input.detailsEnabled === "boolean" ? input.detailsEnabled : true,
detailOrder,
visibleDetails,
trailing: isTrailing(input.trailing) ? input.trailing : "git_changes",
};
}
export function cloneSidebarTaskRowPresentation(
value: SidebarTaskRowPresentation | undefined,
): SidebarTaskRowPresentation {
const normalized = normalizeSidebarTaskRowPresentation(value);
return {
detailsEnabled: normalized.detailsEnabled,
detailOrder: [...normalized.detailOrder],
visibleDetails: [...normalized.visibleDetails],
trailing: normalized.trailing,
};
}
@@ -17,6 +17,19 @@ type UIStore = UseBoundStore<StoreApi<UISlice>>;
const CREATE_FAILED = "create failed";
const RENAME_FAILED = "rename failed";
const DRAFT_WRITE_FAILED = "draft write failed";
type SettingsResponse = Awaited<ReturnType<typeof updateUserSettings>>;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});
return { promise, resolve, reject };
}
function makeStore(): UIStore {
return create<UISlice>()(
@@ -87,6 +100,12 @@ describe("createSidebarView semantics", () => {
sort: { key: "state", direction: "asc" },
group: "repository",
collapsedGroups: [],
taskRow: {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
},
});
expect(sidebar.activeViewId).toBe(createdId);
expect(sidebar.draft).toBeNull();
@@ -243,3 +262,81 @@ describe("createSidebarView failure isolation", () => {
expect(successfulStore.getState().sidebarViews.views).toHaveLength(2);
});
});
describe("sidebar draft write failure isolation", () => {
it("restores the confirmed draft after a task-row write fails", async () => {
const store = makeStore();
seedSidebar(store, [makeView("all", "All tasks")]);
vi.mocked(updateUserSettings).mockRejectedValueOnce(new ApiError(DRAFT_WRITE_FAILED, 500, {}));
store.getState().updateSidebarDraft({
taskRow: {
detailsEnabled: false,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: [],
trailing: "none",
},
});
expect(store.getState().sidebarViews.draft).not.toBeNull();
await waitFor(() => expect(store.getState().sidebarViews.syncError).toBe(DRAFT_WRITE_FAILED));
expect(store.getState().sidebarViews.draft).toBeNull();
});
});
describe("sidebar write ordering", () => {
it("keeps a queued successful save after an earlier draft failure", async () => {
const store = makeStore();
seedSidebar(store, [makeView("all", "All tasks")]);
const draftResponse = deferred<SettingsResponse>();
const saveResponse = deferred<SettingsResponse>();
vi.mocked(updateUserSettings)
.mockImplementationOnce(() => draftResponse.promise)
.mockImplementationOnce(() => saveResponse.promise);
store.getState().updateSidebarDraft({
taskRow: {
detailsEnabled: false,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: [],
trailing: "none",
},
});
store.getState().saveSidebarDraftOverwrite();
expect(updateUserSettings).toHaveBeenCalledTimes(1);
draftResponse.reject(new ApiError(DRAFT_WRITE_FAILED, 500, {}));
await waitFor(() => expect(updateUserSettings).toHaveBeenCalledTimes(2));
saveResponse.resolve({ settings: {} } as SettingsResponse);
await waitFor(() => {
expect(store.getState().sidebarViews.draft).toBeNull();
expect(store.getState().sidebarViews.views[0]?.taskRow?.detailsEnabled).toBe(false);
});
});
it("does not resurrect a failed create when its queued draft also fails", async () => {
const store = makeStore();
const original = makeView("all", "All tasks");
seedSidebar(store, [original]);
const createResponse = deferred<SettingsResponse>();
const draftResponse = deferred<SettingsResponse>();
vi.mocked(updateUserSettings)
.mockImplementationOnce(() => createResponse.promise)
.mockImplementationOnce(() => draftResponse.promise);
const createdId = store.getState().createSidebarView();
expect(createdId).not.toBeNull();
store.getState().updateSidebarDraft({ group: "state" });
createResponse.reject(new ApiError(CREATE_FAILED, 500, {}));
await waitFor(() => expect(updateUserSettings).toHaveBeenCalledTimes(2));
draftResponse.reject(new ApiError(DRAFT_WRITE_FAILED, 500, {}));
await waitFor(() => {
expect(store.getState().sidebarViews.views).toEqual([original]);
expect(store.getState().sidebarViews.activeViewId).toBe(original.id);
expect(store.getState().sidebarViews.draft).toBeNull();
});
});
});
@@ -8,6 +8,7 @@ import type {
SidebarViewDraft,
SortSpec,
} from "./sidebar-view-types";
import { cloneSidebarTaskRowPresentation } from "./sidebar-task-row-presentation";
import { toApiSidebarDraft, toApiSidebarView } from "./sidebar-view-wire";
import { createDefaultSidebarView, MAX_SIDEBAR_VIEWS } from "./sidebar-view-builtins";
import { t } from "@/lib/i18n";
@@ -50,18 +51,21 @@ type SidebarSnapshot = {
draft: SidebarViewDraft | null;
};
type ViewMutationSyncState = {
type SidebarWriteJournal = {
latestRequestId: number;
failedRollback?: SidebarSnapshot;
failedWriteKind?: SidebarWriteKind;
};
const viewMutationSyncStates = new WeakMap<ImmerSet, ViewMutationSyncState>();
type SidebarWriteKind = "views" | "local";
function getViewMutationSyncState(set: ImmerSet): ViewMutationSyncState {
const existing = viewMutationSyncStates.get(set);
const sidebarWriteJournals = new WeakMap<ImmerSet, SidebarWriteJournal>();
function getSidebarWriteJournal(set: ImmerSet): SidebarWriteJournal {
const existing = sidebarWriteJournals.get(set);
if (existing) return existing;
const created = { latestRequestId: 0 };
viewMutationSyncStates.set(set, created);
sidebarWriteJournals.set(set, created);
return created;
}
@@ -69,7 +73,7 @@ function snapshotSidebar(s: UISliceState["sidebarViews"]): SidebarSnapshot {
return {
views: s.views.map(cloneView),
activeViewId: s.activeViewId,
draft: s.draft ? { ...s.draft } : null,
draft: cloneDraft(s.draft),
};
}
@@ -81,6 +85,46 @@ function toSidebarSettingsPayload(s: SidebarSnapshot | UISliceState["sidebarView
};
}
function rollbackSidebarState(
set: ImmerSet,
rollback: SidebarSnapshot,
after: SidebarSnapshot,
error?: unknown,
): void {
set((draft) => {
draft.sidebarViews.views = rollback.views;
const activeViewStillExists = rollback.views.some(
(view) => view.id === draft.sidebarViews.activeViewId,
);
if (draft.sidebarViews.activeViewId === after.activeViewId || !activeViewStillExists) {
draft.sidebarViews.activeViewId = rollback.activeViewId;
}
const currentDraft = draft.sidebarViews.draft;
const draftBaseStillExists =
!currentDraft || rollback.views.some((view) => view.id === currentDraft.baseViewId);
if (draftsEqual(currentDraft, after.draft) || !draftBaseStillExists) {
draft.sidebarViews.draft = rollback.draft;
}
if (error !== undefined) {
draft.sidebarViews.syncError =
error instanceof Error ? error.message : t("sidebar:failedToSyncSidebarViews");
}
});
}
function restoreFailedViewMutation(set: ImmerSet, rollback: SidebarSnapshot): void {
set((draft) => {
draft.sidebarViews.views = rollback.views;
if (!rollback.views.some((view) => view.id === draft.sidebarViews.activeViewId)) {
draft.sidebarViews.activeViewId = rollback.activeViewId;
}
const currentDraft = draft.sidebarViews.draft;
if (currentDraft && !rollback.views.some((view) => view.id === currentDraft.baseViewId)) {
draft.sidebarViews.draft = rollback.draft;
}
});
}
function draftsEqual(a: SidebarViewDraft | null, b: SidebarViewDraft | null): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
@@ -100,19 +144,42 @@ function enqueueSidebarSettingsSync(
return request;
}
function syncSidebarViewState(
function syncSidebarWrite(
set: ImmerSet,
payload: {
sidebar_active_view_id: string;
sidebar_draft: ReturnType<typeof toApiSidebarDraft> | null;
},
before: SidebarSnapshot,
after: SidebarSnapshot,
payload: UserSettingsUpdatePayload,
kind: SidebarWriteKind,
) {
enqueueSidebarSettingsSync(set, payload).catch((err) => {
const message = err instanceof Error ? err.message : t("sidebar:failedToSyncSidebarViews");
set((draft) => {
draft.sidebarViews.syncError = message;
});
});
const journal = getSidebarWriteJournal(set);
const thisRequestId = ++journal.latestRequestId;
enqueueSidebarSettingsSync(set, payload).then(
() => {
if (
thisRequestId === journal.latestRequestId &&
journal.failedWriteKind === "views" &&
kind === "local" &&
journal.failedRollback
) {
restoreFailedViewMutation(set, journal.failedRollback);
}
journal.failedRollback = undefined;
journal.failedWriteKind = undefined;
},
(err) => {
const rollback = journal.failedRollback ?? before;
journal.failedRollback = rollback;
journal.failedWriteKind ??= kind;
set((draft) => {
draft.sidebarViews.syncError =
err instanceof Error ? err.message : t("sidebar:failedToSyncSidebarViews");
});
if (thisRequestId !== journal.latestRequestId) return;
rollbackSidebarState(set, rollback, after, err);
journal.failedRollback = undefined;
journal.failedWriteKind = undefined;
},
);
}
function mutateViews(
@@ -128,45 +195,13 @@ function mutateViews(
if (!committed) return;
const after = get().sidebarViews;
const afterSnapshot = snapshotSidebar(after);
const syncState = getViewMutationSyncState(set);
const thisRequestId = ++syncState.latestRequestId;
const request = enqueueSidebarSettingsSync(set, toSidebarSettingsPayload(after));
request.then(
() => {
syncState.failedRollback = undefined;
},
(err) => {
const rollback = syncState.failedRollback ?? snapshot;
syncState.failedRollback = rollback;
if (thisRequestId !== syncState.latestRequestId) return;
const message = err instanceof Error ? err.message : t("sidebar:failedToSyncSidebarViews");
set((draft) => {
draft.sidebarViews.views = rollback.views;
const activeViewStillExists = rollback.views.some(
(view) => view.id === draft.sidebarViews.activeViewId,
);
if (
draft.sidebarViews.activeViewId === afterSnapshot.activeViewId ||
!activeViewStillExists
) {
draft.sidebarViews.activeViewId = rollback.activeViewId;
}
const currentDraft = draft.sidebarViews.draft;
const draftBaseStillExists =
!currentDraft || rollback.views.some((view) => view.id === currentDraft.baseViewId);
if (draftsEqual(currentDraft, afterSnapshot.draft) || !draftBaseStillExists) {
draft.sidebarViews.draft = rollback.draft;
}
draft.sidebarViews.syncError = message;
});
syncState.failedRollback = undefined;
},
);
syncSidebarWrite(set, snapshot, afterSnapshot, toSidebarSettingsPayload(after), "views");
}
function buildSidebarLocalActions(set: ImmerSet, get: () => UISlice) {
return {
setSidebarActiveView: (viewId: string) => {
const before = snapshotSidebar(get().sidebarViews);
let committed = false;
set((draft) => {
if (!draft.sidebarViews.views.some((v) => v.id === viewId)) return;
@@ -175,11 +210,27 @@ function buildSidebarLocalActions(set: ImmerSet, get: () => UISlice) {
draft.sidebarViews.draft = null;
});
if (!committed) return;
syncSidebarViewState(set, { sidebar_active_view_id: viewId, sidebar_draft: null });
const after = snapshotSidebar(get().sidebarViews);
syncSidebarWrite(
set,
before,
after,
{
sidebar_active_view_id: after.activeViewId,
sidebar_draft: after.draft ? toApiSidebarDraft(after.draft) : null,
},
"local",
);
},
updateSidebarDraft: (
patch: Partial<{ filters: FilterClause[]; sort: SortSpec; group: GroupKey }>,
patch: Partial<{
filters: FilterClause[];
sort: SortSpec;
group: GroupKey;
taskRow: SidebarView["taskRow"];
}>,
) => {
const before = snapshotSidebar(get().sidebarViews);
let committed = false;
set((draft) => {
const active = draft.sidebarViews.views.find(
@@ -192,30 +243,46 @@ function buildSidebarLocalActions(set: ImmerSet, get: () => UISlice) {
filters: active.filters,
sort: active.sort,
group: active.group,
taskRow: cloneSidebarTaskRowPresentation(active.taskRow),
};
const next: SidebarViewDraft = {
baseViewId: active.id,
filters: patch.filters ?? current.filters,
sort: patch.sort ?? current.sort,
group: patch.group ?? current.group,
taskRow: cloneSidebarTaskRowPresentation(patch.taskRow ?? current.taskRow),
};
draft.sidebarViews.draft = next;
});
if (!committed) return;
const { activeViewId, draft } = get().sidebarViews;
syncSidebarViewState(set, {
sidebar_active_view_id: activeViewId,
sidebar_draft: draft ? toApiSidebarDraft(draft) : null,
});
const after = snapshotSidebar(get().sidebarViews);
syncSidebarWrite(
set,
before,
after,
{
sidebar_active_view_id: after.activeViewId,
sidebar_draft: after.draft ? toApiSidebarDraft(after.draft) : null,
},
"local",
);
},
discardSidebarDraft: () => {
const before = snapshotSidebar(get().sidebarViews);
set((draft) => {
draft.sidebarViews.draft = null;
});
syncSidebarViewState(set, {
sidebar_active_view_id: get().sidebarViews.activeViewId,
sidebar_draft: null,
});
const after = snapshotSidebar(get().sidebarViews);
syncSidebarWrite(
set,
before,
after,
{
sidebar_active_view_id: after.activeViewId,
sidebar_draft: null,
},
"local",
);
},
clearSidebarSyncError: () =>
set((draft) => {
@@ -257,6 +324,7 @@ function buildSidebarBackendActions(set: ImmerSet, get: () => UISlice) {
sort: s.draft.sort,
group: s.draft.group,
collapsedGroups: [],
taskRow: cloneSidebarTaskRowPresentation(s.draft.taskRow),
});
s.activeViewId = s.views[s.views.length - 1].id;
s.draft = null;
@@ -269,6 +337,7 @@ function buildSidebarBackendActions(set: ImmerSet, get: () => UISlice) {
view.filters = s.draft.filters;
view.sort = s.draft.sort;
view.group = s.draft.group;
view.taskRow = cloneSidebarTaskRowPresentation(s.draft.taskRow);
s.draft = null;
}),
duplicateSidebarView: (viewId: string, name: string) =>
@@ -282,6 +351,7 @@ function buildSidebarBackendActions(set: ImmerSet, get: () => UISlice) {
sort: source.sort,
group: source.group,
collapsedGroups: [],
taskRow: source.taskRow ? cloneSidebarTaskRowPresentation(source.taskRow) : undefined,
});
s.activeViewId = s.views[s.views.length - 1].id;
}),
@@ -325,5 +395,17 @@ function cloneView(v: SidebarView): SidebarView {
sort: { ...v.sort },
group: v.group,
collapsedGroups: [...v.collapsedGroups],
taskRow: v.taskRow ? cloneSidebarTaskRowPresentation(v.taskRow) : undefined,
};
}
function cloneDraft(draft: SidebarViewDraft | null): SidebarViewDraft | null {
if (!draft) return null;
return {
baseViewId: draft.baseViewId,
filters: draft.filters.map((filter) => ({ ...filter })),
sort: { ...draft.sort },
group: draft.group,
taskRow: draft.taskRow ? cloneSidebarTaskRowPresentation(draft.taskRow) : undefined,
};
}
@@ -1,4 +1,5 @@
import type { SidebarView } from "./sidebar-view-types";
import { cloneSidebarTaskRowPresentation } from "./sidebar-task-row-presentation";
export const DEFAULT_VIEW_ID = "view-all-tasks";
export const MAX_SIDEBAR_VIEWS = 50;
@@ -11,6 +12,7 @@ export function createDefaultSidebarView(id: string, name: string): SidebarView
sort: { key: "state", direction: "asc" },
group: "repository",
collapsedGroups: [],
taskRow: cloneSidebarTaskRowPresentation(undefined),
};
}
@@ -1,3 +1,5 @@
import type { SidebarTaskRowPresentation } from "./sidebar-task-row-presentation";
export type FilterDimension =
| "archived"
| "state"
@@ -26,6 +28,8 @@ export type SortKey = "state" | "updatedAt" | "lastActivityAt" | "createdAt" | "
export type SortDirection = "asc" | "desc";
export type SortSpec = { key: SortKey; direction: SortDirection };
export type { SidebarTaskRowPresentation } from "./sidebar-task-row-presentation";
export type GroupKey =
| "none"
| "repository"
@@ -41,6 +45,7 @@ export type SidebarView = {
sort: SortSpec;
group: GroupKey;
collapsedGroups: string[];
taskRow?: SidebarTaskRowPresentation;
};
export type SidebarSliceState = {
@@ -56,4 +61,5 @@ export type SidebarViewDraft = {
filters: FilterClause[];
sort: SortSpec;
group: GroupKey;
taskRow?: SidebarTaskRowPresentation;
};
@@ -1,6 +1,11 @@
import { describe, it, expect } from "vitest";
import type { SidebarView } from "./sidebar-view-types";
import { fromApiSidebarView, toApiSidebarView } from "./sidebar-view-wire";
import type { SidebarView, SidebarViewDraft } from "./sidebar-view-types";
import {
fromApiSidebarDraft,
fromApiSidebarView,
toApiSidebarDraft,
toApiSidebarView,
} from "./sidebar-view-wire";
const view: SidebarView = {
id: "v1",
@@ -13,6 +18,12 @@ const view: SidebarView = {
sort: { key: "lastActivityAt", direction: "desc" },
group: "workflow",
collapsedGroups: ["backlog", "review"],
taskRow: {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
},
};
describe("sidebar view wire", () => {
@@ -43,4 +54,66 @@ describe("sidebar view wire", () => {
expect(api.filters[1].value).toEqual(["review", "in_progress"]);
expect(api.filters[2].value).toBe("fix ");
});
it("round-trips the saved task-row presentation", () => {
const taskRow: NonNullable<SidebarView["taskRow"]> = {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["repository", "pull_request_number"],
trailing: "change_request_status" as const,
};
const viewWithTaskRow: SidebarView = { ...view, taskRow };
const api = toApiSidebarView(viewWithTaskRow);
expect(api.task_row).toEqual({
details_enabled: true,
detail_order: ["relative_time", "repository", "pull_request_number"],
visible_details: ["repository", "pull_request_number"],
trailing: "change_request_status",
});
const restored = fromApiSidebarView(api);
expect(restored.taskRow).toEqual({
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["repository", "pull_request_number"],
trailing: "change_request_status",
});
});
it("round-trips the task-row presentation on a saved-view draft", () => {
const draft: SidebarViewDraft = {
baseViewId: view.id,
filters: view.filters,
sort: view.sort,
group: view.group,
taskRow: {
detailsEnabled: false,
detailOrder: ["pull_request_number", "relative_time", "repository"],
visibleDetails: ["pull_request_number"],
trailing: "none",
},
};
const api = toApiSidebarDraft(draft);
expect(api.task_row?.details_enabled).toBe(false);
expect(fromApiSidebarDraft(api)).toEqual(draft);
});
it("normalizes a missing task-row presentation to the current layout", () => {
const restored = fromApiSidebarView({
id: "v3",
name: "Legacy",
filters: [],
sort: { key: "state", direction: "asc" },
group: "none",
collapsed_groups: [],
});
expect(restored.taskRow).toEqual({
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
});
});
});
@@ -1,5 +1,30 @@
import type { SidebarViewApi, SidebarViewDraftApi } from "@/lib/types/http";
import type { SidebarView, SidebarViewDraft } from "./sidebar-view-types";
import {
cloneSidebarTaskRowPresentation,
normalizeSidebarTaskRowPresentation,
type SidebarTaskRowPresentation,
} from "./sidebar-task-row-presentation";
function toApiTaskRow(value: SidebarTaskRowPresentation | undefined) {
const normalized = cloneSidebarTaskRowPresentation(value);
return {
details_enabled: normalized.detailsEnabled,
detail_order: normalized.detailOrder,
visible_details: normalized.visibleDetails,
trailing: normalized.trailing,
};
}
function fromApiTaskRow(value: SidebarViewApi["task_row"]): SidebarTaskRowPresentation {
if (!value || typeof value !== "object") return normalizeSidebarTaskRowPresentation(undefined);
return normalizeSidebarTaskRowPresentation({
detailsEnabled: value.details_enabled,
detailOrder: value.detail_order,
visibleDetails: value.visible_details,
trailing: value.trailing,
});
}
function toApiClause(c: SidebarView["filters"][number]) {
return {
@@ -27,6 +52,7 @@ export function toApiSidebarView(view: SidebarView): SidebarViewApi {
sort: { key: view.sort.key, direction: view.sort.direction },
group: view.group,
collapsed_groups: view.collapsedGroups,
task_row: toApiTaskRow(view.taskRow),
};
}
@@ -41,6 +67,7 @@ export function fromApiSidebarView(api: SidebarViewApi): SidebarView {
},
group: api.group as SidebarView["group"],
collapsedGroups: api.collapsed_groups ?? [],
taskRow: fromApiTaskRow(api.task_row),
};
}
@@ -50,6 +77,7 @@ export function toApiSidebarDraft(draft: SidebarViewDraft): SidebarViewDraftApi
filters: draft.filters.map(toApiClause),
sort: { key: draft.sort.key, direction: draft.sort.direction },
group: draft.group,
task_row: toApiTaskRow(draft.taskRow),
};
}
@@ -62,5 +90,6 @@ export function fromApiSidebarDraft(api: SidebarViewDraftApi): SidebarViewDraft
direction: api.sort.direction as SidebarView["sort"]["direction"],
},
group: api.group as SidebarView["group"],
taskRow: fromApiTaskRow(api.task_row),
};
}
+7 -1
View File
@@ -5,6 +5,7 @@ import type {
FilterClause,
GroupKey,
SidebarSliceState,
SidebarTaskRowPresentation,
SidebarView,
SidebarViewDraft,
SortSpec,
@@ -385,7 +386,12 @@ export type UISliceActions = {
setSidebarActiveView: (viewId: string) => void;
createSidebarView: () => string | null;
updateSidebarDraft: (
patch: Partial<{ filters: FilterClause[]; sort: SortSpec; group: GroupKey }>,
patch: Partial<{
filters: FilterClause[];
sort: SortSpec;
group: GroupKey;
taskRow: SidebarTaskRowPresentation;
}>,
) => void;
saveSidebarDraftAs: (name: string) => void;
saveSidebarDraftOverwrite: () => void;
@@ -19,6 +19,12 @@ function makeSidebarDraft(baseViewId = "view-a"): SidebarViewDraft {
filters: [],
sort: { key: "state", direction: "asc" },
group: "none",
taskRow: {
detailsEnabled: true,
detailOrder: ["relative_time", "repository", "pull_request_number"],
visibleDetails: ["relative_time", "repository", "pull_request_number"],
trailing: "git_changes",
},
};
}
@@ -682,6 +682,7 @@ describe("sidebar view backend state", () => {
filters: [],
sort: { key: "updatedAt", direction: "desc" },
group: "workflow",
task_row: expect.any(Object),
},
});
});
@@ -717,6 +718,7 @@ describe("sidebar view backend state", () => {
filters: [],
sort: { key: "updatedAt", direction: "desc" },
group: "state",
task_row: expect.any(Object),
},
});
});
+3
View File
@@ -23,6 +23,7 @@ import { buildSidebarTaskPrefsActions } from "./sidebar-task-prefs-actions";
import { buildSidebarViewActions } from "./sidebar-view-actions";
import { DEFAULT_VIEW } from "./sidebar-view-builtins";
import type { SidebarView, SidebarViewDraft, SortSpec } from "./sidebar-view-types";
import { cloneSidebarTaskRowPresentation } from "./sidebar-task-row-presentation";
import type { SystemHealthResponse } from "@/lib/types/health";
import type { ActiveDocument, UISlice, UISliceState } from "./types";
import { buildQuickChatActions } from "./quick-chat-actions";
@@ -69,6 +70,7 @@ export function migrateView(view: SidebarView): SidebarView {
...view,
filters: view.filters.filter((c) => KNOWN_DIMENSIONS.has(c.dimension)),
sort,
taskRow: cloneSidebarTaskRowPresentation(view.taskRow),
};
}
@@ -81,6 +83,7 @@ export function migrateSidebarViewDraft(draft: SidebarViewDraft): SidebarViewDra
...draft,
filters: draft.filters.filter((c) => KNOWN_DIMENSIONS.has(c.dimension)),
sort,
taskRow: cloneSidebarTaskRowPresentation(draft.taskRow),
};
}
+9
View File
@@ -20,6 +20,7 @@ export type SidebarViewApi = {
sort: { key: string; direction: string };
group: string;
collapsed_groups: string[];
task_row?: SidebarTaskRowPresentationApi | null;
};
export type SidebarViewDraftApi = {
@@ -27,6 +28,14 @@ export type SidebarViewDraftApi = {
filters: Array<{ id: string; dimension: string; op: string; value: unknown }>;
sort: { key: string; direction: string };
group: string;
task_row?: SidebarTaskRowPresentationApi | null;
};
export type SidebarTaskRowPresentationApi = {
details_enabled?: boolean;
detail_order?: unknown[];
visible_details?: unknown[];
trailing?: string;
};
export type SidebarTaskPrefsApi = {
+31
View File
@@ -573,16 +573,22 @@
"goToPreviousMessage": "Go to previous message",
"groupBy": "Group by",
"groupExecutorType": "Executor type",
"groupExecutorTypeDescription": "Separate tasks by executor type.",
"groupNone": "None",
"groupNoneDescription": "Keep all tasks in one list.",
"groupRepository": "Repository",
"groupRepositoryDescription": "Separate tasks by repository.",
"groupState": "State",
"groupStateDescription": "Separate tasks by state.",
"groupStatusRateLimited": "Temporarily rate limited",
"groupStatusTimeout": "Search timed out",
"groupStatusUnauthorized": "Sign-in required",
"groupStatusUnsupportedScope": "Unavailable for this workspace",
"groupStatusUpstreamError": "Provider unavailable",
"groupWorkflow": "Workflow",
"groupWorkflowDescription": "Separate tasks by workflow.",
"groupWorkflowStep": "Workflow step",
"groupWorkflowStepDescription": "Separate tasks by workflow step.",
"handOffToTarget": "Hand off to <1>{{label}}</1>",
"handoff": "Handoff",
"hardReset": "Hard Reset",
@@ -1350,6 +1356,31 @@
"showSidebar": "Show sidebar",
"sibling": "Sibling",
"sidebarFilters": "Sidebar filters",
"taskRow": "Task row",
"taskRowChangeRequestStatus": "Change request status",
"taskRowChangeRequestStatusDescription": "Show the pull request or merge request status.",
"taskRowDetails": "Details row",
"taskRowDetailsCount_one": "{{count}} detail",
"taskRowDetailsCount_other": "{{count}} details",
"taskRowDetailsDescription": "Show selected metadata below the task title.",
"taskRowDetailsHidden": "Details hidden",
"taskRowGitChanges": "Git changes",
"taskRowGitChangesDescription": "Show added and removed lines.",
"taskRowNothing": "Nothing",
"taskRowNothingDescription": "Leave the right side empty.",
"taskRowPullRequestNumber": "Pull request number",
"taskRowReorderable": "Reorderable",
"taskRowReorderHandle": "Reorder {{label}}",
"taskRowReordered": "{{label}} moved to position {{position}}",
"taskRowRelativeTime": "Relative time",
"taskRowRelativeTimeDescription": "Show when the task was last updated.",
"taskRowRelativeTimeLastActivity": "Uses the task's last activity time when available.",
"taskRowRelativeTimeLastUpdate": "Uses the task's last update time.",
"taskRowRepository": "Repository",
"taskRowRightSide": "Right side",
"taskRowShownOnRight": "Shown on right",
"taskRowToggleDetail": "{{label}} detail visibility",
"taskRowToggleDetails": "Show task details",
"skipAllQuestions": "Skip all questions",
"skipped": "Skipped",
"snapshotMessageCount_one": "{{count}} message",
+31
View File
@@ -573,16 +573,22 @@
"goToPreviousMessage": "Ĝō ţō ƥŕēvĩōũś ḿēśśàĝē",
"groupBy": "Ĝŕōũƥ ƀŷ",
"groupExecutorType": "Ēxēćũţōŕ ţŷƥē",
"groupExecutorTypeDescription": "Śēƥàŕàţē ţàśķś ƀŷ ēxēćũţōŕ ţŷƥē.",
"groupNone": "Ńōńē",
"groupNoneDescription": "Ķēēƥ àĺĺ ţàśķś ĩń ōńē ĺĩśţ.",
"groupRepository": "Ŕēƥōśĩţōŕŷ",
"groupRepositoryDescription": "Śēƥàŕàţē ţàśķś ƀŷ ŕēƥōśĩţōŕŷ.",
"groupState": "Śţàţē",
"groupStateDescription": "Śēƥàŕàţē ţàśķś ƀŷ śţàţē.",
"groupStatusRateLimited": "Ţēḿƥōŕàŕĩĺŷ ŕàţē ĺĩḿĩţēď",
"groupStatusTimeout": "Śēàŕćĥ ţĩḿēď ōũţ",
"groupStatusUnauthorized": "Śĩĝń-ĩń ŕēqũĩŕēď",
"groupStatusUnsupportedScope": "Ũńàvàĩĺàƀĺē ƒōŕ ţĥĩś ŵōŕķśƥàćē",
"groupStatusUpstreamError": "Ƥŕōvĩďēŕ ũńàvàĩĺàƀĺē",
"groupWorkflow": "Ŵōŕķƒĺōŵ",
"groupWorkflowDescription": "Śēƥàŕàţē ţàśķś ƀŷ ŵōŕķƒĺōŵ.",
"groupWorkflowStep": "Ŵōŕķƒĺōŵ śţēƥ",
"groupWorkflowStepDescription": "Śēƥàŕàţē ţàśķś ƀŷ ŵōŕķƒĺōŵ śţēƥ.",
"handOffToTarget": "Ĥàńď ōƒƒ ţō <1>{{label}}</1>",
"handoff": "Ĥàńďōƒƒ",
"hardReset": "Ĥàŕď Ŕēśēţ",
@@ -1350,6 +1356,31 @@
"showSidebar": "Śĥōŵ śĩďēƀàŕ",
"sibling": "Śĩƀĺĩńĝ",
"sidebarFilters": "Śĩďēƀàŕ ƒĩĺţēŕś",
"taskRow": "Ţàśķ ŕōŵ",
"taskRowChangeRequestStatus": "Ćĥàńĝē ŕēqũēśţ śţàţũś",
"taskRowChangeRequestStatusDescription": "Śĥōŵ ţĥē ƥũĺĺ ŕēqũēśţ ōŕ ḿēŕĝē ŕēqũēśţ śţàţũś.",
"taskRowDetails": "Ďēţàĩĺś ŕōŵ",
"taskRowDetailsCount_one": "{{count}} ďēţàĩĺ",
"taskRowDetailsCount_other": "{{count}} ďēţàĩĺś",
"taskRowDetailsDescription": "Śĥōŵ śēĺēćţēď ḿēţàďàţà ƀēĺōŵ ţĥē ţàśķ ţĩţĺē.",
"taskRowDetailsHidden": "Ďēţàĩĺś ĥĩďďēń",
"taskRowGitChanges": "Ĝĩţ ćĥàńĝēś",
"taskRowGitChangesDescription": "Śĥōŵ àďďēď àńď ŕēḿōvēď ĺĩńēś.",
"taskRowNothing": "Ńōţĥĩńĝ",
"taskRowNothingDescription": "Ĺēàvē ţĥē ŕĩĝĥţ śĩďē ēḿƥţŷ.",
"taskRowPullRequestNumber": "Ƥũĺĺ ŕēqũēśţ ńũḿƀēŕ",
"taskRowReorderable": "Ŕēōŕďēŕàƀĺē",
"taskRowReorderHandle": "Ŕēōŕďēŕ {{label}}",
"taskRowReordered": "{{label}} ḿōvēď ţō ƥōśĩţĩōń {{position}}",
"taskRowRelativeTime": "Ŕēĺàţĩvē ţĩḿē",
"taskRowRelativeTimeDescription": "Śĥōŵ ŵĥēń ţĥē ţàśķ ŵàś ĺàśţ ũƥďàţēď.",
"taskRowRelativeTimeLastActivity": "Ũśēś ţĥē ţàśķ'ś ĺàśţ àćţĩvĩţŷ ţĩḿē ŵĥēń àvàĩĺàƀĺē.",
"taskRowRelativeTimeLastUpdate": "Ũśēś ţĥē ţàśķ'ś ĺàśţ ũƥďàţē ţĩḿē.",
"taskRowRepository": "Ŕēƥōśĩţōŕŷ",
"taskRowRightSide": "Ŕĩĝĥţ śĩďē",
"taskRowShownOnRight": "Śĥōŵń ōń ŕĩĝĥţ",
"taskRowToggleDetail": "{{label}} ďēţàĩĺ vĩśĩƀĩĺĩţŷ",
"taskRowToggleDetails": "Śĥōŵ ţàśķ ďēţàĩĺś",
"skipAllQuestions": "Śķĩƥ àĺĺ qũēśţĩōńś",
"skipped": "Śķĩƥƥēď",
"snapshotMessageCount_one": "{{count}} ḿēśśàĝē",
+31
View File
@@ -558,16 +558,22 @@
"goToPreviousMessage": "Ir para a mensagem anterior",
"groupBy": "Agrupar por",
"groupExecutorType": "Tipo de executor",
"groupExecutorTypeDescription": "Separa as tarefas por tipo de executor.",
"groupNone": "Nenhum",
"groupNoneDescription": "Mantém todas as tarefas numa só lista.",
"groupRepository": "Repositório",
"groupRepositoryDescription": "Separa as tarefas por repositório.",
"groupState": "Estado",
"groupStateDescription": "Separa as tarefas por estado.",
"groupStatusRateLimited": "Temporariamente limitado por taxa",
"groupStatusTimeout": "A pesquisa excedeu o tempo limite",
"groupStatusUnauthorized": "É necessário iniciar sessão",
"groupStatusUnsupportedScope": "Indisponível nesta área de trabalho",
"groupStatusUpstreamError": "Fornecedor indisponível",
"groupWorkflow": "Fluxo de trabalho",
"groupWorkflowDescription": "Separa as tarefas por fluxo de trabalho.",
"groupWorkflowStep": "Passo do fluxo de trabalho",
"groupWorkflowStepDescription": "Separa as tarefas por passo do fluxo de trabalho.",
"handOffToTarget": "Transferir para <1>{{label}}</1>",
"handoff": "Transferir",
"hardReset": "Reposição forçada",
@@ -1305,6 +1311,31 @@
"showSidebar": "Mostrar a barra lateral",
"sibling": "Irmã",
"sidebarFilters": "Filtros da barra lateral",
"taskRow": "Linha da tarefa",
"taskRowChangeRequestStatus": "Estado do pedido de alteração",
"taskRowChangeRequestStatusDescription": "Mostra o estado do pull request ou merge request.",
"taskRowDetails": "Linha de detalhes",
"taskRowDetailsCount_one": "{{count}} detalhe",
"taskRowDetailsCount_other": "{{count}} detalhes",
"taskRowDetailsDescription": "Mostrar os metadados selecionados abaixo do título da tarefa.",
"taskRowDetailsHidden": "Detalhes ocultos",
"taskRowGitChanges": "Alterações do Git",
"taskRowGitChangesDescription": "Mostra as linhas adicionadas e removidas.",
"taskRowNothing": "Nada",
"taskRowNothingDescription": "Deixa o lado direito vazio.",
"taskRowPullRequestNumber": "Número do pull request",
"taskRowReorderable": "Pode ser reordenado",
"taskRowReorderHandle": "Reordenar {{label}}",
"taskRowReordered": "{{label}} movido para a posição {{position}}",
"taskRowRelativeTime": "Tempo relativo",
"taskRowRelativeTimeDescription": "Mostra quando a tarefa foi atualizada pela última vez.",
"taskRowRelativeTimeLastActivity": "Usa a hora da última atividade da tarefa, quando disponível.",
"taskRowRelativeTimeLastUpdate": "Usa a hora da última atualização da tarefa.",
"taskRowRepository": "Repositório",
"taskRowRightSide": "Lado direito",
"taskRowShownOnRight": "Mostrado à direita",
"taskRowToggleDetail": "Visibilidade do detalhe {{label}}",
"taskRowToggleDetails": "Mostrar detalhes da tarefa",
"skipAllQuestions": "Ignorar todas as perguntas",
"skipped": "Ignorada",
"snapshotMessageCount_one": "{{count}} mensagem",
+31
View File
@@ -557,16 +557,22 @@
"goToPreviousMessage": "转到上一条消息",
"groupBy": "分组依据",
"groupExecutorType": "执行器类型",
"groupExecutorTypeDescription": "按执行器类型分开任务。",
"groupNone": "无",
"groupNoneDescription": "将所有任务保留在同一个列表中。",
"groupRepository": "仓库",
"groupRepositoryDescription": "按仓库分开任务。",
"groupState": "状态",
"groupStateDescription": "按状态分开任务。",
"groupStatusRateLimited": "暂时受到速率限制",
"groupStatusTimeout": "搜索超时",
"groupStatusUnauthorized": "需要登录",
"groupStatusUnsupportedScope": "此工作区不可用",
"groupStatusUpstreamError": "提供商不可用",
"groupWorkflow": "工作流",
"groupWorkflowDescription": "按工作流分开任务。",
"groupWorkflowStep": "工作流步骤",
"groupWorkflowStepDescription": "按工作流步骤分开任务。",
"handOffToTarget": "移交给 <1>{{label}}</1>",
"handoff": "移交",
"hardReset": "硬重置",
@@ -1304,6 +1310,31 @@
"showSidebar": "显示侧边栏",
"sibling": "同级",
"sidebarFilters": "侧边栏筛选",
"taskRow": "任务行",
"taskRowChangeRequestStatus": "变更请求状态",
"taskRowChangeRequestStatusDescription": "显示拉取请求或合并请求的状态。",
"taskRowDetails": "详情行",
"taskRowDetailsCount_one": "{{count}} 项详情",
"taskRowDetailsCount_other": "{{count}} 项详情",
"taskRowDetailsDescription": "在任务标题下显示所选元数据。",
"taskRowDetailsHidden": "详情已隐藏",
"taskRowGitChanges": "Git 更改",
"taskRowGitChangesDescription": "显示新增和删除的行。",
"taskRowNothing": "无",
"taskRowNothingDescription": "将右侧留空。",
"taskRowPullRequestNumber": "拉取请求编号",
"taskRowReorderable": "可重新排序",
"taskRowReorderHandle": "重新排序 {{label}}",
"taskRowReordered": "{{label}} 已移动到第 {{position}} 位",
"taskRowRelativeTime": "相对时间",
"taskRowRelativeTimeDescription": "显示任务上次更新时间。",
"taskRowRelativeTimeLastActivity": "如果有记录,则使用任务的最近活动时间。",
"taskRowRelativeTimeLastUpdate": "使用任务的最近更新时间。",
"taskRowRepository": "代码库",
"taskRowRightSide": "右侧",
"taskRowShownOnRight": "显示在右侧",
"taskRowToggleDetail": "{{label}} 详情可见性",
"taskRowToggleDetails": "显示任务详情",
"skipAllQuestions": "跳过全部问题",
"skipped": "已跳过",
"snapshotMessageCount_one": "{{count}} 条消息",
+46 -15
View File
@@ -557,16 +557,22 @@
"goToPreviousMessage": "轉到上一條訊息",
"groupBy": "分組依據",
"groupExecutorType": "執行器類型",
"groupExecutorTypeDescription": "按執行器類型分開任務。",
"groupNone": "無",
"groupNoneDescription": "將所有任務保留在同一個清單中。",
"groupRepository": "儲存庫",
"groupRepositoryDescription": "按儲存庫分開任務。",
"groupState": "狀態",
"groupStateDescription": "按狀態分開任務。",
"groupStatusRateLimited": "暫時受到速率限制",
"groupStatusTimeout": "搜尋超時",
"groupStatusUnauthorized": "需要登入",
"groupStatusUnsupportedScope": "此工作區不可用",
"groupStatusUpstreamError": "提供者不可用",
"groupWorkflow": "工作流程",
"groupWorkflowDescription": "按工作流程分開任務。",
"groupWorkflowStep": "工作流程步驟",
"groupWorkflowStepDescription": "按工作流程步驟分開任務。",
"handOffToTarget": "移交給 <1>{{label}}</1>",
"handoff": "移交",
"hardReset": "硬重置",
@@ -1304,6 +1310,31 @@
"showSidebar": "顯示側邊欄",
"sibling": "同級",
"sidebarFilters": "側邊欄篩選",
"taskRow": "任務行",
"taskRowChangeRequestStatus": "變更請求狀態",
"taskRowChangeRequestStatusDescription": "顯示拉取請求或合併請求的狀態。",
"taskRowDetails": "詳情行",
"taskRowDetailsCount_one": "{{count}} 項詳情",
"taskRowDetailsCount_other": "{{count}} 項詳情",
"taskRowDetailsDescription": "在任務標題下顯示所選元數據。",
"taskRowDetailsHidden": "詳情已隱藏",
"taskRowGitChanges": "Git 更改",
"taskRowGitChangesDescription": "顯示新增和刪除的行。",
"taskRowNothing": "無",
"taskRowNothingDescription": "將右側留空。",
"taskRowPullRequestNumber": "拉取要求編號",
"taskRowReorderable": "可重新排序",
"taskRowReorderHandle": "重新排序 {{label}}",
"taskRowReordered": "{{label}} 已移動到第 {{position}} 位",
"taskRowRelativeTime": "相對時間",
"taskRowRelativeTimeDescription": "顯示任務上次更新時間。",
"taskRowRelativeTimeLastActivity": "如果有記錄,則使用任務的最近活動時間。",
"taskRowRelativeTimeLastUpdate": "使用任務的最近更新時間。",
"taskRowRepository": "程式碼庫",
"taskRowRightSide": "右側",
"taskRowShownOnRight": "顯示於右側",
"taskRowToggleDetail": "{{label}} 詳情可見性",
"taskRowToggleDetails": "顯示任務詳情",
"skipAllQuestions": "跳過全部問題",
"skipped": "已跳過",
"snapshotMessageCount_one": "{{count}} 條訊息",
@@ -1317,13 +1348,13 @@
"sortCustomDescription": "你為任務設定的手動順序。",
"sortDirection": "排序方向 {{direction}}",
"sortLastActivity": "最後活動",
"sortLastActivityDescription": "最近一次使用者操作或代理程式回合。查看任務不會改變此時間。",
"sortLastActivityDescription": "最近一次用戶操作或代理程式回合。查看任務不會改變此時間。",
"sortStatus": "狀態",
"sortStatusDescription": "任務狀態,按審核、進行中和待處理排序。",
"sortTitle": "標題",
"sortTitleDescription": "按任務標題的字母順序。",
"sortUpdated": "更新時間",
"sortUpdatedDescription": "任務摘要的最近重新整理時間。背景事件可能會改變此時間。",
"sortUpdatedDescription": "任務摘要的最近刷新時間。後台事件可能會改變此時間。",
"source": "來源",
"sourceChangesTitle": "{{source}} 變更",
"specifyALocalPortOrLeave": "指定本地端口,或留空以隨機分配。對於 Docker/K8s,請使用已預先暴露的端口。",
@@ -1801,23 +1832,23 @@
"modelSelectionRemediationUnknown": "請檢查執行器設定檔。",
"modelSelectionRequested": "請求的模型",
"modelSelectionWarning": "執行器無法使用已儲存的模型選擇。",
"dynamicRouteWaiting": "沒有可用的合資格代理程式。",
"dynamicRouteActionRequired": "此路由需要復原操作。",
"dynamicRouteRetry": "重試目前代理程式",
"dynamicRouteWaiting": "沒有可用的合格代理。",
"dynamicRouteActionRequired": "此路由需要恢復操作。",
"dynamicRouteRetry": "重試目前代理",
"dynamicRouteRetryNow": "立即重試",
"dynamicRouteTryNext": "嘗試下一個代理程式",
"dynamicRouteSkipNow": "立即略過",
"dynamicRouteRetrying": "正在重試代理程式...",
"dynamicRouteTryNexting": "正在嘗試下一個代理程式...",
"dynamicRouteSkipping": "正在略過代理程式...",
"dynamicRouteTryNext": "嘗試下一個代理",
"dynamicRouteSkipNow": "立即跳過",
"dynamicRouteRetrying": "正在重試代理...",
"dynamicRouteTryNexting": "正在嘗試下一個代理...",
"dynamicRouteSkipping": "正在跳過代理...",
"dynamicRouteCancelWait": "取消等待",
"dynamicRouteStop": "停止",
"dynamicRouteReasonCandidateOrder": "按設定檔順序選取",
"dynamicRouteReasonNoEligibleCandidate": "沒有合資格的候選項目",
"dynamicRouteReasonProviderUnavailable": "供應商不可用",
"dynamicRouteReasonQuotaLimited": "供應商使用量限制",
"dynamicRouteReasonCandidateOrder": "按設定檔順序選擇",
"dynamicRouteReasonNoEligibleCandidate": "沒有合格的候選項",
"dynamicRouteReasonProviderUnavailable": "提供者不可用",
"dynamicRouteReasonQuotaLimited": "提供者使用量限制",
"dynamicRouteErrorClass": "錯誤類別:{{class}}",
"dynamicRouteErrorCode": "錯誤代碼:{{code}}",
"dynamicRouteErrorCode": "錯誤程式碼:{{code}}",
"dynamicRouteRetryOrdinal_one": "重試 {{count}} 次",
"dynamicRouteRetryOrdinal_other": "重試 {{count}} 次",
"dynamicRouteDeadline": "下一次恢復嘗試:{{deadline}}",
+51 -20
View File
@@ -238,8 +238,8 @@
"compareWithPrevious": "與上一個比較",
"comparingAgainstLabel": "比較物件:",
"comparisonTargetLabel": "比較目標",
"comparisonTargetUnavailable": "比較目標無法使用",
"comparisonTargetUnavailableDescription": "無法比較 {{target}}。Kandev 不會使用同名本機分支作為備用目標。",
"comparisonTargetUnavailable": "比較目標不可用",
"comparisonTargetUnavailableDescription": "無法比較 {{target}}。Kandev 不會使用同名本地分支作為後備目標。",
"comparisonTargetUnknown": "已設定的儲存庫目標",
"completed": "已完成",
"completedSuccessfully": "{{operationName}} 已成功完成",
@@ -557,16 +557,22 @@
"goToPreviousMessage": "轉到上一條訊息",
"groupBy": "分組依據",
"groupExecutorType": "執行器型別",
"groupExecutorTypeDescription": "按執行器型別分開任務。",
"groupNone": "無",
"groupNoneDescription": "將所有任務保留在同一個清單中。",
"groupRepository": "儲存庫",
"groupRepositoryDescription": "按儲存庫分開任務。",
"groupState": "狀態",
"groupStateDescription": "按狀態分開任務。",
"groupStatusRateLimited": "暫時受到速率限制",
"groupStatusTimeout": "搜尋超時",
"groupStatusUnauthorized": "需要登入",
"groupStatusUnsupportedScope": "此工作區不可用",
"groupStatusUpstreamError": "提供者不可用",
"groupWorkflow": "工作流程",
"groupWorkflowDescription": "按工作流程分開任務。",
"groupWorkflowStep": "工作流程步驟",
"groupWorkflowStepDescription": "按工作流程步驟分開任務。",
"handOffToTarget": "移交給 <1>{{label}}</1>",
"handoff": "移交",
"hardReset": "硬重置",
@@ -1304,6 +1310,31 @@
"showSidebar": "顯示側邊欄",
"sibling": "同級",
"sidebarFilters": "側邊欄篩選",
"taskRow": "任務行",
"taskRowChangeRequestStatus": "變更請求狀態",
"taskRowChangeRequestStatusDescription": "顯示拉取請求或合併請求的狀態。",
"taskRowDetails": "詳情行",
"taskRowDetailsCount_one": "{{count}} 項詳情",
"taskRowDetailsCount_other": "{{count}} 項詳情",
"taskRowDetailsDescription": "在任務標題下顯示所選後設資料。",
"taskRowDetailsHidden": "詳情已隱藏",
"taskRowGitChanges": "Git 更改",
"taskRowGitChangesDescription": "顯示新增和刪除的行。",
"taskRowNothing": "無",
"taskRowNothingDescription": "將右側留空。",
"taskRowPullRequestNumber": "提取要求編號",
"taskRowReorderable": "可重新排序",
"taskRowReorderHandle": "重新排序 {{label}}",
"taskRowReordered": "{{label}} 已移動到第 {{position}} 位",
"taskRowRelativeTime": "相對時間",
"taskRowRelativeTimeDescription": "顯示任務上次更新時間。",
"taskRowRelativeTimeLastActivity": "如果有記錄,則使用任務的最近活動時間。",
"taskRowRelativeTimeLastUpdate": "使用任務的最近更新時間。",
"taskRowRepository": "程式碼庫",
"taskRowRightSide": "右側",
"taskRowShownOnRight": "顯示於右側",
"taskRowToggleDetail": "{{label}} 詳情可見性",
"taskRowToggleDetails": "顯示任務詳情",
"skipAllQuestions": "跳過全部問題",
"skipped": "已跳過",
"snapshotMessageCount_one": "{{count}} 條訊息",
@@ -1319,11 +1350,11 @@
"sortLastActivity": "最後活動",
"sortLastActivityDescription": "最近一次使用者操作或代理程式回合。檢視任務不會改變此時間。",
"sortStatus": "狀態",
"sortStatusDescription": "任務狀態,依審核、進行中和待處理排序。",
"sortStatusDescription": "任務狀態,按稽核、進行中和待處理排序。",
"sortTitle": "標題",
"sortTitleDescription": "依任務標題的字母順序。",
"sortTitleDescription": "按任務標題的字母順序。",
"sortUpdated": "更新時間",
"sortUpdatedDescription": "任務摘要的最近重新整理時間。背景事件可能會改變此時間。",
"sortUpdatedDescription": "任務摘要的最近重新整理時間。後台事件可能會改變此時間。",
"source": "來源",
"sourceChangesTitle": "{{source}} 變更",
"specifyALocalPortOrLeave": "指定本地埠,或留空以隨機分配。對於 Docker/K8s,請使用已預先暴露的埠。",
@@ -1801,27 +1832,27 @@
"modelSelectionRemediationUnknown": "請檢查執行器設定檔。",
"modelSelectionRequested": "請求的模型",
"modelSelectionWarning": "執行器無法使用已儲存的模型選擇。",
"dynamicRouteWaiting": "沒有可用的合格代理程式。",
"dynamicRouteActionRequired": "此路由需要復原操作。",
"dynamicRouteRetry": "重試目前代理程式",
"dynamicRouteWaiting": "沒有可用的合格代理。",
"dynamicRouteActionRequired": "此路由需要恢復操作。",
"dynamicRouteRetry": "重試目前代理",
"dynamicRouteRetryNow": "立即重試",
"dynamicRouteTryNext": "嘗試下一個代理程式",
"dynamicRouteSkipNow": "立即略過",
"dynamicRouteRetrying": "正在重試代理程式...",
"dynamicRouteTryNexting": "正在嘗試下一個代理程式...",
"dynamicRouteSkipping": "正在略過代理程式...",
"dynamicRouteTryNext": "嘗試下一個代理",
"dynamicRouteSkipNow": "立即跳過",
"dynamicRouteRetrying": "正在重試代理...",
"dynamicRouteTryNexting": "正在嘗試下一個代理...",
"dynamicRouteSkipping": "正在跳過代理...",
"dynamicRouteCancelWait": "取消等待",
"dynamicRouteStop": "停止",
"dynamicRouteReasonCandidateOrder": "依設定檔順序選取",
"dynamicRouteReasonNoEligibleCandidate": "沒有合格的候選項目",
"dynamicRouteReasonProviderUnavailable": "供應商無法使用",
"dynamicRouteReasonQuotaLimited": "供應商使用量限制",
"dynamicRouteReasonCandidateOrder": "按設定檔順序選擇",
"dynamicRouteReasonNoEligibleCandidate": "沒有合格的候選項",
"dynamicRouteReasonProviderUnavailable": "提供者不可用",
"dynamicRouteReasonQuotaLimited": "提供者使用量限制",
"dynamicRouteErrorClass": "錯誤類別:{{class}}",
"dynamicRouteErrorCode": "錯誤代碼:{{code}}",
"dynamicRouteErrorCode": "錯誤程式碼:{{code}}",
"dynamicRouteRetryOrdinal_one": "重試 {{count}} 次",
"dynamicRouteRetryOrdinal_other": "重試 {{count}} 次",
"dynamicRouteDeadline": "下一次復原嘗試:{{deadline}}",
"dynamicRoutePendingOutcome": "復原後:{{outcome}}",
"dynamicRouteDeadline": "下一次恢復嘗試:{{deadline}}",
"dynamicRoutePendingOutcome": "恢復後:{{outcome}}",
"collapsePrompt": "收起提示",
"durationUnitHours": "時",
"durationUnitMinutes": "分",
@@ -0,0 +1,211 @@
---
spec: docs/specs/ui/requirements/sidebar-task-row-presentation.md
created: 2026-08-23
status: complete
---
# Implementation Plan: Sidebar Task Row Presentation
## Overview
Add one task-row presentation object to each saved sidebar view and its draft. Normalize the object
at the frontend boundary, preserve it through the backend-owned user-settings path, and apply the
effective value to every sidebar task row.
Add a compact, collapsed **Task row** editor to the existing view settings. Reuse the installed
`@dnd-kit` packages for pointer, touch, and keyboard ordering. Keep the desktop popover and use a
bottom drawer for the phone and tablet editor.
Refine the provider-neutral change-request status summary in parallel. Give its rows shared label,
icon, and value columns without changing provider status logic.
Related specification: [PR task status summary](../../specs/ui/requirements/pr-task-status-summary.md).
## Confirmed Product Decisions
- Presentation is saved per sidebar view, not globally.
- The current row layout is the migration and new-view default.
- The **Task row** section starts collapsed on every editor open. Its open state is transient.
- The details master toggle hides all under-title metadata, including plugin metadata and queue or
debug indicators.
- Detail order covers relative time, repository, and pull request number. Hidden fields keep their
place in the order.
- The right side supports Git changes, relative time, pull request status, and nothing.
- A trailing relative time suppresses the duplicate details value without changing the saved field.
- A trailing pull request status moves the existing provider indicator. It does not duplicate it.
- Repository remains suppressed when the active view groups by repository.
- The mobile editor is an inset bottom drawer with one scroll body, safe-area padding, and 44 pixel
controls.
- Mobile task rows keep their native primary tap behavior. The compact status indicator stays
passive on coarse pointers.
## Data Contract and Persistence
### Backend
- Add a nullable task-row presentation object to `models.SidebarView` and
`models.SidebarViewDraft`.
- Use explicit nested JSON fields for `details_enabled`, `detail_order`, `visible_details`, and
`trailing`.
- Preserve the nested object through user-settings request and response DTOs, SQLite JSON storage,
optimistic updates, and boot-state camel-case mapping.
- Set the canonical default object on backend-created default views. Keep a missing object valid for
legacy saved data.
- Retain the existing service validation for view IDs, names, active-view references, and the
maximum view count. The frontend owns enum normalization because older clients and future fields
must render safely.
### Frontend
- Define the domain and API types in the sidebar-view type and HTTP contracts.
- Add one pure normalizer for saved and draft presentation data. It removes unknown and duplicate
fields, appends missing known fields, limits visibility to known fields, and applies current
defaults when the object is absent or invalid.
- Extend API wire mapping, boot hydration, migration, built-in views, direct view creation,
duplication, save-as, overwrite, discard, and draft equality.
- Extend `useEffectiveSidebarView` so a draft previews presentation changes immediately.
- Send complete normalized presentation objects to the backend. Do not add local storage.
## Task Row Rendering
- Pass the effective presentation through `TaskSwitcher` and its row plumbing to `TaskItem`.
- Extract pure helpers that resolve visible detail fields, time semantics, group suppression, and
the trailing item. Test these helpers before changing markup.
- Render configurable detail fields in saved order. Append non-configurable queue and debug
indicators after configurable fields when details are enabled.
- Keep plugin `TaskRowMetadata` within the details area so the master toggle produces a true compact
row.
- Let title badges render all current non-change-request badges. Move only the change-request
contribution indicator when the right-side choice requests it.
- Generalize the current trailing Git-change slot. Passive Git changes or time can yield to the row
menu. Interactive provider status and the row menu remain separately focusable.
- Do not reserve trailing space when the selected value is absent.
## View Settings UI
- Extract shared editor content from `SidebarFilterPopover` so desktop and mobile can use the same
draft and save actions.
- Keep desktop in the anchored, viewport-contained popover.
- Render the phone and tablet editor in an inset bottom drawer. The drawer has one scroll owner,
bottom safe-area padding, escape and outside-close behavior, and focus restoration.
- Add a collapsed **Task row** section after **Group by**. Use local component state for expansion.
- Derive the compact summary from details-enabled state, visible detail count, and trailing choice.
- Use sortable rows with a visible handle, visibility switch, keyboard sensor, and accessible drag
announcements. Touch handles and other mobile controls are at least 44 by 44 CSS pixels.
- Explain the relative-time meaning and the dynamic **Shown on right** state in localized copy.
- Add every new key to English, Portuguese, Simplified Chinese, Hong Kong Chinese, and Taiwan
Chinese catalogs. Generate the Traditional Chinese pair with the repository command.
## Change-Request Summary Alignment
- Refactor `ChangeRequestTaskStatusSummary` so all available rows in one entry share a
`max-content`, fixed-icon, and flexible-value grid.
- Align secondary detail to the value column.
- Preserve current test IDs, provider presentation data, semantic tones, icons, wrapping,
multi-entry separators, tooltip state, and viewport containment.
- Exercise the shared component through GitHub, GitLab, and registered-provider unit coverage.
## Tests
- **What:** defaulting, malformed-data normalization, wire round trips, draft equality, save,
save-as, discard, duplicate, and optimistic rollback.
**Files:** `apps/web/lib/state/slices/ui/sidebar-view-wire.test.ts`,
`ui-slice-migration.test.ts`, and `sidebar-view-actions.test.ts`.
**How:** use old, valid, future-field, duplicate-field, and invalid enum fixtures.
- **What:** backend JSON preservation and boot-state mapping.
**Files:** `apps/backend/internal/user/store/sqlite_test.go`,
`service/service_test.go`, `handlers/handlers_test.go`, and
`internal/backendapp/boot_state_routes_test.go`.
**How:** persist an explicit disabled/details order and trailing choice, reload it, and compare
both REST and camel-case boot shapes. Include a legacy missing object.
- **What:** field order, group suppression, relative-time deduplication, details hiding, provider
icon movement, missing-data collapse, and menu coexistence.
**Files:** `apps/web/components/task/task-item.test.tsx`,
`task-item-repository.test.tsx`, and a focused presentation helper test.
**How:** render table-driven presentation and task-data combinations.
- **What:** collapsed editor state, draft patches, summaries, reorder input, and responsive surface
choice.
**Files:** focused tests beside `apps/web/components/task/sidebar-filter/`.
**How:** render with the shared state provider and mock breakpoint, drag-end, and keyboard reorder
events.
- **What:** shared status-value and detail alignment.
**Files:** provider status-summary render tests.
**How:** render label lengths and wrapped detail, then assert the shared grid contract and
unchanged provider text.
## E2E Tests
- **Scenario:** Configure, preview, save, discard, save as, and reload a desktop task-row layout.
**File:** `apps/web/e2e/tests/task/sidebar-filter.spec.ts`.
**What to verify:** the section starts collapsed, its open state does not mark the view dirty,
field order and visibility preview immediately, and saved views retain independent layouts.
- **Scenario:** Use the editor and reordered task row on a phone viewport.
**File:** `apps/web/e2e/tests/task/mobile-sidebar-views.spec.ts`.
**What to verify:** the bottom drawer, 44 pixel controls, touch reorder, internal scroll,
safe-area clearance, primary row tap, reload persistence, and no horizontal overflow.
- **Scenario:** Put pull request status on the right and open its summary beside the row menu.
**File:** `apps/web/e2e/tests/pr/pr-status-badge.spec.ts`.
**What to verify:** one status indicator, separate keyboard targets for indicator and menu,
aligned status-value left edges, aligned merge-queue detail, and viewport containment.
- **Scenario:** Keep the compact provider indicator passive on mobile.
**File:** `apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts`.
**What to verify:** tapping the row still navigates and no compact status control steals the tap.
## Documentation Impact
This design changes no CLI command, public API, install flow, or public configuration key. The
internal specs and plan are sufficient at this checkpoint. During implementation, search public
task and view documentation for screenshots or labels that show the old view editor. Update only
the affected page if one exists.
## Risks
- A non-null Go zero value can confuse a legacy missing object with an explicit disabled setting.
Use a nullable nested object at the persistence boundary and normalize it in the frontend.
- Moving a provider indicator can remove the only hover or focus trigger. Keep one mounted instance
and move its presentation location rather than rendering a second copy.
- The task menu currently overlays passive Git changes. Reusing that overlay for an interactive
status would block its trigger. Give the status and menu separate hit targets.
- Nested drag contexts exist in the mobile sidebar. Keep field sorting inside the editor drawer and
stop its events from reaching task or saved-view sorting contexts.
- Longer translations can widen labels and summaries. Use content-sized grid tracks with a flexible
value column and test narrow viewports and pseudo-locale output.
- Hiding the whole details area also hides plugin metadata and queue indicators. The master-toggle
test must cover those values so future components do not escape the contract.
## Verification Results
- Backend targeted coverage passed: `go test -tags fts5 ./internal/user/... ./internal/backendapp`
reported 808 passing tests across 7 packages.
- Frontend persistence coverage passed: 4 files, 61 tests. Task-row rendering coverage passed: 5
files, 78 tests. Settings coverage passed: 4 files, 12 tests. Shared provider-summary coverage
passed: 4 files, 31 tests.
- Frontend typecheck, full workspace lint, changed-file ESLint, `i18n:check`, `i18n:ratchet`, and
`git diff --check` passed. `make -C apps/backend test` passed the full Go suite.
- Desktop task-row E2E passed: 1 test in 6.1 seconds. Mobile task-row E2E passed: 1 test in 10.2
seconds. PR summary E2E passed: 1 test in 3.2 seconds. The mobile status-summary regression
passed: 1 test in 4.7 seconds. Final capture runs also passed the desktop and mobile task-row
scenarios.
- The repository `i18n:zh-hant` wrapper remains blocked by its pre-existing `agents` namespace
residual warning. The scoped task conversion completed successfully for both Traditional Chinese
locales, with zero task residual warnings.
## Implementation Waves and Parallel Candidates
Wave 1:
- [x] [Task 01: Persist task-row presentation](task-01-persist-task-row-presentation.md)
- [x] [Task 04: Align change-request summary rows](task-04-align-change-request-summary-rows.md)
Wave 2:
- [x] [Task 02: Render configured task rows](task-02-render-configured-task-rows.md)
- [x] [Task 03: Build responsive task-row settings](task-03-build-responsive-task-row-settings.md)
Wave 3:
- [x] [Task 05: Prove task-row presentation end to end](task-05-prove-task-row-presentation.md)
Tasks 01 and 04 are independent. Tasks 02 and 03 both depend on Task 01 and can proceed in
parallel. Task 05 integrates all four production tasks. These labels document dependency only and
do not authorize delegated implementation.
@@ -0,0 +1,97 @@
---
id: "01-persist-task-row-presentation"
title: "Persist task-row presentation"
status: complete
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/ui/requirements/sidebar-task-row-presentation.md"
---
# Task 01: Persist Task-Row Presentation
## Acceptance
- Each saved sidebar view and draft can carry a complete task-row presentation through REST,
SQLite, boot hydration, frontend state, save, save-as, duplicate, discard, and rollback flows.
- Missing or malformed data resolves to the current layout. Explicitly disabled details remain
disabled after a round trip.
- A draft presentation previews as the effective view without mutating the saved view.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile
cd apps/backend && go test -tags fts5 ./internal/user/... ./internal/backendapp
make -C apps/backend test
cd apps && pnpm --filter @kandev/web test -- --run lib/state/slices/ui/sidebar-view-wire.test.ts lib/state/slices/ui/ui-slice-migration.test.ts lib/state/slices/ui/sidebar-view-actions.test.ts lib/state/slices/ui/ui-slice.test.ts
cd apps/web && pnpm run typecheck
```
## Files Likely Touched
- `apps/backend/internal/user/models/models.go`
- `apps/backend/internal/user/store/sqlite.go`
- `apps/backend/internal/user/store/sqlite_test.go`
- `apps/backend/internal/user/service/service_test.go`
- `apps/backend/internal/user/handlers/handlers_test.go`
- `apps/backend/internal/backendapp/boot_state_routes.go`
- `apps/backend/internal/backendapp/boot_state_routes_test.go`
- `apps/web/lib/types/http-user-settings.ts`
- `apps/web/lib/state/slices/ui/sidebar-view-types.ts`
- `apps/web/lib/state/slices/ui/sidebar-view-wire.ts`
- `apps/web/lib/state/slices/ui/sidebar-view-builtins.ts`
- `apps/web/lib/state/slices/ui/sidebar-view-actions.ts`
- `apps/web/lib/state/slices/ui/ui-slice.ts`
- `apps/web/hooks/domains/sidebar/use-effective-sidebar-view.ts`
- Focused tests beside these files
## Dependencies
None.
## Parallelism
`parallel-safe` with Task 04. This task owns the saved-view contract and state files. Task 04 owns
the provider-neutral summary component.
## Inputs
- The data and persistence rules in the sidebar task-row presentation spec.
- ADR 0041 backend ownership and complete-payload normalization rules.
- Existing sidebar view wire, migration, optimistic mutation, and boot-state mapping paths.
- The canonical current layout: details enabled, all fields visible in current order, and Git
changes on the right.
## TDD Sequence
1. Add frontend normalization and wire tests for missing, valid, malformed, duplicate, and future
fields. Record the expected failures.
2. Add action tests for draft creation, save, save-as, duplicate, discard, and failed-write rollback.
3. Add backend persistence and boot-map tests for an explicit presentation and a legacy missing
object. Record the expected failures.
4. Add the nullable backend model and explicit frontend API and domain types.
5. Implement the pure frontend normalizer and extend wire, migration, built-in, action, and
effective-view paths.
6. Run focused backend and frontend tests, then frontend typecheck.
7. Record exact results and synchronize the plan and task status.
## Risks
- A plain boolean zero value cannot distinguish legacy missing data from explicit `false`.
- Full-array optimistic rollback must restore views, active view, and draft together.
- A future client can add a field that this client does not know. Unknown values must not corrupt
known order or visibility.
## Output Contract
Report RED failures, the final wire shape, normalization decisions, files changed, exact test
results, compatibility behavior, blockers, risks, and synchronized task and plan status.
## Results
RED coverage was added for missing and explicit task-row wire data before the production model and
normalizer were implemented. The backend model, SQLite defaults/round trip, boot mapping, API wire
mapping, migration, effective-view preview, and optimistic view actions now preserve the complete
normalized object. Targeted backend coverage passed with 808 tests across 7 packages; frontend
persistence coverage passed with 61 tests across 4 files; frontend typecheck passed.
@@ -0,0 +1,89 @@
---
id: "02-render-configured-task-rows"
title: "Render configured task rows"
status: complete
wave: 2
depends_on: ["01-persist-task-row-presentation"]
plan: "plan.md"
spec: "../../specs/ui/requirements/sidebar-task-row-presentation.md"
---
# Task 02: Render Configured Task Rows
## Acceptance
- Sidebar rows apply the effective view's detail visibility, order, details toggle, and right-side
choice without changing Kanban cards or the rich task list.
- Relative time and repository suppression follow the spec, and missing values reserve no space.
- A moved provider status remains the single interactive indicator and coexists with the task menu.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile
cd apps && pnpm --filter @kandev/web test -- --run components/task/task-item.test.tsx components/task/task-item-repository.test.tsx components/task/task-item.mr-guard.test.tsx components/task/task-row-presentation.test.ts
cd apps/web && pnpm run typecheck
cd apps && pnpm --filter @kandev/web lint -- components/task/task-item.tsx components/task/task-item-stats-row.tsx components/task/task-item-leading-badges.tsx components/task/task-contribution-icons.tsx components/task/task-row-presentation.ts
```
## Files Likely Touched
- `apps/web/components/task/task-item.tsx`
- `apps/web/components/task/task-item-stats-row.tsx`
- `apps/web/components/task/task-item-leading-badges.tsx`
- `apps/web/components/task/task-contribution-icons.tsx`
- `apps/web/components/task/task-row-presentation.ts`
- `apps/web/components/task/task-switcher-row.tsx`
- `apps/web/components/task/task-switcher.tsx`
- Focused tests beside these files
## Dependencies
Task 01.
## Parallelism
`parallel-safe` with Task 03 after Task 01. This task owns task-row rendering and contribution-icon
placement. Task 03 owns the settings surface.
## Inputs
- The display rules in the sidebar task-row presentation spec.
- The normalized effective presentation from Task 01.
- Existing time selection, repository grouping suppression, contribution indicators,
`TaskRowMetadata`, queue indicators, and task-menu behavior.
## TDD Sequence
1. Add pure resolver tests for ordered visible details, relative-time deduplication, repository
grouping, and missing trailing data. Record the expected failures.
2. Add render tests for details enabled and disabled, queue and plugin metadata, each trailing
choice, and one moved contribution indicator.
3. Add a keyboard test that opens the provider summary and the task menu as separate targets.
4. Implement presentation plumbing and the pure resolver.
5. Split configurable details from appended queue and debug indicators and gate the full metadata
block with `details_enabled`.
6. Generalize the trailing slot and move, rather than duplicate, the change-request indicator.
7. Run focused tests, typecheck, and changed-file lint. Record exact results.
## Risks
- Moving the icon can mount two tooltip state owners or remove the focused node. Render one location
from one resolved placement.
- Hiding metadata can leave vertical gaps if title-container spacing remains unconditional.
- The row menu can cover an interactive provider indicator if it reuses the passive-value overlay.
- Subtask toggles also occupy the trailing area and must remain reachable.
## Output Contract
Report RED failures, rendering and focus changes, files changed, exact unit, typecheck, and lint
results, mobile-impact notes, blockers, risks, and synchronized task and plan status.
## Results
RED rendering tests covered ordered details, grouping suppression, details hiding, trailing choices,
provider-status placement, missing values, and menu coexistence. The effective presentation is now
threaded through sidebar rows, with plugin and queue/debug metadata gated by the details master
toggle and one provider indicator rendered in its selected location. Task-row coverage passed with
78 tests across 5 files; the final focused cleanup set passed with 60 tests across 5 files; typecheck
and changed-file ESLint passed.
@@ -0,0 +1,97 @@
---
id: "03-build-responsive-task-row-settings"
title: "Build responsive task-row settings"
status: complete
wave: 2
depends_on: ["01-persist-task-row-presentation"]
plan: "plan.md"
spec: "../../specs/ui/requirements/sidebar-task-row-presentation.md"
---
# Task 03: Build Responsive Task-Row Settings
## Acceptance
- The view editor adds one collapsed **Task row** section with an accurate summary, details toggle,
field visibility and ordering, and right-side choice.
- Section expansion is transient. Presentation changes use the existing draft and save controls.
- Desktop uses the anchored popover. Phone and tablet use an inset, safe-area-aware bottom drawer
with one scroll body and 44 pixel controls.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile
cd apps && pnpm --filter @kandev/web test -- --run components/task/sidebar-filter/sidebar-filter-popover.test.tsx components/task/sidebar-filter/task-row-settings.test.tsx components/task/sidebar-filter/use-sidebar-view-popover.test.tsx
cd apps/web && pnpm run typecheck
cd apps/web && pnpm run i18n:zh-hant
cd apps/web && pnpm run i18n:check
cd apps/web && pnpm run i18n:ratchet
```
## Files Likely Touched
- `apps/web/components/task/sidebar-filter/sidebar-filter-popover.tsx`
- `apps/web/components/task/sidebar-filter/sidebar-filter-bar.tsx`
- `apps/web/components/task/sidebar-filter/task-row-settings.tsx`
- `apps/web/components/task/sidebar-filter/sidebar-view-editor.tsx`
- `apps/web/components/task/mobile/session-task-switcher-sheet.tsx`
- `apps/web/hooks/use-responsive-breakpoint.ts`
- `apps/web/src/locales/en/task.json`
- `apps/web/src/locales/pt-pt/task.json`
- `apps/web/src/locales/zh-cn/task.json`
- `apps/web/src/locales/zh-hk/task.json`
- `apps/web/src/locales/zh-tw/task.json`
- Focused tests beside the editor components
## Dependencies
Task 01.
## Parallelism
`parallel-safe` with Task 02 after Task 01. This task owns the settings surface and locale files.
Task 02 owns the task-row renderer.
## Inputs
- The editor, responsive, and accessibility rules in the spec.
- The existing `ViewHeaderRow`, draft update actions, and mobile task-switcher sheet.
- Existing `@dnd-kit/core`, `@dnd-kit/sortable`, and `@dnd-kit/utilities` dependencies.
- The repository mobile UI language and existing responsive breakpoint hook.
## TDD Sequence
1. Add a test that the section starts collapsed and expansion alone does not call `updateDraft`.
2. Add tests for each compact summary, visibility patch, trailing patch, pointer reorder, and keyboard
reorder. Record the expected failures.
3. Add responsive tests that select a popover for desktop and a drawer for phone and tablet.
4. Extract shared editor content and add the collapsed task-row editor.
5. Add the responsive drawer with one scroll owner, safe-area padding, close behavior, focus return,
and 44 pixel controls.
6. Add localized copy in five catalogs and generate the Traditional Chinese variants.
7. Run focused tests, typecheck, the locale audit, and the i18n ratchet. Record exact results.
## Risks
- Reusing a popover inside the mobile sheet can create nested focus traps. The breakpoint must select
one top-level editor surface.
- A drag handle can start task or saved-view reordering if events escape the editor context.
- Drawer content can gain two vertical scroll owners if the current popover overflow class remains
on shared content.
- Summary plurals require locale plural keys and a numeric `count` value.
## Output Contract
Report RED failures, desktop and mobile surface behavior, accessibility details, locale files,
files changed, exact test and i18n results, blockers, risks, and synchronized task and plan status.
## Results
RED editor tests covered collapsed state, draft patches, summaries, ordering, and desktop/mobile
surface selection. The shared editor now uses an anchored desktop popover and an inset mobile/tablet
drawer with one scroll owner, safe-area padding, focus restoration, sortable fields, keyboard and
touch sensors, and 44 pixel controls. Settings coverage passed with 12 tests across 4 files;
typecheck, `i18n:check`, and `i18n:ratchet` passed. The repository Traditional Chinese wrapper still
reports its pre-existing `agents` residual warning, so the scoped task conversion command was used
and completed with zero task residual warnings.
@@ -0,0 +1,78 @@
---
id: "04-align-change-request-summary-rows"
title: "Align change-request summary rows"
status: complete
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/ui/requirements/pr-task-status-summary.md"
---
# Task 04: Align Change-Request Summary Rows
## Acceptance
- Review, CI, merge, and terminal status values share one horizontal start in each summary entry.
- Secondary detail starts under the status text and wraps inside the value column.
- GitHub, GitLab, and registered-provider summaries keep their current state, icon, color, copy,
focus, hover, and viewport behavior.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile
cd apps && pnpm --filter @kandev/web test -- --run components/integrations/change-request-task-status-summary.test.tsx components/integrations/registered-change-request-task-icon.test.tsx components/github/pr-task-status-summary.test.ts components/gitlab/mr-task-status-summary.test.ts
cd apps/web && pnpm run typecheck
cd apps && pnpm --filter @kandev/web lint -- components/integrations/change-request-task-status-summary.tsx
```
## Files Likely Touched
- `apps/web/components/integrations/change-request-task-status-summary.tsx`
- `apps/web/components/integrations/change-request-task-status-summary.test.tsx`
- Existing GitHub, GitLab, and registered-provider summary tests
- `docs/specs/ui/requirements/pr-task-status-summary.md`
## Dependencies
None.
## Parallelism
`parallel-safe` with Task 01. This task owns only the shared summary layout and focused tests.
## Inputs
- The alignment requirements and scenarios in the PR task status summary spec.
- The existing `SummaryRow`, provider presentation data, and merge-queue detail output.
- Existing GitHub, GitLab, and registered-provider render coverage.
## TDD Sequence
1. Add a focused shared-component test with short and long row labels and queue detail. Record the
expected layout-contract failure.
2. Add provider regression assertions for unchanged labels, tones, icons, and test IDs.
3. Replace per-row independent grids with one shared label, icon, and flexible value grid.
4. Place row detail in the value column under the status text.
5. Verify wrapped text, multiple entries, and absent rows.
6. Run focused tests, typecheck, and changed-file lint. Record exact results.
## Risks
- CSS `subgrid` support or test environments can differ. Prefer a direct shared parent grid if it
provides the same alignment with simpler compatibility.
- A fixed label width can clip translated copy. Use a content-sized track.
- Flattening row wrappers can remove test IDs or accessible grouping. Preserve both.
## Output Contract
Report the RED layout assertion, final grid contract, provider regressions checked, files changed,
exact test, typecheck, and lint results, blockers, risks, and synchronized task and plan status.
## Results
RED shared-component coverage asserted the common label, icon, and value grid contract. The summary
now aligns all status values and places secondary detail beneath the value column while preserving
provider copy, tones, icons, test IDs, wrapping, and viewport behavior. GitHub, GitLab, and
registered-provider coverage passed with 31 tests across 4 files; typecheck and changed-file ESLint
passed.
@@ -0,0 +1,112 @@
---
id: "05-prove-task-row-presentation"
title: "Prove task-row presentation"
status: complete
wave: 3
depends_on:
- "02-render-configured-task-rows"
- "03-build-responsive-task-row-settings"
- "04-align-change-request-summary-rows"
plan: "plan.md"
spec: "../../specs/ui/requirements/sidebar-task-row-presentation.md"
---
# Task 05: Prove Task-Row Presentation End to End
## Acceptance
- Desktop E2E proves live preview, compact-section behavior, save, save-as, discard, independent
views, reload persistence, field order, each right-side choice, and aligned status summaries.
- Mobile E2E proves the native drawer, touch controls, reorder, safe-area and scroll behavior,
passive status indicator, row navigation, persistence, and no horizontal overflow.
- Focused backend and frontend checks, typecheck, lint, localization checks, and `git diff --check`
pass, and every design artifact records the exact results.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile
cd apps/backend && go test -tags fts5 ./internal/user/... ./internal/backendapp
make -C apps/backend test
cd apps && pnpm --filter @kandev/web test -- --run lib/state/slices/ui/sidebar-view-wire.test.ts lib/state/slices/ui/ui-slice-migration.test.ts lib/state/slices/ui/sidebar-view-actions.test.ts components/task/task-item.test.tsx components/task/task-item-repository.test.tsx components/task/task-row-presentation.test.ts components/task/sidebar-filter/sidebar-filter-popover.test.tsx components/task/sidebar-filter/task-row-settings.test.tsx components/integrations/change-request-task-status-summary.test.tsx components/integrations/registered-change-request-task-icon.test.tsx
cd apps/web && pnpm run typecheck
cd apps/web && pnpm run i18n:check
cd apps/web && pnpm run i18n:ratchet
cd apps/web && pnpm e2e:run tests/task/sidebar-filter.spec.ts -- --grep "task row"
cd apps/web && pnpm e2e:run tests/pr/pr-status-badge.spec.ts -- --grep "readable task PR summary|task row"
cd apps/web && pnpm e2e:run --project mobile-chrome tests/task/mobile-sidebar-views.spec.ts tests/task/mobile-task-status-summary.spec.ts -- --grep "task row|status summary"
git diff --check
```
## Files Likely Touched
- `apps/web/e2e/pages/sidebar-filter-popover.ts`
- `apps/web/e2e/tests/task/sidebar-filter.spec.ts`
- `apps/web/e2e/tests/task/mobile-sidebar-views.spec.ts`
- `apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts`
- `apps/web/e2e/tests/pr/pr-status-badge.spec.ts`
- `docs/specs/ui/requirements/sidebar-task-row-presentation.md`
- `docs/specs/ui/requirements/pr-task-status-summary.md`
- `docs/plans/sidebar-task-row-presentation/plan.md`
- All task files in this plan
## Dependencies
Tasks 02, 03, and 04.
## Parallelism
`sequential`. This task validates the integrated persistence, editor, renderer, provider summary,
and mobile behavior after all production tasks finish.
## Inputs
- Every scenario in both linked specs.
- Production and unit changes from Tasks 01 through 04.
- Existing sidebar filter, PR status badge, mobile sidebar view, and mobile status-summary fixtures.
- The mobile parity reference for touch targets, scroll ownership, safe areas, and passive row icons.
## TDD Sequence
1. Extend the sidebar-filter page object with task-row section and field controls.
2. Add desktop E2E for collapsed state, live preview, save, save-as, discard, reload, and independent
views. Record the expected failure before relying on the implementation.
3. Add PR E2E geometry assertions for shared status-value left edges and queue-detail alignment.
4. Add mobile E2E for the drawer, touch reorder, persistence, primary row tap, safe-area clearance,
internal scroll, and overflow.
5. Run the focused backend, unit, typecheck, i18n, desktop E2E, and mobile E2E commands.
6. Inspect desktop and mobile results for title truncation, trailing-menu overlap, wrapped
translations, and unexpected empty space.
7. Update both spec statuses to `shipped`, mark all plan tasks complete, and record exact results.
## Risks
- Drag-and-drop E2E can be input-device sensitive. Assert the persisted order after the gesture,
not only the transient drag overlay.
- Geometry assertions need a small pixel tolerance for browser rounding while still detecting the
current column misalignment.
- Seeded tasks need repository, pull request, diff, queue, and missing-data variants to cover all
layout branches.
- Mobile screenshots or measurements can include browser safe-area differences. Assert against the
drawer content and viewport, not a device-specific absolute offset.
## Output Contract
Report the E2E RED failures, final scenarios, desktop and mobile evidence, files changed, every exact
verification result, public-docs impact, blockers, risks, and synchronized spec, plan, and task
status.
## Results
Desktop task-row E2E passed with 1 test in 6.1 seconds, mobile task-row E2E passed with 1 test in
10.2 seconds, and PR task-summary E2E passed with 1 test in 3.2 seconds. The mobile status-summary
regression passed with 1 test in 4.7 seconds. Final capture runs also passed the desktop and mobile
task-row scenarios. The scenarios cover
collapsed/open state, live preview, ordering, visibility, trailing choices, save-as, overwrite,
discard, reload persistence, independent views, drawer bounds, safe-area/scroll ownership, and
summary alignment. Unit coverage, full backend suite, full workspace lint, typecheck, focused
ESLint, i18n checks, and `git diff --check` passed. Fresh PR evidence was captured for the desktop
settings, mobile drawer, and PR summary surfaces, inspected, compressed, and validated against its
three-entry manifest. The repository Traditional Chinese wrapper remains blocked by its pre-existing
`agents` namespace residual warning; the scoped task conversion passed with zero task residual
warnings.
+1 -1
View File
@@ -19,7 +19,7 @@ This catalog is the entry point for the system-oriented specification layout. Ea
| Release | [README](release/README.md) | complete | 5 requirements, 0 designs |
| System page | [README](system-page/README.md) | complete | 3 requirements, 5 designs |
| Tasks | [README](tasks/README.md) | complete | 69 requirements, 12 designs |
| UI | [README](ui/README.md) | complete | 95 requirements, 11 designs |
| UI | [README](ui/README.md) | complete | 96 requirements, 11 designs |
| Workspaces | [README](workspaces/README.md) | complete | 10 requirements, 2 designs |
## Migration record
+1
View File
@@ -116,6 +116,7 @@ contract that other capabilities can reuse.
- [Sidebar Last Activity Sort](requirements/sidebar-last-activity-sort.md)
- [Sidebar Queued Prompt Count Badge](requirements/sidebar-queued-prompt-count.md)
- [Sidebar Task Completion Icons](requirements/sidebar-task-completion-icons.md)
- [Sidebar Task Row Presentation](requirements/sidebar-task-row-presentation.md)
- [Direct Sidebar View Creation](requirements/sidebar-view-creation.md)
- [Slash Command Composer Selection](requirements/slash-command-composer.md)
- [Subagent Observability](requirements/subagent-observability.md)
@@ -27,6 +27,10 @@ Task pull-request indicators currently flatten the PR title, review state, CI st
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.6:** A task with several linked PRs shows one consistently structured entry per PR, separated clearly, while retaining the existing aggregate icon color, PR count, and ready-to-merge attributes.
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.7:** The disclosure uses localized copy, readable line height, restrained semantic colors, and a viewport-contained width. It remains informational: opening it does not navigate, mutate PR state, fetch new detail, or change task-row activation.
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.8:** The shared task PR indicator uses the same summary in the desktop sidebar, Kanban cards, and rich task-list rows.
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.9:** All status entries in one summary share label, icon, and status-text columns so Review, CI, merge, and terminal values start at the same horizontal position.
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.10:** Secondary detail, including merge-queue position and estimated merge time, starts under the status text instead of under the label or icon.
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.11:** Shared columns adapt to translated labels and wrapped values without a fixed label width that clips content.
- **AC-UI-PR-TASK-STATUS-SUMMARY-001.12:** GitHub, GitLab, and registered change-request providers that use the shared summary component receive the same row alignment without changing provider-specific state derivation or copy.
## Migrated source detail
@@ -36,6 +40,9 @@ Task pull-request indicators currently flatten the PR title, review state, CI st
mergeability into one pipe-delimited sentence. Long titles and several adjacent status values
make the hover disclosure slow to scan during a brief pointer interaction.
The structured disclosure currently sizes each row label independently. Status values therefore
do not align, and secondary merge-queue text begins under the icon instead of the status text.
## What
- Hovering a task's PR indicator with a fine pointer, or focusing it with the keyboard, shows a
@@ -45,6 +52,13 @@ make the hover disclosure slow to scan during a brief pointer interaction.
- Review, CI, and merge or terminal state appear as separate labelled rows when their source data
is available. Each row combines readable text with a semantic icon and color; no meaning depends
on color or icon alone.
- All status entries in one summary share three columns: label, fixed icon, and status text. Review,
CI, merge, and terminal values start at the same horizontal position even when labels differ in
width.
- Secondary detail, such as merge-queue position and estimated merge time, starts under the status
text. It does not start under the icon or label.
- The shared columns adapt to translated labels and wrapped values. The layout does not use a fixed
label width that clips a longer locale.
- Known GitHub states use concise user-facing copy such as **Approved**, **Passed**, **In
progress**, **Changes requested**, **Conflicts**, and **Ready to merge**. An unrecognized
non-empty provider value remains visible instead of being dropped.
@@ -58,6 +72,8 @@ make the hover disclosure slow to scan during a brief pointer interaction.
state, fetch new detail, or change task-row activation.
- The shared task PR indicator uses the same summary in the desktop sidebar, Kanban cards, and rich
task-list rows.
- GitHub, GitLab, and registered change-request providers that use the shared summary component get
the same row alignment. Provider-specific state derivation and copy remain unchanged.
- On coarse-pointer phone and tablet layouts, task rows keep their existing primary tap behavior
and passive PR indicator. Detailed touch interaction remains available through the existing PR
status drawer after opening the task, so this visual refinement adds no hover-only required
@@ -67,7 +83,8 @@ make the hover disclosure slow to scan during a brief pointer interaction.
- **GIVEN** an open PR with an approval, successful CI, and clean mergeability, **WHEN** the user
hovers or focuses its task PR indicator, **THEN** the summary separates the PR number and title
from labelled **Review — Approved**, **CI — Passed**, and **Merge — Ready to merge** rows.
from labelled **Review: Approved**, **CI: Passed**, and **Merge: Ready to merge** rows, and all
three status values have the same horizontal start.
- **GIVEN** a PR with changes requested, failing CI, a merge conflict, a blocked state, or a
behind-base state, **WHEN** its summary opens, **THEN** each available condition appears in its
own readable row with matching semantic text and icon without changing the indicator's existing
@@ -82,20 +99,25 @@ make the hover disclosure slow to scan during a brief pointer interaction.
- **GIVEN** a non-empty provider status Kandev does not recognize, **WHEN** the summary opens,
**THEN** that value remains visible as fallback text; absent status fields do not produce empty
rows.
- **GIVEN** merge-queue detail appears below **Awaiting checks**, **WHEN** the summary opens,
**THEN** that detail starts under **Awaiting checks** and wraps within the status column.
- **GIVEN** translated row labels have different lengths, **WHEN** the summary renders, **THEN** the
longest available label defines the shared label column and no label or status is clipped.
- **GIVEN** a phone task-switcher drawer, **WHEN** a linked-PR task row renders and the user taps
the row, **THEN** the existing task navigation and PR indicator remain usable without horizontal
overflow or a new hover-dependent interaction.
## Out of scope
- Changing GitHub status derivation, merge readiness, polling, API contracts, persistence, or
task-to-PR associations.
- Changing polling, API contracts, persistence, or task-to-change-request associations.
- Adding check-run lists, reviewer lists, comments, merge controls, or other full PR-detail content
to the task indicator summary.
- Changing GitLab merge-request or Azure DevOps pull-request indicators.
- Changing GitHub, GitLab, or registered-provider status derivation, icon precedence, or copy.
- Adding a new phone/tablet task-row drawer or turning the compact PR indicator into a separate
touch action.
## Implementation plan
[PR task status summary plan](../../../plans/pr-task-status-summary/plan.md)
[Sidebar task row presentation refinement](../../../plans/sidebar-task-row-presentation/plan.md)
@@ -0,0 +1,192 @@
---
status: active
system: ui
created: 2026-08-23
owners:
- kandev
---
# Sidebar Task Row Presentation Requirements
## Overview
Each saved sidebar view owns its task-row presentation so focused views can show only the metadata
needed for their workflow. The view editor controls the details row, detail order and visibility,
and the value shown on the right side of each task row across desktop and mobile layouts.
## Requirements
### REQ-UI-SIDEBAR-TASK-ROW-PRESENTATION-001: Configurable task-row presentation
**Intent:** Let each saved sidebar view control task-row metadata without changing established
defaults, persistence ownership, accessibility, or responsive interaction behavior.
#### Acceptance criteria
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.1:** Each saved sidebar view and matching draft may store whether details are enabled, the order and visibility of relative time, repository, and pull request number, and a trailing choice of Git changes, relative time, change request status, or nothing.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.2:** Missing or malformed task-row settings normalize to the established layout of enabled details in canonical order with Git changes on the right, while valid empty visible details remain empty.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.3:** The view editor shows a collapsed Task row section after Group by, summarizes its current configuration, and expands to expose a details toggle, ordered field controls, and the Right side selector.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.4:** Presentation edits preview through the existing draft workflow; Save, Save as, and Discard persist or restore them with the view, while expanding or collapsing the section does not create a draft.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.5:** Disabling details removes all under-title metadata and leaves the title row vertically centered with its task-state icon, badges, trailing content, and action menu.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.6:** Selecting relative time on the right suppresses its duplicate detail while preserving its saved detail position and visibility and marking it as shown on the right in the editor.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.7:** Grouping by repository suppresses duplicate repository details without changing the saved field setting, and absent metadata reserves no empty row space.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.8:** Passive trailing values yield to the action menu on the same outer-row hover and focus conditions; an interactive change-request status remains keyboard and pointer reachable beside the menu.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.9:** Desktop uses the anchored editor popover, while phone and tablet layouts use an inset, safe-area-aware bottom drawer with one internal vertical scroll area and separators constrained to the drawer width.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.10:** Mobile section headers, switches, selectors, and drag handles provide at least 44 by 44 CSS pixel touch targets, and field reorder supports pointer, touch, and keyboard input with an accessible announcement.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.11:** A failed draft, create, or save request cannot roll back a later confirmed sidebar write; all sidebar writes share one synchronization journal and restore only the latest confirmed state.
- **AC-UI-SIDEBAR-TASK-ROW-PRESENTATION-001.12:** The editor and task rows cause no document-level horizontal overflow at supported widths, and the mobile task row remains the primary tap target.
## Migrated source detail
## Why
Sidebar task rows always show the same metadata and trailing Git change count. This layout is useful
for a broad task view, but it can add noise in a focused view. Users also cannot place the metadata
in the order that matches their work.
Each saved sidebar view already owns its filter, sort, and group settings. Task-row presentation
belongs to the same view because a review view and a planning view can need different information.
## What
- Each saved sidebar view owns a task-row presentation setting.
- The view editor contains a collapsed **Task row** section after **Group by**. It starts collapsed
each time the editor opens.
- The collapsed header summarizes the current saved or draft configuration, for example
**3 details · Git changes**, **2 details · Relative time**, **Details hidden · Pull request status**, or
**Details hidden · Nothing**.
- Expanding the section exposes one master **Details row** toggle, the detail fields, and a
**Right side** choice.
- The details row supports these configurable fields:
- Relative time
- Repository
- Pull request number
- Each detail field has a visibility control and a drag handle. Dragging changes the field order.
Keyboard users can reorder the same fields without a pointer.
- Turning off **Details row** hides the complete under-title metadata area. This includes the three
configurable fields, plugin task-row metadata, queued-prompt and WIP-queue indicators, and debug
poll-mode data. The title row and its badges remain visible.
- **Right side** offers **Git changes**, **Relative time**, **Pull request status**, and **Nothing**.
- The current layout is the default: all three detail fields are visible in their current order,
the details row is enabled, and Git changes appear on the right.
## Display rules
- Relative time keeps the view's current time meaning. It uses the last update time by default. A
view sorted by last activity uses the last activity time, with the last update time as fallback.
- When relative time is selected on the right, the row does not repeat relative time in the details
row. The editor keeps the field's saved position and visibility and marks it as shown on the
right. It returns to the details row when the right-side choice changes.
- When the task list is grouped by repository, a visible repository detail remains suppressed
because the group heading already provides that value.
- Pull request number and pull request status can appear together. The number is metadata. The
status is the existing provider indicator.
- Selecting pull request status on the right moves the existing GitHub, GitLab, or registered
provider indicator from the title area. It does not create a duplicate indicator.
- A missing value does not reserve empty space. For example, a task without a pull request shows no
pull request number or trailing status gap.
- **Nothing** removes the trailing data. The task action menu remains available.
- Passive trailing values can yield to the task action menu on hover or keyboard focus, as Git
changes do now. An interactive pull request status remains reachable while the menu is open. The
menu appears beside it and does not cover its pointer or keyboard target.
## Editor behavior
- A presentation edit previews immediately in the active task list and creates the existing saved-
view draft.
- **Save**, **Save as...**, and **Discard** use the existing view workflow. Saving overwrites the
active view, saving as creates an independent view, and discarding restores the saved layout.
- Opening or closing the **Task row** section is temporary interface state. It does not create a
draft, mark the view as changed, or persist.
- The section always starts collapsed when the desktop popover or mobile drawer opens.
- The field order stays stable when a field is hidden. Re-enabling the field restores it at its
previous position.
## Data model and persistence
The user-settings representation adds one optional `task_row` object to each saved sidebar view
and its draft:
```json
{
"details_enabled": true,
"detail_order": ["relative_time", "repository", "pull_request_number"],
"visible_details": ["relative_time", "repository", "pull_request_number"],
"trailing": "git_changes"
}
```
The other trailing values are `relative_time`, `change_request_status`, and `none`.
- The backend-owned user settings remain the durable source. No local-storage preference is added.
- The saved view and its matching draft carry the complete presentation object.
- A client normalizes omitted, null, or malformed presentation data before rendering.
- Normalization ignores unknown fields, removes duplicates, and appends missing known detail fields
to the canonical order. It limits visible details to known fields.
- An absent object resolves to the current layout. This rule preserves old saved views and lets an
older client ignore an unknown future field when it reads the view.
- Existing optimistic save, rollback, active-view validation, and 50-view limit behavior do not
change.
See [ADR 0041](../../../decisions/0041-backend-owned-portable-user-settings.md) for ownership of
portable user settings.
## Responsive and accessible behavior
- Desktop keeps the view editor in its anchored popover with one internal vertical scroll area.
- Phone and tablet layouts present the same view editor in an inset bottom drawer. The drawer owns
one vertical scroll area, respects the bottom safe area, and returns focus to its trigger when it
closes.
- The mobile **Task row** header, switches, selection controls, and drag handles have at least a
44 by 44 CSS pixel touch target.
- Field reordering supports pointer, touch, and keyboard input. The order is exposed to assistive
technology, and a completed reorder receives an accessible announcement.
- The mobile task list keeps the row as its primary tap target. A passive pull request indicator
does not become a competing touch action.
- The editor and task rows do not cause document-level horizontal overflow at supported widths.
## Failure behavior
- A failed draft or save write restores the last confirmed saved views, active view, and draft. It
uses the existing sidebar-view error message.
- A failed or unavailable metadata source only omits that value. It does not change the saved
presentation setting.
- An unknown trailing value resolves to Git changes. A missing or malformed detail order resolves
to the canonical order. A valid empty `visible_details` list remains empty.
## Scenarios
- **GIVEN** an existing saved view without task-row settings, **WHEN** Kandev loads it after an
upgrade, **THEN** its rows keep the current details and Git changes layout.
- **GIVEN** the view editor opens, **WHEN** the user has not expanded **Task row**, **THEN** the
section uses one compact header and its open state does not make the view dirty.
- **GIVEN** the user hides repository and moves pull request number before relative time, **WHEN**
the active rows preview the draft, **THEN** the details row shows pull request number before
relative time and no repository value.
- **GIVEN** details are disabled, **WHEN** a task has plugin metadata, queued prompts, or WIP status,
**THEN** no under-title metadata row renders and the title row remains complete.
- **GIVEN** relative time is visible in details, **WHEN** the user selects relative time for the
right side, **THEN** each task shows one relative time value on the right and none in details.
- **GIVEN** pull request status is selected for the right side, **WHEN** a task has a linked change
request, **THEN** one provider status indicator appears on the right and remains keyboard
reachable beside the task menu.
- **GIVEN** a view is grouped by repository, **WHEN** repository is enabled in its details, **THEN**
the task rows omit the repeated repository while the saved field remains enabled.
- **GIVEN** the user saves, saves as, discards, reloads, or opens the view on another client,
**THEN** task-row settings follow the same result as the view's filters, sort, and grouping.
- **GIVEN** the mobile view editor is open, **WHEN** the user expands and reorders task-row fields,
**THEN** the drawer remains within the viewport, scrolls internally, respects the safe area, and
provides touch-sized controls.
## Out of scope
- Configuring the title, task-state icon, task color, issue badge, remote-executor badge, archived
badge, subtask toggle, or task action menu.
- Adding new metadata sources or changing provider status derivation.
- Applying this preference to Kanban cards or the `/tasks` rich task list.
- A global task-row preference outside saved sidebar views.
- A new cross-tab conflict model for full-array user-settings writes.
## Implementation plan
[Sidebar task row presentation plan](../../../plans/sidebar-task-row-presentation/plan.md)