fix: restore sidebar context for missing task routes (#2229)

This commit is contained in:
Carlos Florêncio
2026-08-03 22:24:39 +01:00
committed by GitHub
parent 5772fa86f0
commit 90da2d66f2
15 changed files with 789 additions and 12 deletions
+18 -2
View File
@@ -783,17 +783,33 @@ func webRuntimeConfig(debug bool, req *http.Request) webapp.RuntimeConfig {
}
func bootPayload(ctx context.Context, req *http.Request, p routeParams, route webapp.RouteClassification) webapp.BootPayload {
initialState := bootInitialState(ctx, req, p, route)
routeData := bootRouteData(ctx, req, p, route)
if route.Route == webapp.RouteTaskDetail && routeData == nil && canLoadTaskDetailFallback(req, p.authSvc) {
bootStateBuilder{p: p}.addHomeKanbanRouteState(ctx, req, initialState)
}
payload := webapp.NewBootPayload(
route,
webRuntimeConfig(p.devMode, req),
bootInitialState(ctx, req, p, route),
initialState,
)
payload.RouteData = bootRouteData(ctx, req, p, route)
payload.RouteData = routeData
payload.Plugins = bootActivePlugins(p)
payload.InterimSettingsInterlockToken = p.interimSettingsInterlockToken
return payload
}
func canLoadTaskDetailFallback(req *http.Request, authSvc *auth.Service) bool {
if authSvc == nil || authSvc.Mode() == auth.ModeDisabled {
return true
}
if req == nil {
return false
}
_, ok := authn.IdentityFromContext(req.Context())
return ok
}
// bootActivePlugins populates the boot payload's Plugins list from every
// active, UI-bundle-declaring plugin, per
// docs/plans/plugins/PLUGIN-API.md ("Loading model").
@@ -796,6 +796,161 @@ func TestBootRouteDataTaskDetailIncludesTaskPageData(t *testing.T) {
}
}
func TestBootPayloadMissingTaskFallsBackToHomeKanbanState(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
workspaces, err := harness.taskSvc.ListWorkspaces(ctx)
if err != nil || len(workspaces) == 0 {
t.Fatalf("ListWorkspaces: count=%d err=%v", len(workspaces), err)
}
workflows, err := harness.taskSvc.ListWorkflows(ctx, workspaces[0].ID, true)
if err != nil || len(workflows) == 0 {
t.Fatalf("ListWorkflows: count=%d err=%v", len(workflows), err)
}
steps, err := harness.workflowSvc.ListStepsByWorkflow(ctx, workflows[0].ID)
if err != nil || len(steps) == 0 {
t.Fatalf("ListStepsByWorkflow: count=%d err=%v", len(steps), err)
}
task, err := harness.taskSvc.CreateTask(ctx, &taskservice.CreateTaskRequest{
WorkspaceID: workspaces[0].ID,
WorkflowID: workflows[0].ID,
WorkflowStepID: steps[0].ID,
Title: "Visible sibling task",
})
if err != nil {
t.Fatalf("CreateTask: %v", err)
}
request := httptest.NewRequest(
http.MethodGet,
"/t/missing-task",
nil,
)
request.AddCookie(&http.Cookie{Name: activeWorkspaceCookie, Value: workspaces[0].ID})
route := webapp.ClassifyRoute("/t/missing-task")
payload := bootPayload(ctx, request, routeParams{
taskSvc: harness.taskSvc,
userCtrl: harness.userCtrl,
services: &Services{Workflow: harness.workflowSvc},
}, route)
if payload.RouteData != nil {
t.Fatalf("missing task route data = %#v, want nil", payload.RouteData)
}
workspacesState, ok := payload.InitialState["workspaces"].(map[string]any)
if !ok {
t.Fatalf("missing fallback workspaces state: %#v", payload.InitialState["workspaces"])
}
if got := workspacesState["activeId"]; got != workspaces[0].ID {
t.Fatalf("fallback active workspace = %v, want %q", got, workspaces[0].ID)
}
if _, ok := payload.InitialState["workflows"].(map[string]any); !ok {
t.Fatalf("missing fallback workflows state: %#v", payload.InitialState["workflows"])
}
if _, ok := payload.InitialState["repositories"].(map[string]any); !ok {
t.Fatalf("missing fallback repositories state: %#v", payload.InitialState["repositories"])
}
kanbanMulti, ok := payload.InitialState["kanbanMulti"].(map[string]any)
if !ok {
t.Fatalf("missing fallback kanban state: %#v", payload.InitialState["kanbanMulti"])
}
snapshots, ok := kanbanMulti["snapshots"].(map[string]any)
if !ok {
t.Fatalf("fallback kanban snapshots = %#v", kanbanMulti["snapshots"])
}
snapshot, ok := snapshots[workflows[0].ID].(map[string]any)
if !ok {
t.Fatalf("missing fallback workflow snapshot %q: %#v", workflows[0].ID, snapshots)
}
tasks, ok := snapshot["tasks"].([]map[string]any)
if !ok {
// JSON-safe boot state is assembled with []map[string]any, so this
// assertion protects the sidebar's task source without depending on
// JSON round-tripping in the test.
t.Fatalf("fallback workflow tasks = %#v", snapshot["tasks"])
}
if len(tasks) != 1 || tasks[0]["id"] != task.ID {
t.Fatalf("fallback workflow tasks = %#v, want task %q", tasks, task.ID)
}
}
func TestBootPayloadAnonymousMissingTaskDoesNotLoadHomeState(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
request := httptest.NewRequest(http.MethodGet, "/t/missing-task", nil)
route := webapp.ClassifyRoute("/t/missing-task")
payload := bootPayload(ctx, request, routeParams{
taskSvc: harness.taskSvc,
userCtrl: harness.userCtrl,
authSvc: newSSOTestAuthService(t),
services: &Services{Workflow: harness.workflowSvc},
}, route)
if payload.RouteData != nil {
t.Fatalf("anonymous missing task route data = %#v, want nil", payload.RouteData)
}
if _, ok := payload.InitialState["auth"]; !ok {
t.Fatal("anonymous auth-enabled bootstrap should include auth state")
}
for _, key := range []string{"workspaces", "workflows", "repositories", "kanbanMulti"} {
if _, ok := payload.InitialState[key]; ok {
t.Fatalf("anonymous auth-enabled bootstrap should not include %s state", key)
}
}
}
func TestBootPayloadValidTaskKeepsRouteSpecificState(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
workspaces, err := harness.taskSvc.ListWorkspaces(ctx)
if err != nil || len(workspaces) == 0 {
t.Fatalf("ListWorkspaces: count=%d err=%v", len(workspaces), err)
}
workflows, err := harness.taskSvc.ListWorkflows(ctx, workspaces[0].ID, true)
if err != nil || len(workflows) == 0 {
t.Fatalf("ListWorkflows: count=%d err=%v", len(workflows), err)
}
steps, err := harness.workflowSvc.ListStepsByWorkflow(ctx, workflows[0].ID)
if err != nil || len(steps) == 0 {
t.Fatalf("ListStepsByWorkflow: count=%d err=%v", len(steps), err)
}
task, err := harness.taskSvc.CreateTask(ctx, &taskservice.CreateTaskRequest{
WorkspaceID: workspaces[0].ID,
WorkflowID: workflows[0].ID,
WorkflowStepID: steps[0].ID,
Title: "Valid detail task",
})
if err != nil {
t.Fatalf("CreateTask: %v", err)
}
request := httptest.NewRequest(http.MethodGet, "/t/"+task.ID, nil)
route := webapp.ClassifyRoute("/t/" + task.ID)
payload := bootPayload(ctx, request, routeParams{
taskSvc: harness.taskSvc,
userCtrl: harness.userCtrl,
services: &Services{Workflow: harness.workflowSvc},
}, route)
if payload.RouteData == nil {
t.Fatal("valid task route data is nil")
}
detail, ok := payload.RouteData["taskDetail"].(map[string]any)
if !ok {
t.Fatalf("task detail route data = %#v", payload.RouteData["taskDetail"])
}
detailTask, ok := detail["task"].(taskdto.TaskDTO)
if !ok {
t.Fatalf("task detail task = %#v", detail["task"])
}
if detailTask.ID != task.ID {
t.Fatalf("task detail id = %q, want %q", detailTask.ID, task.ID)
}
if _, ok := payload.InitialState["workspaces"]; ok {
t.Fatal("valid task route should keep the lean initial state without home workspace data")
}
}
func TestBootTaskDetailMessagesProjectShellOutput(t *testing.T) {
harness := newBootStateTestHarness(t)
ctx := context.Background()
@@ -2525,6 +2525,10 @@ func (s *Service) stopTaskSessionForCoordinator(ctx context.Context, taskID, ses
if err != nil {
return false, err
}
// Detached teardown must not observe this operation as an in-flight
// cancellation. ScheduleTeardown starts a goroutine, so relying on the
// deferred release above makes the ordering scheduler-dependent.
endCancel()
if result.Changed && teardownClaimed {
result.ScheduleTeardown()
}
@@ -0,0 +1,32 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { StateProvider } from "@/components/state-provider";
import { TaskLoadErrorState } from "./task-page-content";
afterEach(cleanup);
function renderErrorState(activeId: string | null) {
render(
<StateProvider initialState={{ workspaces: { items: [], activeId } }}>
<TaskLoadErrorState />
</StateProvider>,
);
}
describe("TaskLoadErrorState", () => {
it("preserves the active workspace in the overview destination", () => {
renderErrorState("ws-1");
const link = screen.getByTestId("task-unavailable-overview-link");
expect(link.getAttribute("href")).toBe("/?home=overview&workspaceId=ws-1");
expect(link.className).toContain("min-h-11");
});
it("falls back to the unscoped overview when no workspace is active", () => {
renderErrorState(null);
expect(screen.getByTestId("task-unavailable-overview-link").getAttribute("href")).toBe(
"/?home=overview",
);
});
});
+23 -6
View File
@@ -2,6 +2,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { IconAlertTriangle } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import Link from "@/components/routing/app-link";
import { useTranslation } from "react-i18next";
import type { Repository, RepositoryScript, Task } from "@/lib/types/http";
import type { Terminal } from "@/hooks/domains/session/use-terminals";
import type { KanbanState } from "@/lib/state/slices";
@@ -14,6 +17,7 @@ import { useAppStore } from "@/components/state-provider";
import { useEnsureTaskSession } from "@/hooks/domains/session/use-ensure-task-session";
import { useExternalVcsFileLinkHydration } from "@/hooks/domains/workspace/use-external-vcs-file-link";
import { fetchTask } from "@/lib/api";
import { linkToTaskOverview } from "@/lib/links";
import { useTasks } from "@/hooks/use-tasks";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { useForegroundRefresh } from "@/hooks/use-foreground-refresh";
@@ -135,6 +139,8 @@ export function useMergedAgentState(
}
function TaskLoadingState() {
const { t } = useTranslation();
return (
<div
className="flex h-full min-h-0 w-full items-center justify-center bg-background px-4"
@@ -142,13 +148,16 @@ function TaskLoadingState() {
>
<div className="flex min-h-24 min-w-0 flex-col items-center justify-center gap-3 text-center text-sm text-muted-foreground">
<GridSpinner className="text-primary" />
<span>Loading task...</span>
<span>{t("common:taskLoading")}</span>
</div>
</div>
);
}
function TaskLoadErrorState() {
export function TaskLoadErrorState() {
const { t } = useTranslation();
const activeWorkspaceId = useAppStore((state) => state.workspaces.activeId);
return (
<div
className="flex h-full min-h-0 w-full items-center justify-center bg-background px-4"
@@ -157,11 +166,19 @@ function TaskLoadErrorState() {
<div className="flex min-h-24 max-w-sm min-w-0 flex-col items-center justify-center gap-3 text-center text-sm text-muted-foreground">
<IconAlertTriangle className="h-5 w-5 text-destructive" aria-hidden="true" />
<div className="space-y-1">
<div className="font-medium text-foreground">Task unavailable</div>
<div>
We could not load this task. It may have been deleted or you may not have access.
</div>
<div className="font-medium text-foreground">{t("common:taskUnavailable")}</div>
<div>{t("common:taskUnavailableDescription")}</div>
</div>
<Button
asChild
size="lg"
className="min-h-11 px-4 sm:min-h-9"
data-testid="task-unavailable-overview-link"
>
<Link href={linkToTaskOverview({ workspaceId: activeWorkspaceId ?? undefined })}>
{t("common:backToTaskOverview")}
</Link>
</Button>
</div>
</div>
);
@@ -117,4 +117,43 @@ test.describe("Mobile task loading state", () => {
await testPage.unroute(sessionPattern, sessionRoute);
}
});
test("returns to task overview from a missing task route", async ({
testPage,
apiClient,
seedData,
}) => {
const title = "Mobile missing route sibling";
await apiClient.createTask(seedData.workspaceId, title, {
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
});
await testPage.goto(`/t/missing-task-route-mobile?workspaceId=${seedData.workspaceId}`);
await expect(testPage.getByTestId("task-load-error-state")).toBeVisible({ timeout: 10_000 });
const overviewLink = testPage.getByTestId("task-unavailable-overview-link");
await expect(overviewLink).toBeVisible();
const linkBox = await overviewLink.boundingBox();
const viewport = testPage.viewportSize();
expect(linkBox).not.toBeNull();
expect(viewport).not.toBeNull();
if (linkBox && viewport) {
expect(linkBox.height).toBeGreaterThanOrEqual(44);
expect(linkBox.x).toBeGreaterThanOrEqual(0);
expect(linkBox.x + linkBox.width).toBeLessThanOrEqual(viewport.width + 1);
}
expect(
await testPage.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
).toBe(true);
await overviewLink.tap();
await expect(testPage).toHaveURL(
new RegExp(`/\\?home=overview&workspaceId=${seedData.workspaceId}`),
);
const mobile = new MobileKanbanPage(testPage);
await mobile.board.waitFor({ state: "visible", timeout: 10_000 });
await expect(mobile.taskCardByTitle(title)).toBeVisible({ timeout: 10_000 });
});
});
@@ -1,4 +1,5 @@
import { test, expect } from "../../fixtures/test-base";
import { SidebarTasksPage } from "../../pages/sidebar-tasks-page";
import { openBlockedTaskLoadingState } from "./task-loading-state-helpers";
test.describe("Task loading state", () => {
@@ -22,4 +23,28 @@ test.describe("Task loading state", () => {
await unblockTaskDetailRequest();
}
});
test("keeps sibling tasks available after a missing task route", async ({
testPage,
apiClient,
seedData,
}) => {
const sibling = await apiClient.createTask(seedData.workspaceId, "Missing route sibling", {
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
});
await testPage.goto(`/t/missing-task-route-desktop?workspaceId=${seedData.workspaceId}`);
await expect(testPage.getByTestId("task-load-error-state")).toBeVisible({ timeout: 10_000 });
await expect(testPage.getByTestId("task-unavailable-overview-link")).toBeVisible();
const sidebar = new SidebarTasksPage(testPage);
await expect(sidebar.row(sibling.id)).toBeVisible({ timeout: 10_000 });
await expect(testPage.getByText("No tasks yet.", { exact: true })).toHaveCount(0);
await sidebar.plainClick(sibling.id);
await expect(testPage).toHaveURL(new RegExp(`/t/${sibling.id}$`));
await expect(testPage.getByTestId("task-load-error-state")).toBeHidden({ timeout: 10_000 });
});
});
+4
View File
@@ -2,6 +2,7 @@
"aboutContextCompactionCount": "About inferred compaction count",
"agents": "Agents",
"automations": "Automations",
"backToTaskOverview": "Back to task overview",
"cancel": "Cancel",
"changelog": "Changelog",
"commandAgentsSettings": "Agents Settings",
@@ -72,6 +73,9 @@
"status": "Status",
"subtaskTitle": "Subtask title",
"system": "System",
"taskLoading": "Loading task...",
"taskUnavailable": "Task unavailable",
"taskUnavailableDescription": "We could not load this task. It may have been deleted or you may not have access.",
"title": "Title",
"unsavedChanges": "Unsaved changes",
"workspace": "Workspace",
+4
View File
@@ -2,6 +2,7 @@
"aboutContextCompactionCount": "Àƀōũţ ĩńƒēŕŕēď ćōḿƥàćţĩōń ćōũńţ",
"agents": "Àĝēńţś",
"automations": "Àũţōḿàţĩōńś",
"backToTaskOverview": "Ɓàćķ ţō ţàśķ ōvēŕvĩēŵ",
"cancel": "Ćàńćēĺ",
"changelog": "Ćĥàńĝēĺōĝ",
"commandAgentsSettings": "Àĝēńţś Śēţţĩńĝś",
@@ -72,6 +73,9 @@
"status": "Śţàţũś",
"subtaskTitle": "Śũƀţàśķ ţĩţĺē",
"system": "Śŷśţēḿ",
"taskLoading": "Ĺōàďĩńĝ ţàśķ...",
"taskUnavailable": "Ţàśķ ũńàvàĩĺàƀĺē",
"taskUnavailableDescription": "Ŵē ćōũĺď ńōţ ĺōàď ţĥĩś ţàśķ. Ĩţ ḿàŷ ĥàvē ƀēēń ďēĺēţēď ōŕ ŷōũ ḿàŷ ńōţ ĥàvē àććēśś.",
"title": "Ţĩţĺē",
"unsavedChanges": "Ũńśàvēď ćĥàńĝēś",
"workspace": "Ŵōŕķśƥàćē",
+21 -4
View File
@@ -8,6 +8,7 @@ import type { Task } from "@/lib/types/http";
const mocks = vi.hoisted(() => ({
fetchSessionDataForTask: vi.fn(),
}));
const KANBAN_TASK_SHELL_TEST_ID = "kanban-task-shell";
vi.mock("@/components/state-hydrator", () => ({
StateHydrator: () => <div data-testid="state-hydrator" />,
@@ -16,7 +17,7 @@ vi.mock("@/components/state-hydrator", () => ({
vi.mock("@/app/tasks/[id]/kanban-task-shell", () => ({
KanbanTaskShell: ({ task, taskId }: { task: Task | null; taskId: string }) => (
<div
data-testid="kanban-task-shell"
data-testid={KANBAN_TASK_SHELL_TEST_ID}
data-route-task-id={taskId}
data-task-id={task?.id ?? ""}
/>
@@ -75,7 +76,7 @@ describe("TaskDetailRoute", () => {
render(<TaskDetailRoute taskId="task-1" />);
expect(screen.queryByTestId("kanban-task-shell")).toBeNull();
expect(screen.queryByTestId(KANBAN_TASK_SHELL_TEST_ID)).toBeNull();
expect(screen.getByRole("status").textContent).toContain("Loading task");
expect(screen.getByRole("status").parentElement?.className).toContain("h-full");
expect(screen.getByRole("status").parentElement?.className).toContain("min-h-0");
@@ -85,7 +86,9 @@ describe("TaskDetailRoute", () => {
routeData.resolve(makeFetchedData());
await waitFor(() => {
expect(screen.getByTestId("kanban-task-shell").getAttribute("data-task-id")).toBe("task-1");
expect(screen.getByTestId(KANBAN_TASK_SHELL_TEST_ID).getAttribute("data-task-id")).toBe(
"task-1",
);
});
});
@@ -93,7 +96,21 @@ describe("TaskDetailRoute", () => {
render(<TaskDetailRoute taskId="task-1" initialData={makeFetchedData()} />);
expect(mocks.fetchSessionDataForTask).not.toHaveBeenCalled();
expect(screen.getByTestId("kanban-task-shell").getAttribute("data-task-id")).toBe("task-1");
expect(screen.getByTestId(KANBAN_TASK_SHELL_TEST_ID).getAttribute("data-task-id")).toBe(
"task-1",
);
expect(screen.getByTestId("state-hydrator")).toBeTruthy();
});
it("reaches the unavailable task shell when route data fails", async () => {
mocks.fetchSessionDataForTask.mockRejectedValueOnce(new Error("task not found"));
render(<TaskDetailRoute taskId="missing-task" />);
await waitFor(() => {
expect(screen.getByTestId(KANBAN_TASK_SHELL_TEST_ID)).toBeTruthy();
});
expect(screen.getByTestId(KANBAN_TASK_SHELL_TEST_ID).getAttribute("data-task-id")).toBe("");
expect(screen.queryByTestId("state-hydrator")).toBeNull();
});
});