mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
## Thinking Path > - Paperclip manages agents and the tasks they work on. > - Recovery should continue unfinished work when it is eligible. > - An active unanswered question is a persisted reason to wait for a person. > - Treating a later Retry as an answer makes the recovery sweep repeatedly request continuations that admission refuses. > - Provider-limit holds also produce one cancellation toast per task, even though provider work never started. > - This PR aligns recovery with persisted interaction status and presents these waits accurately. ## Linked Issues or Issue Description Refs: #20466. This addresses the question blocker presentation and automatic recovery loop; it preserves the existing interaction-resolution policy. Related work: #19420 schedules provider quota retries, and #21570 handles notices and reply ownership in agent chats. This change concerns assigned-task reconciliation, task/inbox status, and per-run cancellation toasts. **What happened?** The assigned-work sweep ignored pending interactions whenever a newer run carried `explicitUserContinuation`. Continuation admission still refused the pending question, so repeated sweeps recorded unsuccessful continuation attempts. The task could meanwhile show an older provider error as its current blocker. Separately, each pre-dispatch provider-limit hold generated a cancellation toast, and the one-hour fallback was described as a known reset and promised start time. **Expected behavior** Wait quietly while the question remains active under the shared interaction eligibility rules, then react to the existing resolution notification. Dismissed or historical ordinary questions remain answerable without blocking work; governed requests keep their gates. Show the current question on task and inbox surfaces. Keep provider failure history, suppress cancellation toasts for expected provider holds, and describe scheduled availability checks without promising the provider will accept work. **Steps to reproduce** 1. Leave an `ask_user_questions` interaction pending with `supersedeOnUserComment: false`. 2. Create a later failed/interrupted explicit Retry and run assigned-work reconciliation repeatedly. 3. Observe that the question remains pending while the sweep attempts fresh continuations. 4. Separately, let an agent with recent provider rate-limit evidence receive automatic task wakes without a reported reset time. ## What Changed - Remove inferred question supersession from both assigned-work fact loading and candidate selection. Use the existing active-interaction predicate consistently in those reads, fresh-continuation admission, and the task projection. Cover dismissed/historical ordinary questions, retained governed gates, repeated checks, idle workers, and the existing resolution notification. - Add the `question` interruption action, load active pending question IDs alongside approvals in one company-scoped query, and show that blocker on tasks and inbox rows. Preserve a supported manual Retry after a failed attempt, suppress duplicate actions for saved input, and keep other current user gates authoritative. This preserves the existing issue-detail SQL statement budget. Historical run failures remain intact. Refresh the shared source SDK input pin. - Suppress cancellation toasts specifically for cancelled `provider_limit_wait` runs. Label provider retry deadlines as availability rechecks, retain relative-time formatting, and record successful scheduling as an informational lifecycle event. - Document the wait contract in the continuation architecture guide. ## Verification - Demonstrated failing regressions before the implementation: continuation loop, task projection, task notice, cancellation toast, provider deadline wording, and deadline formatting. - Initial focused Vitest qualification: 642 tests passed across 14 files, using: ```sh pnpm exec vitest run \ server/src/__tests__/{assigned-work-invariant,assigned-work-recheck-idle,heartbeat-provider-limit-wait,task-interruption-query}.test.ts \ server/src/services/{task-interruption-presentation,execution-projection,fresh-continuation-fallback,issue-thread-interactions}.test.ts \ server/src/services/recovery/assigned-work-invariant.test.ts \ ui/src/{components/ExecutionBlockerNotice.test.tsx,context/LiveUpdatesProvider.test.ts,context/LiveUpdatesProvider.hook.test.tsx,lib/provider-limit-message.test.ts,pages/Inbox.test.tsx} ``` - `pnpm --filter @paperclipai/shared typecheck` — passed. - Review follow-up: 157 tests passed in `assigned-work-invariant`, `task-interruption-query`, and `fresh-continuation-fallback`; 575 passed in `task-interruption-query`, `assigned-work-recheck-idle`, `task-interruption-presentation`, `issue-question-context`, `issue-thread-interactions`, and `explicit-native-continuation` (the query file overlaps). The strengthened final dismissed/historical/governed projection regression also passed separately. - Final query-consolidation verification: 157 tests passed across five files, including the unchanged 64-statement issue-detail census and mixed approval/question batches: ```sh pnpm exec vitest run \ server/src/__tests__/{issue-detail-statements,task-interruption-query,assigned-work-invariant,assigned-work-recheck-idle}.test.ts \ server/src/services/task-interruption-presentation.test.ts ``` - `pnpm --filter @paperclipai/server typecheck` — passed, including test layers. - Manual-recovery follow-up: 204 tests passed across seven projection/recovery/notice suites, and all 104 Inbox tests passed. The lost-runner integration still starts exactly one run from a manual Retry and leaves the question unanswered. The saved-decision census verifies one decision batch query for a 41-task list, with at most three statements referencing interactions; the overall 64-statement issue-detail limit remains unchanged. - `pnpm --filter @paperclipai/ui typecheck` — passed. - `pnpm --filter @paperclipai/ui build` — passed. - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` — passed. - `pnpm verify` — exit 2: broader CI is required for changed global inputs. Focused tests and package checks supply local evidence; broad CI remains required. - `git diff --check` and a local secret/instance-data scan — passed. - Final CI on `1c16fe7c0d8`: [trusted CI workflow](https://github.com/paperclipai/paperclip/actions/runs/44650155842) passed, including all server shards, native-server verification, build, canary, e2e, release registry, and serialized suites. All PR checks are complete, with no failures; the branch is conflict-free. - Greptile reviewed the latest revision, `1c16fe7c0d8`, at 5/5 with no actionable findings or unresolved review threads. The focused tests cover genuine provider failures, live work and terminal tasks, unchanged task locks/retry delivery, preservation of historical failures, and question resolution waking the affected task while other active pending questions remain quiet. Review regressions also cover dismissed/historical ordinary questions retaining Retry and governed requests retaining their gates. No live task was retried or answered for validation. ## Risks - An active pending question now consistently blocks automatic assigned-work recovery. Shared interaction eligibility determines when ordinary conversation input becomes deferred or historical; governed requests retain their authority. Automatic recovery no longer infers that a newer Retry resolved an active question. - Manual Retry keeps its existing admission policy and recovery checks. The question notice preserves that supported action after a failed attempt without changing approval or credential authority; pending saved input prevents duplicate actions. - The shared interruption action gains `question`; the task and inbox consumers are updated together. The pending-question query returns only task IDs and uses the existing company/task/status index. - Provider cooldown policy, quotas, credentials, routing, cancellation history, and durable retry timing are unchanged. The actual provider can still return a rate limit at the recheck. - No migration is required. Existing large owner modules receive small localized changes; no code file crosses 1,000 lines. ## Model Used OpenAI `gpt-6.1-sol` through the Codex harness in T3 Code, xhigh reasoning effort, with code execution and tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either linked existing issues or described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
3718 lines
160 KiB
TypeScript
3718 lines
160 KiB
TypeScript
import { errorCodes, isTransientError } from "@/api/errors";
|
||
import { useQueryView } from "@/components/QueryView";
|
||
import { useCoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation";
|
||
import { useAccountBoundMutation } from "@/hooks/useAccountBoundMutation";
|
||
import { bindAccount } from "@/lib/account-scope";
|
||
import { useWarmTaskDetailCode } from "@/hooks/useWarmTaskDetailCode";
|
||
import { topTaskRefs, usePreloadTaskChats } from "../hooks/usePreloadTaskChats";
|
||
import { describeError } from "../api/errors";
|
||
import { useIssueRowDetails } from "../hooks/useIssueRowDetails";
|
||
import { IssueRowDetailsNotice } from "../components/IssueRowDetailsNotice";
|
||
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||
import { Link, useLocation, useNavigate } from "@/lib/router";
|
||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||
import { deriveOriginatingActor, INBOX_MINE_ISSUE_STATUS_FILTER, isHeartbeatRunVisibleInMine } from "@paperclipai/shared";
|
||
import { usePublishSharedQueryData, useSharedPollingQuery } from "@/hooks/useSharedPolling";
|
||
import { approvalsApi } from "../api/approvals";
|
||
import { accessApi } from "../api/access";
|
||
import { authApi } from "../api/auth";
|
||
import { ApiError } from "../api/client";
|
||
import { dashboardApi } from "../api/dashboard";
|
||
import { executionWorkspacesApi } from "../api/execution-workspaces";
|
||
import { issuesApi } from "../api/issues";
|
||
import { useSecondTick } from "../hooks/useSecondTick";
|
||
import { taskRetryNotStartedReason } from "../hooks/useTaskRetry";
|
||
import { agentsApi } from "../api/agents";
|
||
import { heartbeatsApi } from "../api/heartbeats";
|
||
import { instanceSettingsApi } from "../api/instanceSettings";
|
||
import { projectsApi } from "../api/projects";
|
||
import {
|
||
BLOCKED_GROUP_OPTIONS,
|
||
BLOCKED_SORT_OPTIONS,
|
||
type BlockedInboxGroupBy,
|
||
type BlockedInboxSort,
|
||
} from "../lib/blockedInbox";
|
||
import { useCompany } from "../context/CompanyContext";
|
||
import { useToastActions } from "../context/ToastContext";
|
||
import { useBreadcrumbs } from "../context/BreadcrumbContext";
|
||
import { useSidebar } from "../context/SidebarContext";
|
||
import { queryKeys } from "../lib/queryKeys";
|
||
import { buildMineRevealSources, mineRevealSourcesQueryKey, readMineRevealSources, type MineRevealSources } from "../lib/inbox-mine-reveal-sources";
|
||
import { useDialogActions } from "../context/DialogContext";
|
||
import { useIssueExternalObjectSummaries } from "../hooks/useIssueExternalObjects";
|
||
import {
|
||
applyIssueFilters,
|
||
countActiveIssueFilters,
|
||
defaultIssueFilterState,
|
||
normalizeIssueFilterState,
|
||
type IssueFilterState,
|
||
} from "../lib/issue-filters";
|
||
import { collectLiveIssueIds, collectSubtreeLiveCounts, issueWaitingOf } from "../lib/liveIssueIds";
|
||
import { formatAssigneeUserLabel } from "../lib/assignees";
|
||
import { buildCompanyUserLabelMap, buildCompanyUserProfileMap } from "../lib/company-members";
|
||
import {
|
||
armIssueDetailInboxQuickArchive,
|
||
createIssueDetailLocationState,
|
||
createIssueDetailPath,
|
||
rememberIssueDetailLocationState,
|
||
withIssueDetailHeaderSeed,
|
||
} from "../lib/issueDetailBreadcrumb";
|
||
import { prefetchIssueDetailForNavigation } from "../lib/issueDetailCache";
|
||
import {
|
||
hasBlockingShortcutDialog,
|
||
isKeyboardShortcutTextInputTarget,
|
||
resolveInboxUndoArchiveKeyAction,
|
||
shouldBlurPageSearchOnEnter,
|
||
shouldBlurPageSearchOnEscape,
|
||
} from "../lib/keyboardShortcuts";
|
||
import {
|
||
resolveInboxIssueBlockerAttention,
|
||
resolveIssueRunningDescendantCount,
|
||
} from "../lib/inbox-live-descendants";
|
||
import {
|
||
beginLocalInboxArchive,
|
||
boundLocalInboxArchive,
|
||
cancelInboxIssueQueries,
|
||
clearLocalInboxArchive,
|
||
confirmLocalInboxArchive,
|
||
invalidateInboxIssueQueries,
|
||
invalidateTaskArchiveQueries,
|
||
getIssuePresenceInActiveInboxCaches,
|
||
removeIssueFromInboxCaches,
|
||
restoreIssueToInboxCaches,
|
||
snapshotInboxIssueCaches,
|
||
type InboxIssueCacheSnapshot,
|
||
useLocalInboxArchiveIssueIds,
|
||
} from "../lib/inboxArchiveCache";
|
||
import { EmptyState } from "../components/EmptyState";
|
||
import { CollectionToolbar, type CollectionToolbarProps } from "../components/CollectionToolbar";
|
||
import { IssueGroupHeader } from "../components/IssueGroupHeader";
|
||
import { PageSkeleton } from "../components/PageSkeleton";
|
||
import {
|
||
InboxIssueMetaLeading,
|
||
InboxIssueTrailingColumns,
|
||
IssueColumnPicker,
|
||
issueActivityText,
|
||
issueActivityTimestamp,
|
||
issueTrailingColumns,
|
||
} from "../components/IssueColumns";
|
||
import { IssueFiltersPopover } from "../components/IssueFiltersPopover";
|
||
import { InboxArchiveButton, IssueRow } from "../components/IssueRow";
|
||
import { BlockedInboxView } from "../components/BlockedInboxView";
|
||
import { SwipeToArchive } from "../components/SwipeToArchive";
|
||
import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
|
||
import { Inbox as LegacyInbox } from "./LegacyInbox";
|
||
|
||
import { StatusIcon } from "../components/StatusIcon";
|
||
import { cn } from "../lib/utils";
|
||
import { StatusBadge } from "../components/StatusBadge";
|
||
import { approvalLabel, defaultTypeIcon, typeIcon } from "../components/ApprovalPayload";
|
||
import { timeAgo } from "../lib/timeAgo";
|
||
import { Button } from "@/components/ui/button";
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
} from "@/components/ui/dialog";
|
||
import { Separator } from "@/components/ui/separator";
|
||
import { Tabs } from "@/components/ui/tabs";
|
||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||
import {
|
||
Inbox as InboxIcon,
|
||
AlertTriangle,
|
||
Check,
|
||
ChevronRight,
|
||
ArrowUpDown,
|
||
Layers,
|
||
Plus,
|
||
XCircle,
|
||
X,
|
||
RotateCcw,
|
||
UserPlus,
|
||
Search,
|
||
ListTree,
|
||
} from "lucide-react";
|
||
import { Input } from "@/components/ui/input";
|
||
import { PageTabBar } from "../components/PageTabBar";
|
||
import type { Approval, HeartbeatRun, InboxMineSnapshot, Issue, JoinRequest } from "@paperclipai/shared";
|
||
import {
|
||
ACTIONABLE_APPROVAL_STATUSES,
|
||
DEFAULT_INBOX_ISSUE_COLUMNS,
|
||
buildGroupedInboxSections,
|
||
buildInboxIssueGroupCreateDefaults,
|
||
buildInboxKeyboardNavEntries,
|
||
getAvailableInboxIssueColumns,
|
||
getInboxWorkItemKey,
|
||
getApprovalsForTab,
|
||
getArchivedInboxSearchIssues,
|
||
getInboxKeyboardSelectionIndex,
|
||
getInboxWorkItems,
|
||
getInboxSearchSupplementIssues,
|
||
getLatestFailedRunsByAgent,
|
||
collectReferencedExecutionWorkspaceIds,
|
||
matchesInboxIssueSearch,
|
||
getRecentTouchedIssues,
|
||
isInboxEntityDismissed,
|
||
isMineInboxTab,
|
||
loadCollapsedInboxGroupKeys,
|
||
loadCollapsedInboxParentIds,
|
||
loadInboxNesting,
|
||
loadInboxWorkItemGroupBy,
|
||
normalizeInboxIssueColumns,
|
||
resolveInboxNestingEnabled,
|
||
shouldResetInboxWorkspaceGrouping,
|
||
resolveIssueWorkspaceName,
|
||
resolveInboxSelectionIndex,
|
||
saveCollapsedInboxGroupKeys,
|
||
saveCollapsedInboxParentIds,
|
||
saveInboxNesting,
|
||
saveInboxWorkItemGroupBy,
|
||
type InboxWorkspaceGroupingOptions,
|
||
type InboxApprovalFilter,
|
||
type InboxCategoryFilter,
|
||
type InboxFilterPreferences,
|
||
type InboxIssueColumn,
|
||
type InboxKeyboardNavEntry,
|
||
saveLastInboxTab,
|
||
shouldShowCompanyAlerts,
|
||
shouldShowInboxSection,
|
||
type InboxGroupedSection,
|
||
type InboxTab,
|
||
type InboxWorkItem,
|
||
type InboxWorkItemGroupBy,
|
||
INBOX_FILTER_PREFERENCES_KEY_PREFIX,
|
||
INBOX_ISSUE_COLUMNS_KEY,
|
||
inboxNavEntryTask,
|
||
} from "../lib/inbox";
|
||
import { useDismissedInboxAlerts, useInboxDismissals, useReadInboxItems } from "../hooks/useInboxBadge";
|
||
import { useInboxSortAttention } from "../hooks/useInboxSortAttention";
|
||
import {
|
||
captureInboxOrderPin,
|
||
reconcileInboxOrderPin,
|
||
type InboxOrderPin,
|
||
} from "../lib/inboxOrderPin";
|
||
import {
|
||
loadTaskCollectionPreferences,
|
||
saveTaskCollectionPreferences,
|
||
type TaskCollectionPreferenceLocation,
|
||
} from "../lib/task-collection-preferences";
|
||
import {
|
||
taskDateGroup,
|
||
taskDateGroupSeparator,
|
||
type TaskDateGroup,
|
||
} from "../lib/task-date-groups";
|
||
import { taskStatusIconProps } from "@/lib/task-status-presentation";
|
||
|
||
const INBOX_HEARTBEAT_RUN_LIMIT = 200;
|
||
const INBOX_ISSUE_LIST_LIMIT = 100;
|
||
const INBOX_HOT_PATH_STALE_MS = 30_000;
|
||
// Stable fallback so memos over unloaded or disabled issue reads do not rerun on every render.
|
||
const NO_ISSUES: Issue[] = [];
|
||
const NO_JOIN_REQUESTS: JoinRequest[] = [];
|
||
/** Bounds an optional read that can hold task rows hidden; a timeout reveals rows and retries in the background. */
|
||
const INBOX_OPTIONAL_READ_TIMEOUT_MS = 10_000;
|
||
const INBOX_COLLECTION_KEY = "inbox";
|
||
|
||
type StreamlinedInboxViewState = InboxFilterPreferences & {
|
||
showDateGroupSeparators: boolean;
|
||
};
|
||
|
||
const DEFAULT_INBOX_FILTER_PREFERENCES: StreamlinedInboxViewState = {
|
||
allCategoryFilter: "everything",
|
||
allApprovalFilter: "all",
|
||
issueFilters: { ...defaultIssueFilterState },
|
||
showDateGroupSeparators: true,
|
||
};
|
||
|
||
function normalizeInboxCollectionViewState(value: unknown): StreamlinedInboxViewState {
|
||
const candidate = value && typeof value === "object"
|
||
? value as Partial<StreamlinedInboxViewState>
|
||
: {};
|
||
const category = candidate.allCategoryFilter;
|
||
const approval = candidate.allApprovalFilter;
|
||
return {
|
||
allCategoryFilter:
|
||
category === "issues_i_touched"
|
||
|| category === "join_requests"
|
||
|| category === "approvals"
|
||
|| category === "failed_runs"
|
||
|| category === "alerts"
|
||
? category
|
||
: "everything",
|
||
allApprovalFilter: approval === "actionable" || approval === "resolved" ? approval : "all",
|
||
issueFilters: {
|
||
...normalizeIssueFilterState(candidate.issueFilters),
|
||
// The filter menu no longer offers Workspace. Drop a saved selection so
|
||
// it cannot keep hiding tasks. A task-link workspace query is applied
|
||
// by the task list after this load.
|
||
workspaces: [],
|
||
},
|
||
showDateGroupSeparators: candidate.showDateGroupSeparators !== false,
|
||
};
|
||
}
|
||
|
||
function inboxCollectionPreferenceLocation(
|
||
companyId: string | null | undefined,
|
||
): TaskCollectionPreferenceLocation {
|
||
return {
|
||
companyId: companyId ?? "__unscoped__",
|
||
collectionKey: INBOX_COLLECTION_KEY,
|
||
legacyViewStorageKey: companyId
|
||
? `${INBOX_FILTER_PREFERENCES_KEY_PREFIX}:${companyId}`
|
||
: undefined,
|
||
legacyColumnsStorageKey: INBOX_ISSUE_COLUMNS_KEY,
|
||
};
|
||
}
|
||
|
||
function loadInboxCollectionPreferences(companyId: string | null | undefined) {
|
||
return loadTaskCollectionPreferences({
|
||
...inboxCollectionPreferenceLocation(companyId),
|
||
defaultViewState: DEFAULT_INBOX_FILTER_PREFERENCES,
|
||
defaultColumns: DEFAULT_INBOX_ISSUE_COLUMNS,
|
||
normalizeViewState: normalizeInboxCollectionViewState,
|
||
normalizeColumns: (value) => Array.isArray(value)
|
||
? normalizeInboxIssueColumns(value)
|
||
: DEFAULT_INBOX_ISSUE_COLUMNS,
|
||
});
|
||
}
|
||
|
||
export { InboxIssueMetaLeading, InboxIssueTrailingColumns } from "../components/IssueColumns";
|
||
export { IssueGroupHeader as InboxGroupHeader } from "../components/IssueGroupHeader";
|
||
type SectionKey =
|
||
| "work_items"
|
||
| "alerts";
|
||
|
||
/** A flat navigation entry for keyboard j/k traversal that includes expanded children. */
|
||
type NavEntry = InboxKeyboardNavEntry;
|
||
// Stable identity for a nav row, resilient to the numeric index shifting when
|
||
// the inbox reshapes (archive/poll). Used to re-anchor both the keyboard
|
||
// selection and the hovered row across list refreshes.
|
||
const navEntryKey = (entry: NavEntry | undefined): string | null =>
|
||
!entry
|
||
? null
|
||
: entry.type === "top"
|
||
? `top:${entry.itemKey}`
|
||
: entry.type === "child"
|
||
? `child:${entry.issueId}`
|
||
: `group:${entry.groupKey}`;
|
||
type CreatorOption = {
|
||
id: string;
|
||
label: string;
|
||
kind: "agent" | "user";
|
||
searchText?: string;
|
||
};
|
||
|
||
function firstNonEmptyLine(value: string | null | undefined): string | null {
|
||
if (!value) return null;
|
||
const line = value.split("\n").map((chunk) => chunk.trim()).find(Boolean);
|
||
return line ?? null;
|
||
}
|
||
|
||
function runFailureMessage(run: HeartbeatRun): string {
|
||
return firstNonEmptyLine(run.error) ?? firstNonEmptyLine(run.stderrExcerpt) ?? "Run exited with an error.";
|
||
}
|
||
|
||
function approvalStatusLabel(status: Approval["status"]): string {
|
||
return status.replaceAll("_", " ");
|
||
}
|
||
|
||
function readIssueIdFromRun(run: HeartbeatRun): string | null {
|
||
if (run.issueId) return run.issueId;
|
||
const context = run.contextSnapshot;
|
||
if (!context) return null;
|
||
|
||
const issueId = context["issueId"];
|
||
if (typeof issueId === "string" && issueId.length > 0) return issueId;
|
||
|
||
const taskId = context["taskId"];
|
||
if (typeof taskId === "string" && taskId.length > 0) return taskId;
|
||
|
||
return null;
|
||
}
|
||
|
||
function nonEmptyLabel(value: string | null | undefined): string | null {
|
||
const trimmed = value?.trim();
|
||
return trimmed ? trimmed : null;
|
||
}
|
||
|
||
export function formatJoinRequestInboxLabel(
|
||
joinRequest: Pick<
|
||
JoinRequest,
|
||
"requestType" | "agentName" | "requestEmailSnapshot" | "requestingUserId"
|
||
> & {
|
||
requesterUser?: {
|
||
name: string | null;
|
||
email: string | null;
|
||
} | null;
|
||
},
|
||
) {
|
||
if (joinRequest.requestType !== "human") {
|
||
return `Agent join request${joinRequest.agentName ? `: ${joinRequest.agentName}` : ""}`;
|
||
}
|
||
|
||
const requesterName = nonEmptyLabel(joinRequest.requesterUser?.name);
|
||
const requesterEmail =
|
||
nonEmptyLabel(joinRequest.requesterUser?.email) ??
|
||
nonEmptyLabel(joinRequest.requestEmailSnapshot);
|
||
const requesterId = nonEmptyLabel(joinRequest.requestingUserId);
|
||
|
||
if (requesterName && requesterEmail) return `${requesterName} (${requesterEmail})`;
|
||
if (requesterEmail) return requesterEmail;
|
||
if (requesterName) return requesterName;
|
||
if (requesterId) return requesterId;
|
||
return "Human join request";
|
||
}
|
||
|
||
|
||
type NonIssueUnreadState = "visible" | "fading" | "hidden" | null;
|
||
|
||
// Rows outside SwipeToArchive (non-archivable tabs/sections) still need the
|
||
// hover-follows-selection band that SwipeToArchive's surface normally paints.
|
||
function InboxRowSurface({ selected, children }: { selected: boolean; children: ReactNode }) {
|
||
return <div className={cn(selected && "rounded-lg bg-accent/50")}>{children}</div>;
|
||
}
|
||
|
||
export function FailedRunInboxRow({
|
||
run,
|
||
issueById,
|
||
agentName: linkedAgentName,
|
||
issueLinkState,
|
||
onDismiss,
|
||
onRetry,
|
||
isRetrying,
|
||
unreadState = null,
|
||
onMarkRead,
|
||
onArchive,
|
||
archiveDisabled,
|
||
selected = false,
|
||
className,
|
||
}: {
|
||
run: HeartbeatRun;
|
||
issueById: Map<string, Issue>;
|
||
agentName: string | null;
|
||
issueLinkState: unknown;
|
||
onDismiss: () => void;
|
||
onRetry: () => void;
|
||
isRetrying: boolean;
|
||
unreadState?: NonIssueUnreadState;
|
||
onMarkRead?: () => void;
|
||
onArchive?: () => void;
|
||
archiveDisabled?: boolean;
|
||
selected?: boolean;
|
||
className?: string;
|
||
}) {
|
||
const issueId = readIssueIdFromRun(run);
|
||
const issue = issueId ? issueById.get(issueId) ?? null : null;
|
||
const interruption = issue?.interruption;
|
||
useSecondTick(interruption?.state === "retry_scheduled");
|
||
const retrySeconds = Math.max(0, Math.ceil((Date.parse(interruption?.nextRetryAt ?? "") - Date.now()) / 1000));
|
||
const displayError = isRetrying ? "Thinking"
|
||
: interruption?.retryWait ? interruption.retryWait.message
|
||
: interruption?.state === "working" ? "Thinking"
|
||
: interruption?.state === "retry_scheduled" ? `Trying again in ${retrySeconds}s…`
|
||
: interruption?.state === "failed" ? "Couldn’t finish this attempt. Your message is saved."
|
||
: interruption?.state === "waiting_for_user" ? ({
|
||
approval: "Approval required", question: "Respond to the pending question", reconnect: "Reconnect account", assign_agent: "Assign an agent", choose_model: "Choose a supported model",
|
||
resume: "Work is paused", budget: "Budget limit reached",
|
||
project_access: "Agent needs project access",
|
||
confirm_owner_stop: "Confirm the previous server stopped",
|
||
confirm_run_stopped: "Confirm the previous run stopped",
|
||
unblock: "The agent needs your help",
|
||
}[interruption.userAction ?? "resume"]) : runFailureMessage(run);
|
||
const retryAvailable = !interruption || (interruption.canRetry && interruption.retryAction !== "move_forward");
|
||
const showUnreadSlot = unreadState !== null;
|
||
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
|
||
|
||
return (
|
||
<div className={cn(
|
||
"group py-2.5 pl-4 pr-2 sm:py-2",
|
||
className,
|
||
)}>
|
||
<div className="flex items-start gap-2 sm:items-center">
|
||
{showUnreadSlot ? (
|
||
<span className="hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center">
|
||
{showUnreadDot ? (
|
||
<button
|
||
type="button"
|
||
onClick={onMarkRead}
|
||
className={cn(
|
||
"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",
|
||
"hover:bg-blue-500/20",
|
||
)}
|
||
aria-label="Mark as read"
|
||
>
|
||
<span className={cn(
|
||
"block h-2 w-2 rounded-full transition-opacity duration-300",
|
||
"bg-blue-600 dark:bg-blue-400",
|
||
unreadState === "fading" ? "opacity-0" : "opacity-100",
|
||
)} />
|
||
</button>
|
||
) : (
|
||
<span className="inline-flex h-4 w-4" aria-hidden="true" />
|
||
)}
|
||
</span>
|
||
) : null}
|
||
<Link
|
||
to={issueId ? `/issues/${issueId}` : `/agents/${run.agentId}/runs/${run.id}`}
|
||
className={cn(
|
||
"flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",
|
||
selected ? "hover:bg-transparent" : "hover:bg-accent/50",
|
||
)}
|
||
>
|
||
{!showUnreadSlot && <span className="hidden h-2 w-2 shrink-0 sm:inline-flex" aria-hidden="true" />}
|
||
<span className="hidden h-3.5 w-3.5 shrink-0 sm:inline-flex" aria-hidden="true" />
|
||
<span className="mt-0.5 shrink-0 rounded-md bg-red-500/20 p-1.5 sm:mt-0">
|
||
<XCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
|
||
</span>
|
||
<span className="min-w-0 flex-1">
|
||
<span className="line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none">
|
||
{issue ? (
|
||
<>
|
||
<span className="font-mono text-muted-foreground mr-1.5">
|
||
{issue.identifier ?? issue.id.slice(0, 8)}
|
||
</span>
|
||
{issue.title}
|
||
</>
|
||
) : (
|
||
<>Failed run{linkedAgentName ? ` — ${linkedAgentName}` : ""}</>
|
||
)}
|
||
</span>
|
||
<span className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||
{!interruption && <StatusBadge status={run.status} />}
|
||
{linkedAgentName && issue ? <span>{linkedAgentName}</span> : null}
|
||
<span className="truncate max-w-(--sz-300px)">{displayError}</span>
|
||
<span>{timeAgo(run.createdAt)}</span>
|
||
</span>
|
||
</span>
|
||
</Link>
|
||
<div className="hidden shrink-0 items-center gap-2 sm:flex">
|
||
{onArchive ? (
|
||
<InboxArchiveButton onArchive={onArchive} disabled={archiveDisabled} />
|
||
) : null}
|
||
{retryAvailable && <Button
|
||
type="button"
|
||
variant="outline"
|
||
size="sm"
|
||
className="h-8 shrink-0 px-2.5"
|
||
onClick={onRetry}
|
||
disabled={isRetrying}
|
||
>
|
||
<RotateCcw className="mr-1.5 h-3.5 w-3.5" />
|
||
{isRetrying ? "Thinking" : "Retry"}
|
||
</Button>}
|
||
{!showUnreadSlot && (
|
||
<button
|
||
type="button"
|
||
onClick={onDismiss}
|
||
className="rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||
aria-label="Dismiss"
|
||
>
|
||
<X className="h-4 w-4" />
|
||
</button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
<div className="mt-3 flex gap-2 sm:hidden">
|
||
{retryAvailable && <Button
|
||
type="button"
|
||
variant="outline"
|
||
size="sm"
|
||
className="h-8 shrink-0 px-2.5"
|
||
onClick={onRetry}
|
||
disabled={isRetrying}
|
||
>
|
||
<RotateCcw className="mr-1.5 h-3.5 w-3.5" />
|
||
{isRetrying ? "Thinking" : "Retry"}
|
||
</Button>}
|
||
{!showUnreadSlot && (
|
||
<button
|
||
type="button"
|
||
onClick={onDismiss}
|
||
className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||
aria-label="Dismiss"
|
||
>
|
||
<X className="h-4 w-4" />
|
||
</button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ApprovalInboxRow({
|
||
approval,
|
||
requesterName,
|
||
onApprove,
|
||
onReject,
|
||
isPending,
|
||
unreadState = null,
|
||
onMarkRead,
|
||
onArchive,
|
||
archiveDisabled,
|
||
selected = false,
|
||
className,
|
||
}: {
|
||
approval: Approval;
|
||
requesterName: string | null;
|
||
onApprove: () => void;
|
||
onReject: () => void;
|
||
isPending: boolean;
|
||
unreadState?: NonIssueUnreadState;
|
||
onMarkRead?: () => void;
|
||
onArchive?: () => void;
|
||
archiveDisabled?: boolean;
|
||
selected?: boolean;
|
||
className?: string;
|
||
}) {
|
||
const Icon = typeIcon[approval.type] ?? defaultTypeIcon;
|
||
const label = approvalLabel(approval.type, approval.payload as Record<string, unknown> | null);
|
||
const showResolutionButtons =
|
||
approval.type !== "budget_override_required" &&
|
||
ACTIONABLE_APPROVAL_STATUSES.has(approval.status);
|
||
const showUnreadSlot = unreadState !== null;
|
||
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
|
||
|
||
return (
|
||
<div className={cn(
|
||
"group py-2.5 pl-4 pr-2 sm:py-2",
|
||
className,
|
||
)}>
|
||
<div className="flex items-start gap-2 sm:items-center">
|
||
{showUnreadSlot ? (
|
||
<span className="hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center">
|
||
{showUnreadDot ? (
|
||
<button
|
||
type="button"
|
||
onClick={onMarkRead}
|
||
className={cn(
|
||
"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",
|
||
"hover:bg-blue-500/20",
|
||
)}
|
||
aria-label="Mark as read"
|
||
>
|
||
<span className={cn(
|
||
"block h-2 w-2 rounded-full transition-opacity duration-300",
|
||
"bg-blue-600 dark:bg-blue-400",
|
||
unreadState === "fading" ? "opacity-0" : "opacity-100",
|
||
)} />
|
||
</button>
|
||
) : (
|
||
<span className="inline-flex h-4 w-4" aria-hidden="true" />
|
||
)}
|
||
</span>
|
||
) : null}
|
||
<Link
|
||
to={`/approvals/${approval.id}`}
|
||
className={cn(
|
||
"flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",
|
||
selected ? "hover:bg-transparent" : "hover:bg-accent/50",
|
||
)}
|
||
>
|
||
{!showUnreadSlot && <span className="hidden h-2 w-2 shrink-0 sm:inline-flex" aria-hidden="true" />}
|
||
<span className="hidden h-3.5 w-3.5 shrink-0 sm:inline-flex" aria-hidden="true" />
|
||
<span className="mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0">
|
||
<Icon className="h-4 w-4 text-muted-foreground" />
|
||
</span>
|
||
<span className="min-w-0 flex-1">
|
||
<span className="line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none">
|
||
{label}
|
||
</span>
|
||
<span className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||
<span className="capitalize">{approvalStatusLabel(approval.status)}</span>
|
||
{requesterName ? <span>requested by {requesterName}</span> : null}
|
||
<span>updated {timeAgo(approval.updatedAt)}</span>
|
||
</span>
|
||
</span>
|
||
</Link>
|
||
{(onArchive || showResolutionButtons) ? (
|
||
<div className="hidden shrink-0 items-center gap-2 sm:flex">
|
||
{onArchive ? (
|
||
<InboxArchiveButton onArchive={onArchive} disabled={archiveDisabled} />
|
||
) : null}
|
||
{showResolutionButtons ? (
|
||
<>
|
||
<Button
|
||
size="sm"
|
||
className="h-8 min-w-(--sz-64px) justify-center bg-green-700 px-3 text-white hover:bg-green-600"
|
||
onClick={onApprove}
|
||
disabled={isPending}
|
||
>
|
||
Approve
|
||
</Button>
|
||
<Button
|
||
variant="destructive"
|
||
size="sm"
|
||
className="h-8 min-w-(--sz-64px) justify-center px-3"
|
||
onClick={onReject}
|
||
disabled={isPending}
|
||
>
|
||
Reject
|
||
</Button>
|
||
</>
|
||
) : null}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
{showResolutionButtons ? (
|
||
<div className="mt-3 flex gap-2 sm:hidden">
|
||
<Button
|
||
size="sm"
|
||
className="h-8 min-w-(--sz-64px) justify-center bg-green-700 px-3 text-white hover:bg-green-600"
|
||
onClick={onApprove}
|
||
disabled={isPending}
|
||
>
|
||
Approve
|
||
</Button>
|
||
<Button
|
||
variant="destructive"
|
||
size="sm"
|
||
className="h-8 min-w-(--sz-64px) justify-center px-3"
|
||
onClick={onReject}
|
||
disabled={isPending}
|
||
>
|
||
Reject
|
||
</Button>
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function JoinRequestInboxRow({
|
||
joinRequest,
|
||
onApprove,
|
||
onReject,
|
||
isPending,
|
||
unreadState = null,
|
||
onMarkRead,
|
||
onArchive,
|
||
archiveDisabled,
|
||
selected = false,
|
||
className,
|
||
}: {
|
||
joinRequest: JoinRequest;
|
||
onApprove: () => void;
|
||
onReject: () => void;
|
||
isPending: boolean;
|
||
unreadState?: NonIssueUnreadState;
|
||
onMarkRead?: () => void;
|
||
onArchive?: () => void;
|
||
archiveDisabled?: boolean;
|
||
selected?: boolean;
|
||
className?: string;
|
||
}) {
|
||
const label = formatJoinRequestInboxLabel(joinRequest);
|
||
const showUnreadSlot = unreadState !== null;
|
||
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
|
||
|
||
return (
|
||
<div className={cn(
|
||
"group py-2.5 pl-4 pr-2 sm:py-2",
|
||
className,
|
||
)}>
|
||
<div className="flex items-start gap-2 sm:items-center">
|
||
{showUnreadSlot ? (
|
||
<span className="hidden sm:inline-flex h-4 w-4 shrink-0 items-center justify-center self-center">
|
||
{showUnreadDot ? (
|
||
<button
|
||
type="button"
|
||
onClick={onMarkRead}
|
||
className={cn(
|
||
"inline-flex h-4 w-4 items-center justify-center rounded-full transition-colors",
|
||
"hover:bg-blue-500/20",
|
||
)}
|
||
aria-label="Mark as read"
|
||
>
|
||
<span className={cn(
|
||
"block h-2 w-2 rounded-full transition-opacity duration-300",
|
||
"bg-blue-600 dark:bg-blue-400",
|
||
unreadState === "fading" ? "opacity-0" : "opacity-100",
|
||
)} />
|
||
</button>
|
||
) : (
|
||
<span className="inline-flex h-4 w-4" aria-hidden="true" />
|
||
)}
|
||
</span>
|
||
) : null}
|
||
<div className="flex min-w-0 flex-1 items-start gap-2">
|
||
{!showUnreadSlot && <span className="hidden h-2 w-2 shrink-0 sm:inline-flex" aria-hidden="true" />}
|
||
<span className="hidden h-3.5 w-3.5 shrink-0 sm:inline-flex" aria-hidden="true" />
|
||
<span className="mt-0.5 shrink-0 rounded-md bg-muted p-1.5 sm:mt-0">
|
||
<UserPlus className="h-4 w-4 text-muted-foreground" />
|
||
</span>
|
||
<span className="min-w-0 flex-1">
|
||
<span className="line-clamp-2 text-sm font-medium sm:truncate sm:line-clamp-none">
|
||
{label}
|
||
</span>
|
||
<span className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||
<span>requested {timeAgo(joinRequest.createdAt)} from IP {joinRequest.requestIp}</span>
|
||
{joinRequest.adapterType && <span>adapter: {joinRequest.adapterType}</span>}
|
||
</span>
|
||
</span>
|
||
</div>
|
||
<div className="hidden shrink-0 items-center gap-2 sm:flex">
|
||
{onArchive ? (
|
||
<InboxArchiveButton onArchive={onArchive} disabled={archiveDisabled} />
|
||
) : null}
|
||
<Button
|
||
size="sm"
|
||
className="h-8 bg-green-700 px-3 text-white hover:bg-green-600"
|
||
onClick={onApprove}
|
||
disabled={isPending}
|
||
>
|
||
Approve
|
||
</Button>
|
||
<Button
|
||
variant="destructive"
|
||
size="sm"
|
||
className="h-8 px-3"
|
||
onClick={onReject}
|
||
disabled={isPending}
|
||
>
|
||
Reject
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
<div className="mt-3 flex gap-2 sm:hidden">
|
||
<Button
|
||
size="sm"
|
||
className="h-8 bg-green-700 px-3 text-white hover:bg-green-600"
|
||
onClick={onApprove}
|
||
disabled={isPending}
|
||
>
|
||
Approve
|
||
</Button>
|
||
<Button
|
||
variant="destructive"
|
||
size="sm"
|
||
className="h-8 px-3"
|
||
onClick={onReject}
|
||
disabled={isPending}
|
||
>
|
||
Reject
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function InboxCollectionToolbar({
|
||
streamlined,
|
||
context,
|
||
search,
|
||
controls,
|
||
feedback,
|
||
ariaLabel,
|
||
}: CollectionToolbarProps & { streamlined: boolean }) {
|
||
if (streamlined) {
|
||
return (
|
||
<CollectionToolbar
|
||
className={ariaLabel === "Tasks controls" ? "mobile-task-toolbar" : undefined}
|
||
ariaLabel={ariaLabel}
|
||
context={context}
|
||
search={search}
|
||
controls={controls}
|
||
feedback={feedback}
|
||
/>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<div role="toolbar" aria-label={ariaLabel} className="space-y-2">
|
||
{search ? <div className="sm:hidden">{search}</div> : null}
|
||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||
{context}
|
||
<div className="flex items-center gap-2">
|
||
{search ? <div className="hidden sm:block">{search}</div> : null}
|
||
{controls}
|
||
</div>
|
||
</div>
|
||
{feedback}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* PAP-670: the inbox stopped being its own page and became the "My work" half
|
||
* of Tasks. `Tasks` hosts this component and drives it through these props, so
|
||
* every inbox behaviour (unread state, archive, date groups, the mixed
|
||
* approval / failed-run / join-request rows) survives the merge by construction
|
||
* rather than being reimplemented on the task list.
|
||
*
|
||
* With no props it is still the standalone `/inbox/*` page, which the legacy
|
||
* (non-streamlined) shell continues to use.
|
||
*/
|
||
export interface InboxSurfaceProps {
|
||
/** Which view to render. Falls back to the last path segment when absent. */
|
||
tab?: InboxTab;
|
||
/** Replaces the inbox tab bar in the toolbar's context slot. */
|
||
toolbarContext?: ReactNode;
|
||
/** Breadcrumb and back-link label; "Inbox" when standalone, "Tasks" when hosted. */
|
||
surfaceLabel?: string;
|
||
}
|
||
|
||
export function Inbox(props: InboxSurfaceProps = {}) {
|
||
const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
|
||
const coordinator = useCoordinatorPresentation();
|
||
return streamlinedUiEnabled || coordinator ? <StreamlinedInbox {...props} /> : <LegacyInbox />;
|
||
}
|
||
|
||
function StreamlinedInbox({
|
||
tab: tabOverride,
|
||
toolbarContext,
|
||
surfaceLabel = "Inbox",
|
||
}: InboxSurfaceProps) {
|
||
const streamlinedUiEnabled = true;
|
||
const { selectedCompanyId } = useCompany();
|
||
const { setBreadcrumbs } = useBreadcrumbs();
|
||
const { openNewIssue } = useDialogActions();
|
||
const { isMobile } = useSidebar();
|
||
const navigate = useNavigate();
|
||
const { pushToast } = useToastActions();
|
||
const location = useLocation();
|
||
const queryClient = useQueryClient();
|
||
const [actionError, setActionError] = useState<string | null>(null);
|
||
const { data: experimentalSettings, isLoading: isSettingsLoading } = useQuery({
|
||
queryKey: queryKeys.instance.experimentalSettings,
|
||
queryFn: () => instanceSettingsApi.getExperimental(),
|
||
});
|
||
const experimentalSettingsLoaded = experimentalSettings !== undefined;
|
||
const [searchQuery, setSearchQuery] = useState("");
|
||
const normalizedSearchQuery = searchQuery.trim();
|
||
const [filterPreferences, setFilterPreferences] = useState<StreamlinedInboxViewState>(
|
||
() => loadInboxCollectionPreferences(selectedCompanyId).viewState,
|
||
);
|
||
const [groupBy, setGroupBy] = useState<InboxWorkItemGroupBy>(() => loadInboxWorkItemGroupBy());
|
||
const [blockedGroupBy, setBlockedGroupBy] = useState<BlockedInboxGroupBy>("none");
|
||
const [blockedSortBy, setBlockedSortBy] = useState<BlockedInboxSort>("most_recent");
|
||
const [visibleIssueColumns, setVisibleIssueColumns] = useState<InboxIssueColumn[]>(
|
||
() => loadInboxCollectionPreferences(selectedCompanyId).columns,
|
||
);
|
||
const { dismissed: dismissedAlerts, dismiss: dismissAlert } = useDismissedInboxAlerts();
|
||
const { readItems, markRead: markItemRead, markUnread: markItemUnread } = useReadInboxItems();
|
||
const { allCategoryFilter, allApprovalFilter, issueFilters } = filterPreferences;
|
||
|
||
const pathSegment = location.pathname.split("/").pop() ?? "mine";
|
||
const pathTab: InboxTab =
|
||
pathSegment === "mine"
|
||
|| pathSegment === "recent"
|
||
|| pathSegment === "all"
|
||
|| pathSegment === "unread"
|
||
|| pathSegment === "blocked"
|
||
? pathSegment
|
||
: "mine";
|
||
const tab: InboxTab = tabOverride ?? pathTab;
|
||
const canArchiveFromTab = isMineInboxTab(tab);
|
||
const isTasksUnread = surfaceLabel === "Tasks" && tab === "unread";
|
||
const issueLinkState = useMemo(
|
||
() =>
|
||
createIssueDetailLocationState(
|
||
surfaceLabel,
|
||
`${location.pathname}${location.search}${location.hash}`,
|
||
"inbox",
|
||
),
|
||
[surfaceLabel, location.pathname, location.search, location.hash],
|
||
);
|
||
|
||
const { data: session, isLoading: isSessionLoading } = useQuery({
|
||
queryKey: queryKeys.auth.session,
|
||
queryFn: () => authApi.getSession(),
|
||
});
|
||
const currentUserId = session?.user.id ?? session?.session.userId ?? null;
|
||
const canArchiveTaskFromTab = canArchiveFromTab || (isTasksUnread && !!currentUserId);
|
||
const mineContextQueryKey = [...queryKeys.issues.list(selectedCompanyId!), "mine-context", currentUserId] as const;
|
||
const { data: mineSnapshot } = useQuery<InboxMineSnapshot>({ queryKey: mineContextQueryKey, enabled: false });
|
||
// On a returning visit the saved query cache restores Mine's snapshot and the
|
||
// approvals, join requests and dismissals it showed. Those stand in until the
|
||
// reads answer, so rows show without waiting on the network.
|
||
const revealSourcesQueryKey = mineRevealSourcesQueryKey(selectedCompanyId!, currentUserId);
|
||
const { data: savedRevealSourcesData } = useQuery<MineRevealSources>({ queryKey: revealSourcesQueryKey, enabled: false });
|
||
const savedRevealSources = tab === "mine" && mineSnapshot
|
||
? readMineRevealSources(savedRevealSourcesData, currentUserId, selectedCompanyId) : null;
|
||
const {
|
||
dismissals: inboxDismissals,
|
||
dismissedAtByKey,
|
||
dismiss: dismissInboxItem,
|
||
isLoading: isDismissalsLoading,
|
||
hasServerData: hasServerDismissals,
|
||
error: dismissalsError,
|
||
} = useInboxDismissals(selectedCompanyId, { fallback: savedRevealSources?.dismissals });
|
||
|
||
|
||
const { data: agents, isLoading: isAgentsLoading } = useQuery({
|
||
queryKey: queryKeys.agents.list(selectedCompanyId!),
|
||
queryFn: () => agentsApi.list(selectedCompanyId!),
|
||
enabled: !!selectedCompanyId,
|
||
});
|
||
|
||
const { data: projects, isLoading: isProjectsLoading } = useQuery({
|
||
queryKey: queryKeys.projects.list(selectedCompanyId!, { includeArchived: true }),
|
||
queryFn: () => projectsApi.list(selectedCompanyId!, { includeArchived: true }),
|
||
enabled: !!selectedCompanyId,
|
||
});
|
||
const { data: labels } = useQuery({
|
||
queryKey: queryKeys.issues.labels(selectedCompanyId!),
|
||
queryFn: () => issuesApi.listLabels(selectedCompanyId!),
|
||
enabled: !!selectedCompanyId,
|
||
});
|
||
const isolatedWorkspacesEnabled = experimentalSettings?.enableIsolatedWorkspaces === true;
|
||
const externalObjectsEnabled = experimentalSettings?.enableExternalObjects === true;
|
||
|
||
useEffect(() => {
|
||
setBreadcrumbs([{ label: surfaceLabel }]);
|
||
}, [setBreadcrumbs, surfaceLabel]);
|
||
|
||
useEffect(() => {
|
||
saveLastInboxTab(tab);
|
||
setSelectedIndex(-1);
|
||
setSearchQuery("");
|
||
}, [tab]);
|
||
|
||
const previousSelectedCompanyIdRef = useRef<string | null>(selectedCompanyId);
|
||
useEffect(() => {
|
||
if (previousSelectedCompanyIdRef.current !== selectedCompanyId) {
|
||
previousSelectedCompanyIdRef.current = selectedCompanyId;
|
||
const preferences = loadInboxCollectionPreferences(selectedCompanyId);
|
||
setFilterPreferences(preferences.viewState);
|
||
setVisibleIssueColumns(preferences.columns);
|
||
setCollapsedGroupKeys(loadCollapsedInboxGroupKeys(selectedCompanyId));
|
||
setCollapsedInboxParents(loadCollapsedInboxParentIds(selectedCompanyId));
|
||
}
|
||
}, [selectedCompanyId]);
|
||
|
||
const {
|
||
data: serverApprovals,
|
||
isLoading: isApprovalsLoading,
|
||
failureCount: approvalsFailureCount,
|
||
error: approvalsError,
|
||
} = useQuery({
|
||
queryKey: queryKeys.approvals.list(selectedCompanyId!),
|
||
queryFn: ({ signal }) =>
|
||
approvalsApi.list(selectedCompanyId!, undefined, { signal, timeoutMs: INBOX_OPTIONAL_READ_TIMEOUT_MS }),
|
||
enabled: !!selectedCompanyId,
|
||
});
|
||
|
||
const {
|
||
data: serverJoinRequests,
|
||
isLoading: isJoinRequestsLoading,
|
||
failureCount: joinRequestsFailureCount,
|
||
error: joinRequestsError,
|
||
} = useQuery({
|
||
queryKey: queryKeys.access.joinRequests(selectedCompanyId!),
|
||
queryFn: async ({ signal }) => {
|
||
try {
|
||
return await accessApi.listJoinRequests(selectedCompanyId!, "pending_approval", undefined, {
|
||
signal,
|
||
timeoutMs: INBOX_OPTIONAL_READ_TIMEOUT_MS,
|
||
});
|
||
} catch (err) {
|
||
if (err instanceof ApiError && (err.status === 403 || err.status === 401)) {
|
||
return [];
|
||
}
|
||
throw err;
|
||
}
|
||
},
|
||
enabled: !!selectedCompanyId,
|
||
});
|
||
|
||
// Saved values stand in while a read is pending or after a transient failure;
|
||
// a refusal (403/404) or a server answer replaces them.
|
||
const savedStandsIn = (data: unknown, error: unknown) =>
|
||
data === undefined && savedRevealSources !== null && (!error || isTransientError(error));
|
||
const approvalsFromSaved = savedStandsIn(serverApprovals, approvalsError);
|
||
const joinRequestsFromSaved = savedStandsIn(serverJoinRequests, joinRequestsError);
|
||
const approvals = approvalsFromSaved ? savedRevealSources!.approvals : serverApprovals;
|
||
const joinRequests = serverJoinRequests ?? (joinRequestsFromSaved ? savedRevealSources!.joinRequests : NO_JOIN_REQUESTS);
|
||
|
||
// Save what Mine shows for the next visit. A complete record needs a server
|
||
// answer from every source. Once one exists, each answer replaces its part at
|
||
// once, and a refusal (401/403/404) empties it, so a reload never shows what
|
||
// the server has since refused while another read is still pending.
|
||
useEffect(() => {
|
||
if (tab !== "mine" || !selectedCompanyId || !currentUserId || !mineSnapshot) return;
|
||
const key = mineRevealSourcesQueryKey(selectedCompanyId, currentUserId);
|
||
const saved = readMineRevealSources(queryClient.getQueryData(key), currentUserId, selectedCompanyId);
|
||
const refused = (error: unknown) => !!error && !isTransientError(error);
|
||
const part = <T,>(server: T[] | undefined, error: unknown, previous: T[] | undefined) =>
|
||
server ?? (refused(error) ? [] : previous);
|
||
const nextApprovals = part(serverApprovals, approvalsError, saved?.approvals);
|
||
const nextJoinRequests = part(serverJoinRequests, joinRequestsError, saved?.joinRequests);
|
||
const nextDismissals = part(hasServerDismissals ? inboxDismissals : undefined, dismissalsError, saved?.dismissals);
|
||
if (!nextApprovals || !nextJoinRequests || !nextDismissals) return;
|
||
const next = buildMineRevealSources({
|
||
userId: currentUserId, companyId: selectedCompanyId, approvals: nextApprovals, joinRequests: nextJoinRequests,
|
||
dismissals: nextDismissals, failedRunIds: mineSnapshot.failureRuns.map((run) => run.id),
|
||
});
|
||
// Each write schedules a save of the query cache; skip unchanged values.
|
||
if (JSON.stringify(queryClient.getQueryData(key)) === JSON.stringify(next)) return;
|
||
queryClient.setQueryData(key, next);
|
||
}, [tab, selectedCompanyId, currentUserId, mineSnapshot, serverApprovals, approvalsError, serverJoinRequests, joinRequestsError,
|
||
hasServerDismissals, inboxDismissals, dismissalsError, queryClient]);
|
||
|
||
const dashboardQueryKey = queryKeys.dashboard(selectedCompanyId!);
|
||
const sharedDashboard = useSharedPollingQuery({
|
||
companyId: selectedCompanyId,
|
||
resourceKey: "dashboard",
|
||
queryKey: dashboardQueryKey,
|
||
enabled: !!selectedCompanyId && tab === "all",
|
||
});
|
||
const { data: dashboard, isLoading: isDashboardLoading, dataUpdatedAt: dashboardUpdatedAt } = useQuery({
|
||
queryKey: dashboardQueryKey,
|
||
queryFn: () => dashboardApi.summary(selectedCompanyId!),
|
||
enabled: !!selectedCompanyId && tab === "all",
|
||
});
|
||
usePublishSharedQueryData(sharedDashboard, dashboard, dashboardUpdatedAt);
|
||
|
||
const mineIssuesQuery = useQuery({
|
||
queryKey: [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId] as const,
|
||
queryFn: async ({ signal }) => {
|
||
const snapshot = await issuesApi.inboxMine(selectedCompanyId!, { signal });
|
||
if (snapshot.userId !== currentUserId) {
|
||
void queryClient.invalidateQueries({ queryKey: queryKeys.auth.session });
|
||
throw new ApiError("Your account changed. Refresh the inbox.", 409, { error: "account_changed" });
|
||
}
|
||
queryClient.setQueryData(mineContextQueryKey, snapshot);
|
||
return snapshot.issues as Issue[];
|
||
},
|
||
enabled: !!selectedCompanyId && !!currentUserId && tab === "mine",
|
||
refetchOnMount: mineSnapshot ? undefined : "always",
|
||
refetchOnWindowFocus: false,
|
||
staleTime: mineSnapshot ? INBOX_HOT_PATH_STALE_MS : 0,
|
||
// A successful aggregate can still omit a failed source. React Query's
|
||
// error retries do not run for that 200 response, so retry those sources.
|
||
refetchInterval: () => {
|
||
const snapshot = queryClient.getQueryData<InboxMineSnapshot>(mineContextQueryKey);
|
||
return [snapshot?.failureError, snapshot?.contextError].some(error =>
|
||
error && isTransientError(new ApiError(error.message, error.status, null))) ? 5_000 : false;
|
||
},
|
||
});
|
||
const { data: mineIssuesRaw = NO_ISSUES, isLoading: isMineIssuesLoading, error: mineIssuesError } = mineIssuesQuery;
|
||
const mineIssuesView = useQueryView(mineIssuesQuery);
|
||
const mineIssuesQueryKey = [...queryKeys.issues.listMineByMe(selectedCompanyId!), "index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId] as const;
|
||
// Mine owns one coherent response: broadcasting only its task array would
|
||
// refresh that array while another tab retained stale parent/failure context.
|
||
// Each tab uses the authenticated aggregate read; the server coalesces it.
|
||
|
||
const touchedIssuesQueryKey = [
|
||
...(isTasksUnread ? queryKeys.issues.listUnreadTouchedByMe(selectedCompanyId!) : queryKeys.issues.listTouchedByMe(selectedCompanyId!)),
|
||
"index", "with-routine-executions", "live-descendant-summary", INBOX_ISSUE_LIST_LIMIT, currentUserId,
|
||
] as const;
|
||
const touchedIssuesQuery = useQuery({
|
||
queryKey: touchedIssuesQueryKey,
|
||
queryFn: () =>
|
||
issuesApi.listCompact(selectedCompanyId!, {
|
||
touchedByUserId: "me",
|
||
inboxArchivedByUserId: isTasksUnread ? "me" : undefined,
|
||
status: INBOX_MINE_ISSUE_STATUS_FILTER,
|
||
projection: "index",
|
||
sortField: "updated",
|
||
sortDir: "desc",
|
||
includeRoutineExecutions: true,
|
||
includeLiveDescendantSummary: true,
|
||
limit: INBOX_ISSUE_LIST_LIMIT,
|
||
}).then((rows) => rows as Issue[]),
|
||
enabled: !!selectedCompanyId && (tab !== "mine" && tab !== "blocked" || normalizedSearchQuery.length > 0),
|
||
refetchOnWindowFocus: false,
|
||
staleTime: INBOX_HOT_PATH_STALE_MS,
|
||
});
|
||
const { data: touchedIssuesRaw = NO_ISSUES, isLoading: isTouchedIssuesLoading, error: touchedIssuesError, dataUpdatedAt: touchedIssuesUpdatedAt } = touchedIssuesQuery;
|
||
const touchedIssuesView = useQueryView(touchedIssuesQuery);
|
||
const sharedTouchedIssues = useSharedPollingQuery<Issue[]>({
|
||
companyId: selectedCompanyId,
|
||
resourceKey: isTasksUnread ? "inbox:unread-touched-issues" : "inbox:touched-issues",
|
||
queryKey: touchedIssuesQueryKey,
|
||
enabled: !!selectedCompanyId && (tab !== "mine" && tab !== "blocked" || normalizedSearchQuery.length > 0),
|
||
});
|
||
usePublishSharedQueryData(sharedTouchedIssues, touchedIssuesRaw, touchedIssuesUpdatedAt);
|
||
|
||
const { data: otherHeartbeatRuns, isLoading: isOtherRunsLoading, error: otherRunsError } = useQuery({
|
||
queryKey: [...queryKeys.heartbeats(selectedCompanyId!), "inbox-failures", INBOX_HEARTBEAT_RUN_LIMIT],
|
||
queryFn: () => heartbeatsApi.list(selectedCompanyId!, undefined, INBOX_HEARTBEAT_RUN_LIMIT, { summary: true, latestFailuresOnly: true }),
|
||
enabled: !!selectedCompanyId && tab !== "mine",
|
||
refetchOnWindowFocus: false,
|
||
staleTime: INBOX_HOT_PATH_STALE_MS,
|
||
});
|
||
const heartbeatRuns = tab === "mine" ? mineSnapshot?.failureRuns : otherHeartbeatRuns;
|
||
const isRunsLoading = tab === "mine" ? !!currentUserId && !mineSnapshot && !mineIssuesError : isOtherRunsLoading;
|
||
const runsError = tab === "mine" && mineSnapshot?.failureError
|
||
? new ApiError(mineSnapshot.failureError.message, mineSnapshot.failureError.status, null) : tab === "mine" ? null : otherRunsError;
|
||
const bundledContextIds = useMemo(() => new Set(tab === "mine" && mineSnapshot ? [
|
||
...mineSnapshot.issues.map((issue) => issue.parentId).filter((id): id is string => Boolean(id)),
|
||
...mineSnapshot.failureRuns.map(readIssueIdFromRun).filter((id): id is string => Boolean(id)),
|
||
] : []), [tab, mineSnapshot]);
|
||
const { parentContextIds, failureContextIds, contextIssueIds } = useMemo(() => {
|
||
const sourceIssues = tab === "mine" ? mineIssuesRaw : touchedIssuesRaw;
|
||
const loadedIds = new Set(sourceIssues.map((issue) => issue.id));
|
||
// Failure cards need interruption state even when their task is already in
|
||
// the index. Parent captions only need index metadata.
|
||
const failureIds = new Set((heartbeatRuns ?? []).map(readIssueIdFromRun)
|
||
.filter((id): id is string => Boolean(id))
|
||
.filter((id) => !bundledContextIds.has(id)));
|
||
const parentIds = new Set(sourceIssues.map((issue) => issue.parentId)
|
||
.filter((id): id is string => Boolean(id))
|
||
.filter((id) => !loadedIds.has(id) && !failureIds.has(id) && !bundledContextIds.has(id)));
|
||
return {
|
||
parentContextIds: [...parentIds].sort(),
|
||
failureContextIds: [...failureIds].sort(),
|
||
contextIssueIds: new Set([...parentIds, ...failureIds]),
|
||
};
|
||
}, [tab, mineIssuesRaw, touchedIssuesRaw, heartbeatRuns, bundledContextIds]);
|
||
const needsIssueContext = !!selectedCompanyId && contextIssueIds.size > 0 && tab !== "blocked"
|
||
&& (tab !== "mine" || !!mineSnapshot || !!mineIssuesError);
|
||
const {
|
||
data: issueContext,
|
||
isLoading: isContextIssuesLoading,
|
||
isPlaceholderData: isContextIssuesPlaceholder,
|
||
error: extraContextIssuesError,
|
||
} = useQuery<{
|
||
companyId: string | null;
|
||
userId: string | null;
|
||
issues: Issue[];
|
||
failureIssueIds: string[];
|
||
}>({
|
||
queryKey: [...queryKeys.issues.list(selectedCompanyId!), "row-context", "parent-index-with-failure-state", parentContextIds, failureContextIds, currentUserId],
|
||
placeholderData: (previous) => needsIssueContext && previous?.companyId === selectedCompanyId && previous.userId === currentUserId
|
||
? { ...previous, issues: previous.issues.filter((issue) => contextIssueIds.has(issue.id)) }
|
||
: undefined,
|
||
queryFn: async ({ signal }) => {
|
||
const loadContext = async (ids: string[], projection: "index" | "rows") => {
|
||
const result: Issue[] = [];
|
||
for (let offset = 0; offset < ids.length; offset += 100) {
|
||
result.push(...await issuesApi.listCompact(selectedCompanyId!, {
|
||
ids: ids.slice(offset, offset + 100), projection, limit: 100,
|
||
includeRoutineExecutions: true,
|
||
}, { signal }) as Issue[]);
|
||
}
|
||
return result;
|
||
};
|
||
const [parents, failures] = await Promise.all([
|
||
loadContext(parentContextIds, "index"),
|
||
loadContext(failureContextIds, "rows"),
|
||
]);
|
||
// A completed failure read also establishes absence for filtered/missing
|
||
// tasks. Parent-only placeholders cannot supply this coverage.
|
||
return { companyId: selectedCompanyId, userId: currentUserId, issues: [...parents, ...failures], failureIssueIds: failureContextIds };
|
||
},
|
||
enabled: needsIssueContext,
|
||
});
|
||
const contextIssuesError = extraContextIssuesError ?? (tab === "mine" && mineSnapshot?.contextError
|
||
? new ApiError(mineSnapshot.contextError.message, mineSnapshot.contextError.status, null) : null);
|
||
const contextIssues = useMemo(() => {
|
||
if (tab !== "mine" || !mineSnapshot) return issueContext?.issues ?? [];
|
||
const sourceIds = new Set(mineIssuesRaw.map((issue) => issue.id));
|
||
const parentIds = new Set(mineIssuesRaw.map((issue) => issue.parentId));
|
||
return [
|
||
...mineSnapshot.issues.filter((issue) => !sourceIds.has(issue.id) && parentIds.has(issue.id)),
|
||
...mineSnapshot.contextIssues.filter((issue) => parentIds.has(issue.id) || mineSnapshot.failureIssueIds.includes(issue.id)),
|
||
...(issueContext?.issues ?? []),
|
||
] as Issue[];
|
||
}, [tab, mineSnapshot, mineIssuesRaw, issueContext]);
|
||
const knownFailureContextIds = useMemo(() => new Set([
|
||
...(tab === "mine" ? mineSnapshot?.failureIssueIds ?? [] : []), ...(issueContext?.failureIssueIds ?? []),
|
||
]), [tab, mineSnapshot, issueContext]);
|
||
const issues = useMemo(() => [...mineIssuesRaw, ...touchedIssuesRaw, ...contextIssues], [mineIssuesRaw, touchedIssuesRaw, contextIssues]);
|
||
const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);
|
||
const sharedLiveRuns = useSharedPollingQuery({
|
||
companyId: selectedCompanyId,
|
||
resourceKey: "live-runs",
|
||
queryKey: liveRunsQueryKey,
|
||
enabled: !!selectedCompanyId,
|
||
// Event-sourced via LiveUpdatesProvider (GitHub issue 9627); no interval poll needed.
|
||
refetchInterval: false,
|
||
leaderOnly: true,
|
||
});
|
||
const { data: liveRuns, isLoading: isLiveRunsLoading, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({
|
||
queryKey: liveRunsQueryKey,
|
||
queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),
|
||
enabled: sharedLiveRuns.enabled,
|
||
refetchInterval: sharedLiveRuns.refetchInterval,
|
||
});
|
||
usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);
|
||
const {
|
||
data: companyMembers,
|
||
isLoading: isMembersLoading,
|
||
failureCount: membersFailureCount,
|
||
} = useQuery({
|
||
queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
|
||
queryFn: ({ signal }) =>
|
||
accessApi.listUserDirectory(selectedCompanyId!, { signal, timeoutMs: INBOX_OPTIONAL_READ_TIMEOUT_MS }),
|
||
enabled: !!selectedCompanyId,
|
||
});
|
||
const [archivingIssueIds, setArchivingIssueIds] = useState<Set<string>>(new Set());
|
||
const [undoableArchiveIssueIds, setUndoableArchiveIssueIds] = useState<string[]>([]);
|
||
const [unarchivingIssueIds, setUnarchivingIssueIds] = useState<Set<string>>(new Set());
|
||
const guardedArchiveIssueIds = useLocalInboxArchiveIssueIds(selectedCompanyId);
|
||
const locallyArchivedIssueIds = useMemo(() => {
|
||
const issueIds = new Set(guardedArchiveIssueIds);
|
||
for (const issueId of undoableArchiveIssueIds) issueIds.add(issueId);
|
||
for (const issueId of archivingIssueIds) issueIds.add(issueId);
|
||
for (const issueId of unarchivingIssueIds) issueIds.delete(issueId);
|
||
return issueIds;
|
||
}, [archivingIssueIds, guardedArchiveIssueIds, undoableArchiveIssueIds, unarchivingIssueIds]);
|
||
|
||
const companyUserLabelMap = useMemo(
|
||
() => buildCompanyUserLabelMap(companyMembers?.users),
|
||
[companyMembers?.users],
|
||
);
|
||
const companyUserProfileMap = useMemo(
|
||
() => buildCompanyUserProfileMap(companyMembers?.users),
|
||
[companyMembers?.users],
|
||
);
|
||
|
||
const mineIssues = useMemo(
|
||
() => getRecentTouchedIssues(mineIssuesRaw).filter((issue) => !locallyArchivedIssueIds.has(issue.id)),
|
||
[locallyArchivedIssueIds, mineIssuesRaw],
|
||
);
|
||
const touchedIssues = useMemo(
|
||
() => getRecentTouchedIssues(touchedIssuesRaw).filter((issue) => !locallyArchivedIssueIds.has(issue.id)),
|
||
[locallyArchivedIssueIds, touchedIssuesRaw],
|
||
);
|
||
const sourceSearchIds = useMemo(() => [...new Set([...mineIssuesRaw, ...touchedIssuesRaw].map((issue) => issue.id))].sort(), [mineIssuesRaw, touchedIssuesRaw]);
|
||
const sourceSearchQuery = useQuery<Issue[]>({
|
||
queryKey: [...queryKeys.issues.list(selectedCompanyId!), "inbox-source-search", normalizedSearchQuery, sourceSearchIds],
|
||
queryFn: async ({ signal }) => {
|
||
const matches: Issue[] = [];
|
||
for (let offset = 0; offset < sourceSearchIds.length; offset += 100) {
|
||
matches.push(...await issuesApi.listCompact(selectedCompanyId!, {
|
||
ids: sourceSearchIds.slice(offset, offset + 100), q: normalizedSearchQuery,
|
||
projection: "index", includeRoutineExecutions: true, limit: 100,
|
||
}, { signal }) as Issue[]);
|
||
}
|
||
return matches;
|
||
},
|
||
enabled: !!selectedCompanyId && normalizedSearchQuery.length > 0 && sourceSearchIds.length > 0,
|
||
});
|
||
const { data: sourceSearchMatches = [], isLoading: isSourceSearchLoading, error: sourceSearchError } = sourceSearchQuery;
|
||
const sourceSearchView = useQueryView(sourceSearchQuery);
|
||
const sourceSearchMatchIds = useMemo(() => new Set(sourceSearchMatches.map((issue) => issue.id)), [sourceSearchMatches]);
|
||
const shouldUseIssueSearchSupplement =
|
||
!!selectedCompanyId
|
||
&& normalizedSearchQuery.length > 0;
|
||
const { data: remoteIssueSearchResults = NO_ISSUES } = useQuery({
|
||
queryKey: [
|
||
...queryKeys.issues.search(selectedCompanyId!, normalizedSearchQuery, undefined, 25),
|
||
"compact",
|
||
"inbox-supplement",
|
||
issueFilters.showAgentCreatedTasks,
|
||
"live-descendant-summary",
|
||
],
|
||
queryFn: () =>
|
||
issuesApi.listCompact(selectedCompanyId!, {
|
||
q: normalizedSearchQuery,
|
||
limit: 25,
|
||
includeAgentCreatedTasks: issueFilters.showAgentCreatedTasks,
|
||
includeParticipatedTasks: true,
|
||
includeRoutineExecutions: true,
|
||
includeLiveDescendantSummary: true,
|
||
}).then((rows) => rows as Issue[]),
|
||
enabled: shouldUseIssueSearchSupplement,
|
||
});
|
||
const liveIssueIds = useMemo(
|
||
() => collectLiveIssueIds(liveRuns, [
|
||
...(issues ?? []),
|
||
...mineIssuesRaw,
|
||
...touchedIssuesRaw,
|
||
...remoteIssueSearchResults,
|
||
]),
|
||
[issues, liveRuns, mineIssuesRaw, remoteIssueSearchResults, touchedIssuesRaw],
|
||
);
|
||
const inboxIssueIdsForExternalObjectSummaries = useMemo(() => {
|
||
const issueIds = new Set<string>();
|
||
for (const issue of mineIssues) issueIds.add(issue.id);
|
||
for (const issue of touchedIssues) issueIds.add(issue.id);
|
||
for (const issue of remoteIssueSearchResults) issueIds.add(issue.id);
|
||
return [...issueIds];
|
||
}, [mineIssues, remoteIssueSearchResults, touchedIssues]);
|
||
// Only the workspaces these rows reference; a company-wide list can be thousands of rows.
|
||
const referencedExecutionWorkspaceIds = useMemo(
|
||
() => collectReferencedExecutionWorkspaceIds(issues, remoteIssueSearchResults),
|
||
[issues, remoteIssueSearchResults],
|
||
);
|
||
const referencedExecutionWorkspaceIdsKey = referencedExecutionWorkspaceIds.join(",");
|
||
const workspaceLookupEnabled = !!selectedCompanyId && isolatedWorkspacesEnabled && referencedExecutionWorkspaceIds.length > 0;
|
||
const {
|
||
data: executionWorkspaces = [],
|
||
isLoading: isWorkspacesLoading,
|
||
isPlaceholderData: isWorkspacesPlaceholder,
|
||
} = useQuery({
|
||
queryKey: queryKeys.executionWorkspaces.summaryList(selectedCompanyId ?? "__disabled__", {
|
||
ids: referencedExecutionWorkspaceIdsKey,
|
||
}),
|
||
queryFn: () => executionWorkspacesApi.listSummariesByIds(selectedCompanyId!, referencedExecutionWorkspaceIds),
|
||
enabled: workspaceLookupEnabled,
|
||
// Keep names visible while this company's id set changes; never carry them across companies
|
||
// or into a view that needs no lookup, where a placeholder would never be replaced.
|
||
placeholderData: (previous, previousQuery) =>
|
||
workspaceLookupEnabled && previousQuery?.queryKey[1] === selectedCompanyId ? previous : undefined,
|
||
});
|
||
const {
|
||
summaries: externalObjectSummaryByIssueId,
|
||
isLoading: externalObjectSummariesLoading,
|
||
isReady: externalObjectSummariesReady,
|
||
error: externalObjectSummariesError,
|
||
refetch: retryExternalObjectSummaries,
|
||
} = useIssueExternalObjectSummaries(
|
||
selectedCompanyId,
|
||
inboxIssueIdsForExternalObjectSummaries,
|
||
);
|
||
const issueFilterContext = useMemo(() => ({
|
||
externalObjectSummaryByIssueId,
|
||
externalObjectSummariesReady: externalObjectSummariesReady && !externalObjectSummariesLoading,
|
||
}), [externalObjectSummariesLoading, externalObjectSummariesReady, externalObjectSummaryByIssueId]);
|
||
const visibleMineIssues = useMemo(
|
||
() => applyIssueFilters(mineIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext),
|
||
[mineIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext],
|
||
);
|
||
const visibleTouchedIssues = useMemo(
|
||
() => applyIssueFilters(touchedIssues, issueFilters, currentUserId, false, liveIssueIds, issueFilterContext),
|
||
[touchedIssues, issueFilters, currentUserId, liveIssueIds, issueFilterContext],
|
||
);
|
||
const unreadTouchedIssues = useMemo(
|
||
() => visibleTouchedIssues.filter((issue) => issue.isUnreadForMe),
|
||
[visibleTouchedIssues],
|
||
);
|
||
const creatorOptions = useMemo<CreatorOption[]>(() => {
|
||
const options = new Map<string, CreatorOption>();
|
||
const sourceIssues = [...mineIssues, ...touchedIssues];
|
||
|
||
if (currentUserId) {
|
||
options.set(`user:${currentUserId}`, {
|
||
id: `user:${currentUserId}`,
|
||
label: currentUserId === "local-board" ? "Board" : "Me",
|
||
kind: "user",
|
||
searchText: currentUserId === "local-board" ? "board me human local-board" : `me board human ${currentUserId}`,
|
||
});
|
||
}
|
||
|
||
for (const issue of sourceIssues) {
|
||
if (issue.createdByUserId) {
|
||
const id = `user:${issue.createdByUserId}`;
|
||
if (!options.has(id)) {
|
||
options.set(id, {
|
||
id,
|
||
label: formatAssigneeUserLabel(issue.createdByUserId, currentUserId) ?? issue.createdByUserId.slice(0, 5),
|
||
kind: "user",
|
||
searchText: `${issue.createdByUserId} board user human`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const knownAgentIds = new Set<string>();
|
||
for (const agent of agents ?? []) {
|
||
knownAgentIds.add(agent.id);
|
||
const id = `agent:${agent.id}`;
|
||
if (!options.has(id)) {
|
||
options.set(id, {
|
||
id,
|
||
label: agent.name,
|
||
kind: "agent",
|
||
searchText: `${agent.name} ${agent.id} agent`,
|
||
});
|
||
}
|
||
}
|
||
|
||
for (const issue of sourceIssues) {
|
||
if (issue.createdByAgentId && !knownAgentIds.has(issue.createdByAgentId)) {
|
||
const id = `agent:${issue.createdByAgentId}`;
|
||
if (!options.has(id)) {
|
||
options.set(id, {
|
||
id,
|
||
label: issue.createdByAgentId.slice(0, 8),
|
||
kind: "agent",
|
||
searchText: `${issue.createdByAgentId} agent`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
return [...options.values()].sort((a, b) => {
|
||
if (a.kind !== b.kind) return a.kind === "user" ? -1 : 1;
|
||
return a.label.localeCompare(b.label);
|
||
});
|
||
}, [agents, currentUserId, mineIssues, touchedIssues]);
|
||
const issuesToRender = useMemo(
|
||
() => {
|
||
if (tab === "mine") return visibleMineIssues;
|
||
if (tab === "unread") return unreadTouchedIssues;
|
||
return visibleTouchedIssues;
|
||
},
|
||
[tab, visibleMineIssues, visibleTouchedIssues, unreadTouchedIssues],
|
||
);
|
||
|
||
const agentById = useMemo(() => {
|
||
const map = new Map<string, string>();
|
||
for (const agent of agents ?? []) map.set(agent.id, agent.name);
|
||
return map;
|
||
}, [agents]);
|
||
|
||
const issueById = useMemo(() => {
|
||
const map = new Map<string, Issue>();
|
||
for (const issue of issues ?? []) map.set(issue.id, issue);
|
||
return map;
|
||
}, [issues]);
|
||
const projectById = useMemo(() => {
|
||
const map = new Map<string, { name: string; color: string | null }>();
|
||
for (const project of projects ?? []) {
|
||
map.set(project.id, { name: project.name, color: project.color });
|
||
}
|
||
return map;
|
||
}, [projects]);
|
||
const projectWorkspaceById = useMemo(() => {
|
||
const map = new Map<string, { name: string; projectId: string }>();
|
||
for (const project of projects ?? []) {
|
||
for (const workspace of project.workspaces ?? []) {
|
||
map.set(workspace.id, { name: workspace.name, projectId: project.id });
|
||
}
|
||
}
|
||
return map;
|
||
}, [projects]);
|
||
const defaultProjectWorkspaceIdByProjectId = useMemo(() => {
|
||
const map = new Map<string, string>();
|
||
for (const project of projects ?? []) {
|
||
const defaultWorkspaceId =
|
||
project.executionWorkspacePolicy?.defaultProjectWorkspaceId
|
||
?? project.primaryWorkspace?.id
|
||
?? null;
|
||
if (defaultWorkspaceId) map.set(project.id, defaultWorkspaceId);
|
||
}
|
||
return map;
|
||
}, [projects]);
|
||
const executionWorkspaceById = useMemo(() => {
|
||
const map = new Map<string, {
|
||
name: string;
|
||
mode: "shared_workspace" | "isolated_workspace" | "operator_branch" | "adapter_managed" | "cloud_sandbox";
|
||
projectWorkspaceId: string | null;
|
||
projectId: string | null;
|
||
}>();
|
||
for (const workspace of executionWorkspaces) {
|
||
const projectWorkspace = workspace.projectWorkspaceId
|
||
? projectWorkspaceById.get(workspace.projectWorkspaceId) ?? null
|
||
: null;
|
||
map.set(workspace.id, {
|
||
name: workspace.name,
|
||
mode: workspace.mode,
|
||
projectWorkspaceId: workspace.projectWorkspaceId ?? null,
|
||
projectId: projectWorkspace?.projectId ?? null,
|
||
});
|
||
}
|
||
return map;
|
||
}, [executionWorkspaces, projectWorkspaceById]);
|
||
const inboxWorkspaceGrouping = useMemo<InboxWorkspaceGroupingOptions>(
|
||
() => ({
|
||
agentById,
|
||
executionWorkspaceById,
|
||
projectWorkspaceById,
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
projectById,
|
||
userLabelById: companyUserLabelMap,
|
||
currentUserId,
|
||
}),
|
||
[
|
||
agentById,
|
||
companyUserLabelMap,
|
||
currentUserId,
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
executionWorkspaceById,
|
||
projectById,
|
||
projectWorkspaceById,
|
||
],
|
||
);
|
||
const visibleIssueColumnSet = useMemo(() => new Set(visibleIssueColumns), [visibleIssueColumns]);
|
||
const availableIssueColumns = useMemo(
|
||
() => getAvailableInboxIssueColumns(isolatedWorkspacesEnabled),
|
||
[isolatedWorkspacesEnabled],
|
||
);
|
||
const availableIssueColumnSet = useMemo(() => new Set(availableIssueColumns), [availableIssueColumns]);
|
||
const visibleTrailingIssueColumns = useMemo(
|
||
() => issueTrailingColumns.filter((column) => visibleIssueColumnSet.has(column) && availableIssueColumnSet.has(column)),
|
||
[availableIssueColumnSet, visibleIssueColumnSet],
|
||
);
|
||
const visibleTaskDataColumns = useMemo(
|
||
() => visibleTrailingIssueColumns.filter((column) => column !== "updated"),
|
||
[visibleTrailingIssueColumns],
|
||
);
|
||
const showTaskTimestamp = visibleIssueColumnSet.has("updated") && availableIssueColumnSet.has("updated");
|
||
|
||
const failedRuns = useMemo(
|
||
() =>
|
||
getLatestFailedRunsByAgent(heartbeatRuns ?? []).filter((run) => {
|
||
const issueId = readIssueIdFromRun(run);
|
||
return !isInboxEntityDismissed(dismissedAtByKey, `run:${run.id}`, run.createdAt)
|
||
&& (!issueId || knownFailureContextIds.has(issueId) || !!contextIssuesError)
|
||
&& issueById.get(issueId ?? "")?.interruption?.state !== "resolved";
|
||
}),
|
||
[heartbeatRuns, dismissedAtByKey, issueById, knownFailureContextIds, contextIssuesError],
|
||
);
|
||
const approvalsToRender = useMemo(() => {
|
||
let filtered = getApprovalsForTab(approvals ?? [], tab, allApprovalFilter, currentUserId);
|
||
if (tab === "mine") {
|
||
filtered = filtered.filter(
|
||
(a) => !isInboxEntityDismissed(dismissedAtByKey, `approval:${a.id}`, a.updatedAt),
|
||
);
|
||
}
|
||
return filtered;
|
||
}, [approvals, tab, allApprovalFilter, currentUserId, dismissedAtByKey]);
|
||
const showJoinRequestsCategory =
|
||
allCategoryFilter === "everything" || allCategoryFilter === "join_requests";
|
||
const showTouchedCategory =
|
||
allCategoryFilter === "everything" || allCategoryFilter === "issues_i_touched";
|
||
const showApprovalsCategory =
|
||
allCategoryFilter === "everything" || allCategoryFilter === "approvals";
|
||
const showFailedRunsCategory =
|
||
allCategoryFilter === "everything" || allCategoryFilter === "failed_runs";
|
||
const showAlertsCategory = allCategoryFilter === "everything" || allCategoryFilter === "alerts";
|
||
const failedRunsForTab = useMemo(() => {
|
||
if (tab === "all" && !showFailedRunsCategory) return [];
|
||
if (tab === "mine") return failedRuns.filter((run) => isHeartbeatRunVisibleInMine(run, currentUserId));
|
||
return failedRuns;
|
||
}, [failedRuns, tab, showFailedRunsCategory, currentUserId]);
|
||
|
||
const joinRequestsForTab = useMemo(() => {
|
||
if (tab === "all" && !showJoinRequestsCategory) return [];
|
||
if (tab === "mine") {
|
||
return joinRequests.filter(
|
||
(jr) => !isInboxEntityDismissed(dismissedAtByKey, `join:${jr.id}`, jr.updatedAt ?? jr.createdAt),
|
||
);
|
||
}
|
||
return joinRequests;
|
||
}, [joinRequests, tab, showJoinRequestsCategory, dismissedAtByKey]);
|
||
|
||
const workItemsToRender = useMemo(
|
||
() =>
|
||
getInboxWorkItems({
|
||
issues: tab === "all" && !showTouchedCategory ? [] : issuesToRender,
|
||
approvals: tab === "all" && !showApprovalsCategory ? [] : approvalsToRender,
|
||
failedRuns: failedRunsForTab,
|
||
joinRequests: joinRequestsForTab,
|
||
}),
|
||
[approvalsToRender, issuesToRender, showApprovalsCategory, showTouchedCategory, tab, failedRunsForTab, joinRequestsForTab],
|
||
);
|
||
|
||
const filteredWorkItems = useMemo(() => {
|
||
const q = normalizedSearchQuery.toLowerCase();
|
||
if (!q) return workItemsToRender;
|
||
return workItemsToRender.filter((item) => {
|
||
if (item.kind === "issue") {
|
||
return matchesInboxIssueSearch(item.issue, q, {
|
||
matchedIssueIds: sourceSearchMatchIds,
|
||
isolatedWorkspacesEnabled,
|
||
executionWorkspaceById,
|
||
projectWorkspaceById,
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
});
|
||
}
|
||
if (item.kind === "approval") {
|
||
const a = item.approval;
|
||
const label = approvalLabel(a.type, a.payload as Record<string, unknown> | null);
|
||
if (label.toLowerCase().includes(q)) return true;
|
||
if (a.type.toLowerCase().includes(q)) return true;
|
||
return false;
|
||
}
|
||
if (item.kind === "failed_run") {
|
||
const run = item.run;
|
||
const name = agentById.get(run.agentId);
|
||
if (name?.toLowerCase().includes(q)) return true;
|
||
const msg = runFailureMessage(run);
|
||
if (msg.toLowerCase().includes(q)) return true;
|
||
const issueId = readIssueIdFromRun(run);
|
||
if (issueId) {
|
||
const issue = issueById.get(issueId);
|
||
if (issue?.title.toLowerCase().includes(q)) return true;
|
||
if (issue?.identifier?.toLowerCase().includes(q)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
if (item.kind === "join_request") {
|
||
const jr = item.joinRequest;
|
||
if (jr.agentName?.toLowerCase().includes(q)) return true;
|
||
if (jr.capabilities?.toLowerCase().includes(q)) return true;
|
||
return false;
|
||
}
|
||
return false;
|
||
});
|
||
}, [
|
||
workItemsToRender,
|
||
agentById,
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
executionWorkspaceById,
|
||
issueById,
|
||
isolatedWorkspacesEnabled,
|
||
normalizedSearchQuery,
|
||
sourceSearchMatchIds,
|
||
projectWorkspaceById,
|
||
]);
|
||
|
||
const archivedSearchIssues = useMemo(
|
||
() =>
|
||
tab === "mine"
|
||
? getArchivedInboxSearchIssues({
|
||
visibleIssues: visibleMineIssues,
|
||
searchableIssues: visibleTouchedIssues,
|
||
query: normalizedSearchQuery,
|
||
matchedIssueIds: sourceSearchMatchIds,
|
||
isolatedWorkspacesEnabled,
|
||
executionWorkspaceById,
|
||
projectWorkspaceById,
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
})
|
||
: [],
|
||
[
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
executionWorkspaceById,
|
||
isolatedWorkspacesEnabled,
|
||
normalizedSearchQuery,
|
||
sourceSearchMatchIds,
|
||
projectWorkspaceById,
|
||
tab,
|
||
visibleMineIssues,
|
||
visibleTouchedIssues,
|
||
],
|
||
);
|
||
const issueSearchSupplementResults = useMemo(
|
||
() =>
|
||
getInboxSearchSupplementIssues({
|
||
query: normalizedSearchQuery,
|
||
filteredWorkItems,
|
||
archivedSearchIssues,
|
||
remoteIssues: remoteIssueSearchResults,
|
||
issueFilters,
|
||
currentUserId,
|
||
enableAgentCreatedVisibilityFilter: false,
|
||
liveIssueIds,
|
||
issueFilterContext,
|
||
}),
|
||
[
|
||
archivedSearchIssues,
|
||
currentUserId,
|
||
filteredWorkItems,
|
||
issueFilterContext,
|
||
issueFilters,
|
||
liveIssueIds,
|
||
normalizedSearchQuery,
|
||
remoteIssueSearchResults,
|
||
],
|
||
);
|
||
const nonInboxSearchIssueIds = useMemo(
|
||
() => new Set([
|
||
...archivedSearchIssues.map((issue) => issue.id),
|
||
...issueSearchSupplementResults.map((issue) => issue.id),
|
||
]),
|
||
[archivedSearchIssues, issueSearchSupplementResults],
|
||
);
|
||
|
||
// --- Parent-child nesting for inbox issues ---
|
||
const [nestingPreferenceEnabled, setNestingPreferenceEnabled] = useState(() => loadInboxNesting());
|
||
const nestingEnabled = resolveInboxNestingEnabled(nestingPreferenceEnabled, isMobile);
|
||
useEffect(() => {
|
||
if (!shouldResetInboxWorkspaceGrouping(groupBy, isolatedWorkspacesEnabled, experimentalSettingsLoaded)) return;
|
||
setGroupBy("none");
|
||
saveInboxWorkItemGroupBy("none");
|
||
}, [experimentalSettingsLoaded, groupBy, isolatedWorkspacesEnabled]);
|
||
const toggleNesting = useCallback(() => {
|
||
setNestingPreferenceEnabled((prev) => {
|
||
const next = !prev;
|
||
saveInboxNesting(next);
|
||
return next;
|
||
});
|
||
}, []);
|
||
const [collapsedInboxParents, setCollapsedInboxParents] = useState<Set<string>>(
|
||
() => loadCollapsedInboxParentIds(selectedCompanyId),
|
||
);
|
||
const [collapsedGroupKeys, setCollapsedGroupKeys] = useState<Set<string>>(() => loadCollapsedInboxGroupKeys(selectedCompanyId));
|
||
const toggleGroupCollapse = useCallback((groupKey: string) => {
|
||
setCollapsedGroupKeys((prev) => {
|
||
const next = new Set(prev);
|
||
if (next.has(groupKey)) next.delete(groupKey);
|
||
else next.add(groupKey);
|
||
saveCollapsedInboxGroupKeys(selectedCompanyId, next);
|
||
return next;
|
||
});
|
||
}, [selectedCompanyId]);
|
||
const setGroupCollapsed = useCallback((groupKey: string, collapsed: boolean) => {
|
||
setCollapsedGroupKeys((prev) => {
|
||
if (collapsed ? prev.has(groupKey) : !prev.has(groupKey)) return prev;
|
||
const next = new Set(prev);
|
||
if (collapsed) next.add(groupKey);
|
||
else next.delete(groupKey);
|
||
saveCollapsedInboxGroupKeys(selectedCompanyId, next);
|
||
return next;
|
||
});
|
||
}, [selectedCompanyId]);
|
||
const freshGroupedSections = useMemo<InboxGroupedSection[]>(() => [
|
||
...buildGroupedInboxSections(filteredWorkItems, groupBy, inboxWorkspaceGrouping, { nestingEnabled }),
|
||
...buildGroupedInboxSections(
|
||
getInboxWorkItems({ issues: archivedSearchIssues, approvals: [] }),
|
||
groupBy,
|
||
inboxWorkspaceGrouping,
|
||
{ keyPrefix: "archived-search:", searchSection: "archived", nestingEnabled },
|
||
),
|
||
...buildGroupedInboxSections(
|
||
getInboxWorkItems({ issues: issueSearchSupplementResults, approvals: [] }),
|
||
groupBy,
|
||
inboxWorkspaceGrouping,
|
||
{ keyPrefix: "other-search:", searchSection: "other", nestingEnabled },
|
||
),
|
||
], [
|
||
archivedSearchIssues,
|
||
filteredWorkItems,
|
||
groupBy,
|
||
inboxWorkspaceGrouping,
|
||
issueSearchSupplementResults,
|
||
nestingEnabled,
|
||
]);
|
||
|
||
// --- Order pinning (PAP-16015) ---
|
||
// The freshly computed sort is only *displayed* at attention boundaries. Between
|
||
// them we reconcile the fresh sections against the last committed order so that
|
||
// archiving mid-engagement (which drops rows from the caches, and can lower a
|
||
// parent's subtree-max sort ts) can no longer reshuffle the list under the
|
||
// cursor. New items still land at their algorithmic position; archived rows hold
|
||
// their slot for the 5s undo grace before collapsing. See `inboxOrderPin.ts`.
|
||
const orderPinRef = useRef<InboxOrderPin>({ sections: [] });
|
||
// Bumped by an attention commit to force `groupedSections` to adopt the fresh order.
|
||
const [orderCommitToken, setOrderCommitToken] = useState(0);
|
||
const orderCommitRequestedRef = useRef(false);
|
||
const commitInboxOrder = useCallback(() => {
|
||
orderCommitRequestedRef.current = true;
|
||
setOrderCommitToken((token) => token + 1);
|
||
}, []);
|
||
|
||
// Distinct view = distinct pin. Switching tab/filter/search/grouping resets the
|
||
// held order so we never carry one view's layout into another.
|
||
const inboxSortViewIdentity = useMemo(
|
||
() =>
|
||
JSON.stringify([
|
||
selectedCompanyId,
|
||
tab,
|
||
groupBy,
|
||
nestingEnabled,
|
||
normalizedSearchQuery,
|
||
allCategoryFilter,
|
||
allApprovalFilter,
|
||
issueFilters,
|
||
]),
|
||
[
|
||
allApprovalFilter,
|
||
allCategoryFilter,
|
||
groupBy,
|
||
issueFilters,
|
||
nestingEnabled,
|
||
normalizedSearchQuery,
|
||
selectedCompanyId,
|
||
tab,
|
||
],
|
||
);
|
||
// Adopt the fresh order in the SAME render the view identity changes, so a
|
||
// section key shared between the two views never briefly shows the previous
|
||
// view's order before the hook's passive commit effect runs.
|
||
const previousInboxSortViewIdentityRef = useRef(inboxSortViewIdentity);
|
||
if (previousInboxSortViewIdentityRef.current !== inboxSortViewIdentity) {
|
||
previousInboxSortViewIdentityRef.current = inboxSortViewIdentity;
|
||
orderCommitRequestedRef.current = true;
|
||
}
|
||
|
||
const groupedSections = useMemo<InboxGroupedSection[]>(() => {
|
||
const nowMs = Date.now();
|
||
// An attention boundary (or a view change) fired: adopt the fresh order
|
||
// wholesale and re-pin it.
|
||
if (orderCommitRequestedRef.current) {
|
||
orderCommitRequestedRef.current = false;
|
||
orderPinRef.current = captureInboxOrderPin(freshGroupedSections);
|
||
return freshGroupedSections;
|
||
}
|
||
const { sections, pin } = reconcileInboxOrderPin(orderPinRef.current, freshGroupedSections, nowMs);
|
||
orderPinRef.current = pin;
|
||
return sections;
|
||
// orderCommitToken forces re-adoption at a commit boundary; inboxSortViewIdentity
|
||
// forces it on a view change even when the fresh sections keep their identity.
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||
}, [freshGroupedSections, inboxSortViewIdentity, orderCommitToken]);
|
||
|
||
const inboxSortAttention = useInboxSortAttention({
|
||
viewIdentity: inboxSortViewIdentity,
|
||
onCommit: commitInboxOrder,
|
||
});
|
||
const noteInboxSortInteraction = inboxSortAttention.noteInteraction;
|
||
|
||
const openCreateIssueForGroup = useCallback((group: InboxGroupedSection) => {
|
||
const defaults = buildInboxIssueGroupCreateDefaults(
|
||
group.key,
|
||
groupBy,
|
||
group.displayItems,
|
||
inboxWorkspaceGrouping,
|
||
);
|
||
if (!defaults) return;
|
||
openNewIssue(defaults);
|
||
}, [groupBy, inboxWorkspaceGrouping, openNewIssue]);
|
||
const totalVisibleWorkItems = useMemo(
|
||
() => groupedSections.reduce((count, group) => count + group.displayItems.length, 0),
|
||
[groupedSections],
|
||
);
|
||
const toggleInboxParentCollapse = useCallback((parentId: string) => {
|
||
setCollapsedInboxParents((prev) => {
|
||
const next = new Set(prev);
|
||
if (next.has(parentId)) next.delete(parentId);
|
||
else next.add(parentId);
|
||
saveCollapsedInboxParentIds(selectedCompanyId, next);
|
||
return next;
|
||
});
|
||
}, [selectedCompanyId]);
|
||
const setInboxParentCollapsed = useCallback((parentId: string, collapsed: boolean) => {
|
||
setCollapsedInboxParents((prev) => {
|
||
if (prev.has(parentId) === collapsed) return prev;
|
||
const next = new Set(prev);
|
||
if (collapsed) next.add(parentId);
|
||
else next.delete(parentId);
|
||
saveCollapsedInboxParentIds(selectedCompanyId, next);
|
||
return next;
|
||
});
|
||
}, [selectedCompanyId]);
|
||
|
||
// Build flat navigation list from visible rows so keyboard traversal respects collapsed groups.
|
||
const flatNavItems = useMemo((): NavEntry[] => {
|
||
return buildInboxKeyboardNavEntries(groupedSections, collapsedGroupKeys, collapsedInboxParents);
|
||
}, [collapsedGroupKeys, collapsedInboxParents, groupedSections]);
|
||
// Read the current nav list from event handlers without recreating them (and
|
||
// without capturing a stale array), so hover can resolve the row's key.
|
||
const flatNavItemsRef = useRef(flatNavItems);
|
||
flatNavItemsRef.current = flatNavItems;
|
||
// Roll live descendant runs up to their ancestors across the loaded inbox tree
|
||
// so a parent that is not itself live can still surface "n live below".
|
||
const subtreeCounts = useMemo(() => {
|
||
const nodes: { id: string; parentId: string | null }[] = [];
|
||
const seen = new Set<string>();
|
||
const pushIssue = (issue: Issue) => {
|
||
if (seen.has(issue.id)) return;
|
||
seen.add(issue.id);
|
||
nodes.push({ id: issue.id, parentId: issue.parentId });
|
||
};
|
||
for (const group of groupedSections) {
|
||
for (const item of group.displayItems) {
|
||
if (item.kind === "issue") pushIssue(item.issue);
|
||
}
|
||
for (const children of group.childrenByIssueId.values()) {
|
||
for (const child of children) pushIssue(child);
|
||
}
|
||
}
|
||
return {
|
||
live: collectSubtreeLiveCounts(nodes, liveIssueIds),
|
||
running: collectSubtreeLiveCounts(nodes, liveIssueIds, { startedOnly: true }),
|
||
};
|
||
}, [groupedSections, liveIssueIds]);
|
||
const subtreeLiveCounts = subtreeCounts.live;
|
||
const topFlatIndex = useMemo(() => {
|
||
const map = new Map<string, number>();
|
||
flatNavItems.forEach((entry, index) => {
|
||
if (entry.type === "top") map.set(entry.itemKey, index);
|
||
});
|
||
return map;
|
||
}, [flatNavItems]);
|
||
const childFlatIndex = useMemo(() => {
|
||
const map = new Map<string, number>();
|
||
flatNavItems.forEach((entry, index) => {
|
||
if (entry.type === "child") map.set(entry.issueId, index);
|
||
});
|
||
return map;
|
||
}, [flatNavItems]);
|
||
const groupFlatIndex = useMemo(() => {
|
||
const map = new Map<string, number>();
|
||
flatNavItems.forEach((entry, index) => {
|
||
if (entry.type === "group") map.set(entry.groupKey, index);
|
||
});
|
||
return map;
|
||
}, [flatNavItems]);
|
||
|
||
const agentName = (id: string | null) => {
|
||
if (!id) return null;
|
||
return agentById.get(id) ?? null;
|
||
};
|
||
const setIssueColumns = useCallback((next: InboxIssueColumn[]) => {
|
||
const normalized = normalizeInboxIssueColumns(next);
|
||
setVisibleIssueColumns(normalized);
|
||
saveTaskCollectionPreferences(inboxCollectionPreferenceLocation(selectedCompanyId), {
|
||
viewState: filterPreferences,
|
||
columns: normalized,
|
||
});
|
||
}, [filterPreferences, selectedCompanyId]);
|
||
const toggleIssueColumn = useCallback((column: InboxIssueColumn, enabled: boolean) => {
|
||
if (enabled) {
|
||
setIssueColumns([...visibleIssueColumns, column]);
|
||
return;
|
||
}
|
||
setIssueColumns(visibleIssueColumns.filter((value) => value !== column));
|
||
}, [setIssueColumns, visibleIssueColumns]);
|
||
const updateFilterPreferences = useCallback(
|
||
(updater: (previous: StreamlinedInboxViewState) => StreamlinedInboxViewState) => {
|
||
setFilterPreferences((previous) => {
|
||
const next = updater(previous);
|
||
saveTaskCollectionPreferences(inboxCollectionPreferenceLocation(selectedCompanyId), {
|
||
viewState: next,
|
||
columns: visibleIssueColumns,
|
||
});
|
||
return next;
|
||
});
|
||
},
|
||
[selectedCompanyId, visibleIssueColumns],
|
||
);
|
||
const updateIssueFilters = useCallback((patch: Partial<IssueFilterState>) => {
|
||
updateFilterPreferences((previous) => ({
|
||
...previous,
|
||
issueFilters: { ...previous.issueFilters, ...patch },
|
||
}));
|
||
}, [updateFilterPreferences]);
|
||
useEffect(() => {
|
||
if (!experimentalSettingsLoaded || externalObjectsEnabled || issueFilters.externalObjectStatuses.length === 0) return;
|
||
updateIssueFilters({ externalObjectStatuses: [] });
|
||
}, [
|
||
experimentalSettingsLoaded,
|
||
externalObjectsEnabled,
|
||
issueFilters.externalObjectStatuses.length,
|
||
updateIssueFilters,
|
||
]);
|
||
const updateAllCategoryFilter = useCallback((value: InboxCategoryFilter) => {
|
||
updateFilterPreferences((previous) => ({ ...previous, allCategoryFilter: value }));
|
||
}, [updateFilterPreferences]);
|
||
const updateAllApprovalFilter = useCallback((value: InboxApprovalFilter) => {
|
||
updateFilterPreferences((previous) => ({ ...previous, allApprovalFilter: value }));
|
||
}, [updateFilterPreferences]);
|
||
const updateGroupBy = useCallback((nextGroupBy: InboxWorkItemGroupBy) => {
|
||
setGroupBy(nextGroupBy);
|
||
saveInboxWorkItemGroupBy(nextGroupBy);
|
||
}, []);
|
||
|
||
const approveMutation = useMutation({
|
||
mutationFn: (id: string) => approvalsApi.approve(id),
|
||
onSuccess: (_approval, id) => {
|
||
setActionError(null);
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.approvals.list(selectedCompanyId!) });
|
||
navigate(`/approvals/${id}?resolved=approved`);
|
||
},
|
||
onError: (err) => {
|
||
setActionError(describeError(err, { action: "approve this request" }).body);
|
||
},
|
||
});
|
||
|
||
const rejectMutation = useMutation({
|
||
mutationFn: (id: string) => approvalsApi.reject(id),
|
||
onSuccess: () => {
|
||
setActionError(null);
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.approvals.list(selectedCompanyId!) });
|
||
},
|
||
onError: (err) => {
|
||
setActionError(describeError(err, { action: "reject this request" }).body);
|
||
},
|
||
});
|
||
|
||
const approveJoinMutation = useMutation({
|
||
mutationFn: (joinRequest: JoinRequest) =>
|
||
accessApi.approveJoinRequest(selectedCompanyId!, joinRequest.id),
|
||
onSuccess: () => {
|
||
setActionError(null);
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.access.joinRequests(selectedCompanyId!) });
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(selectedCompanyId!) });
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId!) });
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
|
||
},
|
||
onError: (err) => {
|
||
setActionError(describeError(err).body);
|
||
},
|
||
});
|
||
|
||
const rejectJoinMutation = useMutation({
|
||
mutationFn: (joinRequest: JoinRequest) =>
|
||
accessApi.rejectJoinRequest(selectedCompanyId!, joinRequest.id),
|
||
onSuccess: () => {
|
||
setActionError(null);
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.access.joinRequests(selectedCompanyId!) });
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(selectedCompanyId!) });
|
||
},
|
||
onError: (err) => {
|
||
setActionError(describeError(err).body);
|
||
},
|
||
});
|
||
|
||
const [retryingRunIds, setRetryingRunIds] = useState<Set<string>>(new Set());
|
||
const retryRequestKeys = useRef(new Map<string, string>());
|
||
|
||
const retryRunMutation = useMutation({
|
||
mutationFn: async (run: HeartbeatRun) => {
|
||
const issueId = readIssueIdFromRun(run);
|
||
if (issueId) {
|
||
let idempotencyKey = retryRequestKeys.current.get(run.id);
|
||
if (!idempotencyKey) {
|
||
idempotencyKey = crypto.randomUUID();
|
||
retryRequestKeys.current.set(run.id, idempotencyKey);
|
||
}
|
||
const result = await issuesApi.retryTask(issueId, { idempotencyKey, observedRunId: run.id }).catch(error => {
|
||
if (error instanceof ApiError && error.status >= 400 && error.status < 500)
|
||
retryRequestKeys.current.delete(run.id);
|
||
throw error;
|
||
});
|
||
queryClient.setQueryData<Issue>(queryKeys.issues.detail(issueId), current =>
|
||
current ? { ...current, interruption: result.presentation } : current);
|
||
const notStarted = taskRetryNotStartedReason(result);
|
||
if (notStarted) {
|
||
retryRequestKeys.current.delete(run.id);
|
||
await Promise.all([queryKeys.issues.listMineByMe(run.companyId), queryKeys.heartbeats(run.companyId),
|
||
queryKeys.heartbeats(run.companyId, run.agentId)].map(queryKey => queryClient.invalidateQueries({ queryKey })));
|
||
throw new Error(notStarted);
|
||
}
|
||
return { newRun: { runId: null, issueId }, originalRun: run };
|
||
}
|
||
const result = await agentsApi.retryFailedRun(
|
||
run.agentId,
|
||
run.id,
|
||
run.companyId,
|
||
);
|
||
return { newRun: result, originalRun: run };
|
||
},
|
||
onMutate: (run) => {
|
||
setRetryingRunIds((prev) => new Set(prev).add(run.id));
|
||
},
|
||
onSuccess: ({ newRun, originalRun }) => {
|
||
retryRequestKeys.current.delete(originalRun.id);
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(originalRun.companyId) });
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(originalRun.companyId) });
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(originalRun.companyId, originalRun.agentId) });
|
||
if (newRun.runId)
|
||
navigate(`/agents/${originalRun.agentId}/runs/${newRun.runId}`);
|
||
else if (newRun.issueId) navigate(`/issues/${newRun.issueId}`);
|
||
},
|
||
onError: (error) => {
|
||
pushToast({
|
||
title: "Run retry failed",
|
||
body: error instanceof Error ? error.message : "Unable to retry run",
|
||
tone: "error",
|
||
});
|
||
},
|
||
onSettled: (_data, _error, run) => {
|
||
if (!run) return;
|
||
setRetryingRunIds((prev) => {
|
||
const next = new Set(prev);
|
||
next.delete(run.id);
|
||
return next;
|
||
});
|
||
},
|
||
});
|
||
|
||
const [fadingOutIssues, setFadingOutIssues] = useState<Set<string>>(new Set());
|
||
const [showMarkAllReadConfirm, setShowMarkAllReadConfirm] = useState(false);
|
||
const [fadingNonIssueItems, setFadingNonIssueItems] = useState<Set<string>>(new Set());
|
||
const [archivingNonIssueIds, setArchivingNonIssueIds] = useState<Set<string>>(new Set());
|
||
const [selectedIndex, setSelectedIndex] = useState<number>(-1);
|
||
const listRef = useRef<HTMLDivElement>(null);
|
||
// Keyboard nav scrolls the list, which fires mouseenter on whatever row lands
|
||
// under the stationary cursor — that must not steal the selection. Hover only
|
||
// selects after the pointer has physically moved since the last key nav.
|
||
const pointerMovedSinceKeyNavRef = useRef(true);
|
||
useEffect(() => {
|
||
const handlePointerMove = () => {
|
||
pointerMovedSinceKeyNavRef.current = true;
|
||
};
|
||
window.addEventListener("mousemove", handlePointerMove, { passive: true });
|
||
return () => window.removeEventListener("mousemove", handlePointerMove);
|
||
}, []);
|
||
// Which row the cursor is over, tracked WITHOUT React state so scrubbing the
|
||
// list costs zero re-renders (hover paints via CSS `:hover`, see IssueRow).
|
||
// Keyboard nav reads this to continue from the hovered row.
|
||
const hoveredIndexRef = useRef<number | null>(null);
|
||
// The hovered row's stable key, kept alongside the numeric index so a poll
|
||
// that reshapes the list can re-anchor the hover to the same row instead of
|
||
// dropping it (which stranded j/k back at the top — PAP-9679 regression).
|
||
const hoveredNavKeyRef = useRef<string | null>(null);
|
||
const setSelectedIndexFromPointer = useCallback((idx: number) => {
|
||
if (!pointerMovedSinceKeyNavRef.current) return;
|
||
noteInboxSortInteraction();
|
||
hoveredIndexRef.current = idx;
|
||
hoveredNavKeyRef.current = navEntryKey(flatNavItemsRef.current[idx]);
|
||
// Drop any keyboard selection band the moment the mouse takes over, so we
|
||
// never show two identical highlights at once. React bails out when the
|
||
// value is already -1, so continuous hovering triggers no re-render.
|
||
setSelectedIndex((prev) => (prev < 0 ? prev : -1));
|
||
}, [noteInboxSortInteraction]);
|
||
|
||
const invalidateInboxIssueQueryCaches = () => {
|
||
if (!selectedCompanyId) return;
|
||
invalidateInboxIssueQueries(queryClient, selectedCompanyId);
|
||
};
|
||
|
||
const archiveIssueMutation = useAccountBoundMutation({
|
||
mutationFn: (id: string) => issuesApi.archiveFromInbox(id),
|
||
onMutate: async (id) => {
|
||
// Keep the sort pinned: archiving is engagement, so defer any idle re-sort.
|
||
noteInboxSortInteraction();
|
||
setActionError(null);
|
||
setArchivingIssueIds((prev) => new Set(prev).add(id));
|
||
|
||
if (!selectedCompanyId) return { previousData: [] as InboxIssueCacheSnapshot };
|
||
const account = bindAccount(queryClient);
|
||
const release = beginLocalInboxArchive(selectedCompanyId, id);
|
||
|
||
try {
|
||
await cancelInboxIssueQueries(queryClient, selectedCompanyId);
|
||
} catch (error) {
|
||
release();
|
||
throw error;
|
||
}
|
||
if (!account.isCurrentScope()) {
|
||
release();
|
||
return { previousData: [] as InboxIssueCacheSnapshot };
|
||
}
|
||
const previousData = snapshotInboxIssueCaches(queryClient, selectedCompanyId);
|
||
removeIssueFromInboxCaches(queryClient, selectedCompanyId, id);
|
||
|
||
return { companyId: selectedCompanyId, previousData, account, release };
|
||
},
|
||
onFinished: (id, context) => {
|
||
if (context?.account && !context.account.isCurrentScope()) context.release();
|
||
setArchivingIssueIds((prev) => {
|
||
const next = new Set(prev);
|
||
next.delete(id);
|
||
return next;
|
||
});
|
||
},
|
||
onError: (err, id, context) => {
|
||
setActionError(describeError(err).body);
|
||
context?.release?.();
|
||
// Restore only this failed archive so overlapping archive mutations stay removed.
|
||
if (context?.previousData) {
|
||
restoreIssueToInboxCaches(queryClient, context.previousData, id);
|
||
}
|
||
},
|
||
onSettled: async (_data, error, id, context) => {
|
||
if (!context?.companyId) return;
|
||
if (!error) boundLocalInboxArchive(context.companyId, id);
|
||
await invalidateTaskArchiveQueries(queryClient, context.companyId);
|
||
if (!error) {
|
||
const presence = getIssuePresenceInActiveInboxCaches(queryClient, context.companyId, id);
|
||
if (presence !== "unknown") confirmLocalInboxArchive(context.companyId, id);
|
||
}
|
||
},
|
||
onSuccess: (_data, id, context) => {
|
||
setUndoableArchiveIssueIds((prev) => [...prev.filter((issueId) => issueId !== id), id]);
|
||
if (surfaceLabel === "Tasks" && context?.account) {
|
||
const { account } = context;
|
||
pushToast({
|
||
id: `archive:${context.companyId}:${id}`,
|
||
dedupe: false,
|
||
title: "Task archived",
|
||
body: issueById.get(id)?.identifier ?? id,
|
||
tone: "success",
|
||
ttlMs: 8000,
|
||
action: {
|
||
label: "Undo",
|
||
onClick: () => {
|
||
if (account.isCurrentAccount()) unarchiveIssueMutation.mutate(id);
|
||
},
|
||
},
|
||
});
|
||
}
|
||
},
|
||
});
|
||
|
||
const unarchiveIssueMutation = useAccountBoundMutation({
|
||
mutationFn: (id: string) => issuesApi.unarchiveFromInbox(id),
|
||
onMutate: (id) => {
|
||
setActionError(null);
|
||
setUnarchivingIssueIds((prev) => new Set(prev).add(id));
|
||
if (selectedCompanyId) clearLocalInboxArchive(selectedCompanyId, id);
|
||
return { companyId: selectedCompanyId };
|
||
},
|
||
onError: (err, id, context) => {
|
||
setActionError(describeError(err).body);
|
||
if (context?.companyId) {
|
||
beginLocalInboxArchive(context.companyId, id);
|
||
boundLocalInboxArchive(context.companyId, id);
|
||
}
|
||
},
|
||
onSuccess: (_data, id) => {
|
||
setUndoableArchiveIssueIds((prev) => {
|
||
const next = prev.filter((issueId) => issueId !== id);
|
||
return next;
|
||
});
|
||
},
|
||
onFinished: (id) => {
|
||
setUnarchivingIssueIds((prev) => {
|
||
const next = new Set(prev);
|
||
next.delete(id);
|
||
return next;
|
||
});
|
||
},
|
||
onSettled: (_data, _error, _id, context) => {
|
||
if (context?.companyId) return invalidateTaskArchiveQueries(queryClient, context.companyId);
|
||
},
|
||
});
|
||
|
||
const markReadMutation = useMutation({
|
||
mutationFn: (id: string) => issuesApi.markRead(id),
|
||
onMutate: (id) => {
|
||
setFadingOutIssues((prev) => new Set(prev).add(id));
|
||
},
|
||
onSuccess: () => {
|
||
invalidateInboxIssueQueryCaches();
|
||
},
|
||
onSettled: (_data, _error, id) => {
|
||
setTimeout(() => {
|
||
setFadingOutIssues((prev) => {
|
||
const next = new Set(prev);
|
||
next.delete(id);
|
||
return next;
|
||
});
|
||
}, 300);
|
||
},
|
||
});
|
||
|
||
const markAllReadMutation = useMutation({
|
||
mutationFn: async (issueIds: string[]) => {
|
||
await Promise.all(issueIds.map((issueId) => issuesApi.markRead(issueId)));
|
||
},
|
||
onMutate: (issueIds) => {
|
||
setFadingOutIssues((prev) => {
|
||
const next = new Set(prev);
|
||
for (const issueId of issueIds) next.add(issueId);
|
||
return next;
|
||
});
|
||
},
|
||
onSuccess: () => {
|
||
invalidateInboxIssueQueryCaches();
|
||
},
|
||
onSettled: (_data, _error, issueIds) => {
|
||
setTimeout(() => {
|
||
setFadingOutIssues((prev) => {
|
||
const next = new Set(prev);
|
||
for (const issueId of issueIds) next.delete(issueId);
|
||
return next;
|
||
});
|
||
}, 300);
|
||
},
|
||
});
|
||
|
||
const markUnreadMutation = useMutation({
|
||
mutationFn: (id: string) => issuesApi.markUnread(id),
|
||
onSuccess: () => {
|
||
invalidateInboxIssueQueryCaches();
|
||
},
|
||
});
|
||
|
||
const handleMarkNonIssueRead = useCallback((key: string) => {
|
||
setFadingNonIssueItems((prev) => new Set(prev).add(key));
|
||
markItemRead(key);
|
||
setTimeout(() => {
|
||
setFadingNonIssueItems((prev) => {
|
||
const next = new Set(prev);
|
||
next.delete(key);
|
||
return next;
|
||
});
|
||
}, 300);
|
||
}, [markItemRead]);
|
||
|
||
const handleArchiveNonIssue = useCallback((key: string) => {
|
||
noteInboxSortInteraction();
|
||
setArchivingNonIssueIds((prev) => new Set(prev).add(key));
|
||
setTimeout(() => {
|
||
if (key.startsWith("alert:")) {
|
||
dismissAlert(key);
|
||
} else {
|
||
dismissInboxItem(key);
|
||
}
|
||
setArchivingNonIssueIds((prev) => {
|
||
const next = new Set(prev);
|
||
next.delete(key);
|
||
return next;
|
||
});
|
||
}, 200);
|
||
}, [dismissAlert, dismissInboxItem, noteInboxSortInteraction]);
|
||
|
||
const nonIssueUnreadState = (key: string): NonIssueUnreadState => {
|
||
if (!canArchiveFromTab) return null;
|
||
const isRead = readItems.has(key);
|
||
const isFading = fadingNonIssueItems.has(key);
|
||
if (isFading) return "fading";
|
||
if (!isRead) return "visible";
|
||
return "hidden";
|
||
};
|
||
|
||
// Keep selection on the same logical item when the list shape changes —
|
||
// rows archived/refreshed above the selection would otherwise shift the
|
||
// numeric index onto a neighboring row (and Enter would open the wrong
|
||
// task). Falls back to clamping when the item is gone; never auto-selects
|
||
// on initial load.
|
||
const selectedNavKeyRef = useRef<string | null>(null);
|
||
useEffect(() => {
|
||
// A reshaped list invalidates the numeric hover index. Re-anchor it to the
|
||
// same row by key (the inbox polls constantly, so nulling it here silently
|
||
// broke hover→j/k sync — PAP-9679). Drop it only when the row is gone.
|
||
const hoveredKey = hoveredNavKeyRef.current;
|
||
const nextHovered =
|
||
hoveredKey === null ? -1 : flatNavItems.findIndex((entry) => navEntryKey(entry) === hoveredKey);
|
||
hoveredIndexRef.current = nextHovered >= 0 ? nextHovered : null;
|
||
if (nextHovered < 0) hoveredNavKeyRef.current = null;
|
||
setSelectedIndex((prev) => {
|
||
if (prev < 0) return resolveInboxSelectionIndex(prev, flatNavItems.length);
|
||
const prevKey = selectedNavKeyRef.current;
|
||
const keyIndex = prevKey === null
|
||
? -1
|
||
: flatNavItems.findIndex((entry) => navEntryKey(entry) === prevKey);
|
||
return keyIndex >= 0 ? keyIndex : resolveInboxSelectionIndex(prev, flatNavItems.length);
|
||
});
|
||
}, [flatNavItems]);
|
||
// Record the selected row's key when the selection moves, or when the
|
||
// recorded row has left the list (the re-anchor then falls back to the row now
|
||
// at that index, often without changing it). Recording on every list change
|
||
// would store the row a refresh inserted above the selection before the
|
||
// re-anchor runs, and move the selection onto it.
|
||
const recordedSelectedIndexRef = useRef(selectedIndex);
|
||
useEffect(() => {
|
||
const recordedKey = selectedNavKeyRef.current;
|
||
const recordedRowListed = recordedKey !== null && flatNavItems.some((entry) => navEntryKey(entry) === recordedKey);
|
||
if (selectedIndex === recordedSelectedIndexRef.current && recordedRowListed) return;
|
||
recordedSelectedIndexRef.current = selectedIndex;
|
||
selectedNavKeyRef.current = selectedIndex >= 0 ? navEntryKey(flatNavItems[selectedIndex]) : null;
|
||
}, [flatNavItems, selectedIndex]);
|
||
|
||
useEffect(() => {
|
||
setUndoableArchiveIssueIds((prev) =>
|
||
prev.filter((issueId) => guardedArchiveIssueIds.has(issueId) || unarchivingIssueIds.has(issueId)),
|
||
);
|
||
}, [guardedArchiveIssueIds, unarchivingIssueIds]);
|
||
|
||
useEffect(() => {
|
||
setUndoableArchiveIssueIds([]);
|
||
setUnarchivingIssueIds(new Set());
|
||
}, [selectedCompanyId]);
|
||
|
||
// Use refs for keyboard handler to avoid stale closures
|
||
const kbStateRef = useRef({
|
||
workItems: groupedSections,
|
||
flatNavItems,
|
||
selectedIndex,
|
||
canArchive: canArchiveFromTab,
|
||
canArchiveTask: canArchiveTaskFromTab,
|
||
gmailArchiveShortcut: surfaceLabel === "Tasks",
|
||
nonInboxSearchIssueIds,
|
||
archivingIssueIds,
|
||
undoableArchiveIssueIds,
|
||
unarchivingIssueIds,
|
||
archivingNonIssueIds,
|
||
fadingOutIssues,
|
||
readItems,
|
||
});
|
||
kbStateRef.current = {
|
||
workItems: groupedSections,
|
||
flatNavItems,
|
||
selectedIndex,
|
||
canArchive: canArchiveFromTab,
|
||
canArchiveTask: canArchiveTaskFromTab,
|
||
gmailArchiveShortcut: surfaceLabel === "Tasks",
|
||
nonInboxSearchIssueIds,
|
||
archivingIssueIds,
|
||
undoableArchiveIssueIds,
|
||
unarchivingIssueIds,
|
||
archivingNonIssueIds,
|
||
fadingOutIssues,
|
||
readItems,
|
||
};
|
||
|
||
const kbActionsRef = useRef({
|
||
archiveIssue: (id: string) => archiveIssueMutation.mutate(id),
|
||
undoArchiveIssue: (id: string) => unarchiveIssueMutation.mutate(id),
|
||
archiveNonIssue: handleArchiveNonIssue,
|
||
markRead: (id: string) => markReadMutation.mutate(id),
|
||
markUnreadIssue: (id: string) => markUnreadMutation.mutate(id),
|
||
markNonIssueRead: handleMarkNonIssueRead,
|
||
markNonIssueUnread: markItemUnread,
|
||
setGroupCollapsed,
|
||
setInboxParentCollapsed,
|
||
navigate,
|
||
});
|
||
kbActionsRef.current = {
|
||
archiveIssue: (id: string) => archiveIssueMutation.mutate(id),
|
||
undoArchiveIssue: (id: string) => unarchiveIssueMutation.mutate(id),
|
||
archiveNonIssue: handleArchiveNonIssue,
|
||
markRead: (id: string) => markReadMutation.mutate(id),
|
||
markUnreadIssue: (id: string) => markUnreadMutation.mutate(id),
|
||
markNonIssueRead: handleMarkNonIssueRead,
|
||
markNonIssueUnread: markItemUnread,
|
||
setGroupCollapsed,
|
||
setInboxParentCollapsed,
|
||
navigate,
|
||
};
|
||
|
||
// Keyboard shortcuts (mail-client style) — single stable listener using refs
|
||
useEffect(() => {
|
||
const handleKeyDown = (e: KeyboardEvent) => {
|
||
if (e.defaultPrevented) return;
|
||
|
||
// Don't capture when typing in inputs/textareas or with modifier keys
|
||
const target = e.target;
|
||
if (
|
||
!(target instanceof HTMLElement) ||
|
||
isKeyboardShortcutTextInputTarget(target) ||
|
||
hasBlockingShortcutDialog(document) ||
|
||
e.metaKey ||
|
||
e.ctrlKey ||
|
||
e.altKey
|
||
) {
|
||
return;
|
||
}
|
||
|
||
const st = kbStateRef.current;
|
||
const act = kbActionsRef.current;
|
||
|
||
const undoArchiveAction = !st.canArchiveTask ? "none" : resolveInboxUndoArchiveKeyAction({
|
||
hasUndoableArchive: st.undoableArchiveIssueIds.length > 0,
|
||
defaultPrevented: e.defaultPrevented,
|
||
key: e.key,
|
||
metaKey: e.metaKey,
|
||
ctrlKey: e.ctrlKey,
|
||
altKey: e.altKey,
|
||
target,
|
||
hasOpenDialog: hasBlockingShortcutDialog(document),
|
||
});
|
||
if (undoArchiveAction === "undo_archive") {
|
||
const issueId = st.undoableArchiveIssueIds[st.undoableArchiveIssueIds.length - 1];
|
||
if (!issueId || st.unarchivingIssueIds.has(issueId)) return;
|
||
e.preventDefault();
|
||
act.undoArchiveIssue(issueId);
|
||
return;
|
||
}
|
||
|
||
const navItems = st.flatNavItems;
|
||
const navCount = navItems.length;
|
||
if (navCount === 0) return;
|
||
|
||
// Any inbox keystroke (nav, archive, undo) is engagement: hold the sort.
|
||
noteInboxSortInteraction();
|
||
|
||
/** Resolve the nav entry at an index to an issue (for child entries) or work item. */
|
||
const resolveNavEntry = (idx: number): { issue?: Issue; item?: InboxWorkItem } => {
|
||
const entry = navItems[idx];
|
||
if (!entry) return {};
|
||
if (entry.type === "child") return { issue: entry.issue };
|
||
if (entry.type === "top") return { item: entry.item };
|
||
return {};
|
||
};
|
||
|
||
// The row a keystroke acts on: the hovered row when the mouse has moved
|
||
// since the last key nav (so "hover a row → press a/r/Enter/Arrow" acts on
|
||
// it), otherwise the keyboard selection. Hover no longer writes selection
|
||
// state, so this is what threads the pointer position into every handler.
|
||
const rawHovered = hoveredIndexRef.current;
|
||
const hoveredIndex = rawHovered != null && rawHovered >= 0 && rawHovered < navCount ? rawHovered : -1;
|
||
const fromHover = pointerMovedSinceKeyNavRef.current && hoveredIndex >= 0;
|
||
const effectiveIndex = fromHover ? hoveredIndex : st.selectedIndex;
|
||
|
||
switch (e.key) {
|
||
case "j":
|
||
case "ArrowDown": {
|
||
e.preventDefault();
|
||
pointerMovedSinceKeyNavRef.current = false;
|
||
setSelectedIndex(getInboxKeyboardSelectionIndex(effectiveIndex, navCount, "next"));
|
||
break;
|
||
}
|
||
case "k":
|
||
case "ArrowUp": {
|
||
e.preventDefault();
|
||
pointerMovedSinceKeyNavRef.current = false;
|
||
setSelectedIndex(getInboxKeyboardSelectionIndex(effectiveIndex, navCount, "previous"));
|
||
break;
|
||
}
|
||
case "ArrowLeft":
|
||
case "ArrowRight": {
|
||
if (effectiveIndex < 0 || effectiveIndex >= navCount) return;
|
||
const entry = navItems[effectiveIndex];
|
||
if (!entry) return;
|
||
if (entry.type === "group") {
|
||
e.preventDefault();
|
||
pointerMovedSinceKeyNavRef.current = false;
|
||
setSelectedIndex(effectiveIndex);
|
||
act.setGroupCollapsed(entry.groupKey, e.key === "ArrowLeft");
|
||
break;
|
||
}
|
||
// Parent tasks collapse/expand with the same keys as groups.
|
||
const { issue, item } = resolveNavEntry(effectiveIndex);
|
||
const targetIssue = issue ?? (item?.kind === "issue" ? item.issue : null);
|
||
if (!targetIssue) return;
|
||
const hasChildren = st.workItems.some(
|
||
(group) => (group.childrenByIssueId.get(targetIssue.id)?.length ?? 0) > 0,
|
||
);
|
||
if (!hasChildren) return;
|
||
e.preventDefault();
|
||
pointerMovedSinceKeyNavRef.current = false;
|
||
setSelectedIndex(effectiveIndex);
|
||
act.setInboxParentCollapsed(targetIssue.id, e.key === "ArrowLeft");
|
||
break;
|
||
}
|
||
case "a":
|
||
case "y":
|
||
case "e": {
|
||
if (!st.canArchiveTask || (e.key === "e" && !st.gmailArchiveShortcut)) return;
|
||
if (effectiveIndex < 0 || effectiveIndex >= navCount) return;
|
||
e.preventDefault();
|
||
const { issue, item } = resolveNavEntry(effectiveIndex);
|
||
if (issue) {
|
||
if (!st.nonInboxSearchIssueIds.has(issue.id) && !st.archivingIssueIds.has(issue.id)) act.archiveIssue(issue.id);
|
||
} else if (item) {
|
||
if (item.kind === "issue") {
|
||
if (!st.nonInboxSearchIssueIds.has(item.issue.id) && !st.archivingIssueIds.has(item.issue.id)) {
|
||
act.archiveIssue(item.issue.id);
|
||
}
|
||
} else if (st.canArchive) {
|
||
const key = getInboxWorkItemKey(item);
|
||
if (!st.archivingNonIssueIds.has(key)) act.archiveNonIssue(key);
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
case "U": {
|
||
if (!st.canArchive) return;
|
||
if (effectiveIndex < 0 || effectiveIndex >= navCount) return;
|
||
e.preventDefault();
|
||
const { issue, item } = resolveNavEntry(effectiveIndex);
|
||
if (issue) {
|
||
act.markUnreadIssue(issue.id);
|
||
} else if (item) {
|
||
if (item.kind === "issue") act.markUnreadIssue(item.issue.id);
|
||
else act.markNonIssueUnread(getInboxWorkItemKey(item));
|
||
}
|
||
break;
|
||
}
|
||
case "r": {
|
||
if (!st.canArchive) return;
|
||
if (effectiveIndex < 0 || effectiveIndex >= navCount) return;
|
||
e.preventDefault();
|
||
const { issue, item } = resolveNavEntry(effectiveIndex);
|
||
if (issue) {
|
||
if (issue.isUnreadForMe && !st.fadingOutIssues.has(issue.id)) act.markRead(issue.id);
|
||
} else if (item) {
|
||
if (item.kind === "issue") {
|
||
if (item.issue.isUnreadForMe && !st.fadingOutIssues.has(item.issue.id)) act.markRead(item.issue.id);
|
||
} else {
|
||
const key = getInboxWorkItemKey(item);
|
||
if (!st.readItems.has(key)) act.markNonIssueRead(key);
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
case "Enter": {
|
||
if (effectiveIndex < 0 || effectiveIndex >= navCount) return;
|
||
e.preventDefault();
|
||
const { issue, item } = resolveNavEntry(effectiveIndex);
|
||
if (issue) {
|
||
const pathId = issue.identifier ?? issue.id;
|
||
const detailState = armIssueDetailInboxQuickArchive(withIssueDetailHeaderSeed(issueLinkState, issue));
|
||
rememberIssueDetailLocationState(pathId, detailState);
|
||
void prefetchIssueDetailForNavigation(queryClient, pathId, { issue, history: true });
|
||
act.navigate(createIssueDetailPath(pathId), { state: detailState });
|
||
} else if (item) {
|
||
if (item.kind === "issue") {
|
||
const pathId = item.issue.identifier ?? item.issue.id;
|
||
const detailState = armIssueDetailInboxQuickArchive(
|
||
withIssueDetailHeaderSeed(issueLinkState, item.issue),
|
||
);
|
||
rememberIssueDetailLocationState(pathId, detailState);
|
||
void prefetchIssueDetailForNavigation(queryClient, pathId, { issue: item.issue, history: true });
|
||
act.navigate(createIssueDetailPath(pathId), { state: detailState });
|
||
} else if (item.kind === "approval") {
|
||
act.navigate(`/approvals/${item.approval.id}`);
|
||
} else if (item.kind === "failed_run") {
|
||
act.navigate(`/agents/${item.run.agentId}/runs/${item.run.id}`);
|
||
}
|
||
}
|
||
break;
|
||
}
|
||
default:
|
||
return;
|
||
}
|
||
};
|
||
window.addEventListener("keydown", handleKeyDown);
|
||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||
}, [issueLinkState, noteInboxSortInteraction]);
|
||
|
||
// Scroll selected item into view
|
||
useEffect(() => {
|
||
if (selectedIndex < 0 || !listRef.current) return;
|
||
const rows = listRef.current.querySelectorAll("[data-inbox-item]");
|
||
const row = rows[selectedIndex];
|
||
if (row) row.scrollIntoView({ block: "nearest" });
|
||
}, [selectedIndex]);
|
||
|
||
const hasRunFailures = failedRuns.length > 0;
|
||
const showCompanyAlerts = shouldShowCompanyAlerts(tab) && showAlertsCategory;
|
||
const showAggregateAgentError =
|
||
showCompanyAlerts &&
|
||
!!dashboard &&
|
||
dashboard.agents.error > 0 &&
|
||
!hasRunFailures &&
|
||
!dismissedAlerts.has("alert:agent-errors");
|
||
const showBudgetAlert =
|
||
showCompanyAlerts &&
|
||
!!dashboard &&
|
||
dashboard.costs.monthBudgetCents > 0 &&
|
||
dashboard.costs.monthUtilizationPercent >= 80 &&
|
||
!dismissedAlerts.has("alert:budget");
|
||
const hasAlerts = showAggregateAgentError || showBudgetAlert;
|
||
const showWorkItemsSection = totalVisibleWorkItems > 0;
|
||
const showAlertsSection = shouldShowInboxSection({
|
||
tab,
|
||
hasItems: hasAlerts,
|
||
showOnMine: false,
|
||
showOnRecent: false,
|
||
showOnUnread: false,
|
||
showOnAll: hasAlerts,
|
||
});
|
||
|
||
const visibleSections = [
|
||
showAlertsSection ? "alerts" : null,
|
||
showWorkItemsSection ? "work_items" : null,
|
||
].filter((key): key is SectionKey => key !== null);
|
||
|
||
// Workspace names change what rows show (grouping, the Workspace column) or which rows match a
|
||
// search, so wait for them only then; otherwise rows reveal without the workspace read.
|
||
const workspaceDataAffectsRows = groupBy === "workspace"
|
||
|| (visibleIssueColumnSet.has("workspace") && availableIssueColumnSet.has("workspace"))
|
||
|| normalizedSearchQuery.length > 0;
|
||
// Approvals and join requests sort in among task rows by time, so a late arrival would push
|
||
// rows down. Wait for their first bounded attempt only; a failure or timeout reveals rows.
|
||
const approvalsAffectRows = tab !== "blocked" && (tab !== "all" || showApprovalsCategory);
|
||
const joinRequestsAffectRows = tab !== "blocked" && (tab !== "all" || showJoinRequestsCategory);
|
||
// Saved values from the last visit answer this wait on a returning visit.
|
||
const isApprovalsFirstAttemptPending = isApprovalsLoading && approvalsFailureCount === 0 && !approvalsFromSaved;
|
||
const isJoinRequestsFirstAttemptPending = isJoinRequestsLoading && joinRequestsFailureCount === 0 && !joinRequestsFromSaved;
|
||
// User names only fill row text, except when they name and order assignee groups.
|
||
const userLabelsAffectRows = groupBy === "assignee";
|
||
const isMembersFirstAttemptPending = isMembersLoading && membersFailureCount === 0;
|
||
const initialSourcesSettled =
|
||
![sourceSearchView, mineIssuesView, touchedIssuesView].some(view => view.kind === "reconnecting") &&
|
||
!isSourceSearchLoading && !isSessionLoading && !isSettingsLoading && !isDismissalsLoading && !isAgentsLoading && !isProjectsLoading &&
|
||
!(userLabelsAffectRows && isMembersFirstAttemptPending) &&
|
||
// Previous summaries stand in while a new id set loads; they may lack the new view's workspaces.
|
||
!(workspaceDataAffectsRows && workspaceLookupEnabled && (isWorkspacesLoading || isWorkspacesPlaceholder)) &&
|
||
!(joinRequestsAffectRows && isJoinRequestsFirstAttemptPending) &&
|
||
!(approvalsAffectRows && isApprovalsFirstAttemptPending) &&
|
||
!isDashboardLoading &&
|
||
!isContextIssuesLoading &&
|
||
!isContextIssuesPlaceholder &&
|
||
!isMineIssuesLoading &&
|
||
!isTouchedIssuesLoading &&
|
||
!isRunsLoading
|
||
&& (!issueFilters.liveOnly || !isLiveRunsLoading)
|
||
&& (issueFilters.externalObjectStatuses.length === 0 || externalObjectSummariesReady || !!externalObjectSummariesError);
|
||
const sourceView = tab === "mine" ? mineIssuesView : touchedIssuesView;
|
||
const listError = (sourceSearchView.kind === "error" ? sourceSearchError : null)
|
||
?? (sourceView.kind === "error" ? sourceView.error : null)
|
||
?? (issueFilters.externalObjectStatuses.length > 0 ? externalObjectSummariesError : null);
|
||
const rawOptionalSourceError = dismissalsError ?? approvalsError ?? joinRequestsError ?? runsError ?? contextIssuesError
|
||
?? (tab === "mine" ? mineIssuesError : touchedIssuesError);
|
||
// A query error means retries are over. Transient errors usually clear on their own, but a read
|
||
// that keeps hitting the inbox timeout leaves items missing, so say so and offer a retry.
|
||
const optionalReadTimeoutError = [approvalsError, joinRequestsError]
|
||
.find((error) => errorCodes(error).includes("TIMEOUT")) ?? null;
|
||
const optionalSourceError = optionalReadTimeoutError
|
||
?? (isTransientError(rawOptionalSourceError) ? null : rawOptionalSourceError);
|
||
const retryFailedSources = () => {
|
||
// Optional failures belong to the aggregate read, whose task rows stay usable.
|
||
if (tab === "mine" && (mineSnapshot?.failureError || mineSnapshot?.contextError)) {
|
||
void queryClient.refetchQueries({ queryKey: mineIssuesQueryKey, exact: true });
|
||
}
|
||
// Retry only failed reads for this company; settled rows stay visible.
|
||
void queryClient.refetchQueries({ predicate: (query) => query.state.status === "error"
|
||
&& query.queryKey.includes(selectedCompanyId), type: "active" });
|
||
};
|
||
|
||
const revealScope = JSON.stringify([currentUserId, selectedCompanyId, tab, normalizedSearchQuery, issueFilters]);
|
||
const [revealedScope, setRevealedScope] = useState<string | null>(null);
|
||
useEffect(() => {
|
||
if (initialSourcesSettled && !listError) setRevealedScope(revealScope);
|
||
}, [initialSourcesSettled, listError, revealScope]);
|
||
const allLoaded = initialSourcesSettled || revealedScope === revealScope;
|
||
useWarmTaskDetailCode(allLoaded && !listError && tab !== "blocked" && showWorkItemsSection);
|
||
// Preload the chat of the top visible tasks, in display order, so opening
|
||
// one renders its latest messages and composer from cache.
|
||
// The walk stops at the preload limit, whatever the size of the Inbox.
|
||
const preloadTaskRefs = useMemo(() => topTaskRefs(flatNavItems, inboxNavEntryTask), [flatNavItems]);
|
||
usePreloadTaskChats(selectedCompanyId, preloadTaskRefs, allLoaded && !listError && showWorkItemsSection);
|
||
|
||
const showSeparatorBefore = (key: SectionKey) => visibleSections.indexOf(key) > 0;
|
||
const { enrichIssueRow, error: rowDetailsError, retry: retryRowDetails } = useIssueRowDetails(
|
||
selectedCompanyId, listRef,
|
||
groupedSections.map((group) => group.key + ":" + group.displayItems.map(getInboxWorkItemKey).join(",") + ":" + [...group.childrenByIssueId.values()].flat().map((issue) => issue.id).join(",")).join("|")
|
||
+ ":" + [...collapsedInboxParents].join(",") + ":" + [...collapsedGroupKeys].join(","),
|
||
allLoaded && !listError && tab !== "blocked",
|
||
issues,
|
||
);
|
||
|
||
if (!selectedCompanyId) {
|
||
return <EmptyState icon={InboxIcon} message={`Select an organization to view ${surfaceLabel.toLowerCase()}.`} />;
|
||
}
|
||
|
||
const markAllReadIssues = (tab === "mine" ? visibleMineIssues : unreadTouchedIssues)
|
||
.filter((issue) => issue.isUnreadForMe && !fadingOutIssues.has(issue.id) && !archivingIssueIds.has(issue.id));
|
||
const unreadIssueIds = markAllReadIssues
|
||
.map((issue) => issue.id);
|
||
const canMarkAllRead = unreadIssueIds.length > 0;
|
||
const activeIssueFilterCount = countActiveIssueFilters(issueFilters, true);
|
||
const activeInboxScopeFilterCount = tab === "all"
|
||
? Number(allCategoryFilter !== "everything")
|
||
+ Number(showApprovalsCategory && allApprovalFilter !== "all")
|
||
: 0;
|
||
const activeFilterCount = activeIssueFilterCount + activeInboxScopeFilterCount;
|
||
const showGeneralIssueToolbarControls = tab !== "blocked";
|
||
const activeStatusFilterApplied =
|
||
issueFilters.statuses.length === 4
|
||
&& ["todo", "in_progress", "in_review", "blocked"].every((status) =>
|
||
issueFilters.statuses.includes(status as IssueFilterState["statuses"][number]),
|
||
);
|
||
const issueFilterFeedback = issueFilters.liveOnly
|
||
? "Live runs only — tasks currently connected to an agent run."
|
||
: activeStatusFilterApplied
|
||
? "Active statuses — open tasks, whether or not an agent is running."
|
||
: null;
|
||
return (
|
||
<div className="space-y-6">
|
||
<IssueRowDetailsNotice
|
||
error={optionalSourceError ?? rowDetailsError}
|
||
message={optionalSourceError ? "Some inbox items couldn’t load. Showing available items." : undefined}
|
||
retryLabel={optionalSourceError ? "Retry missing items" : undefined}
|
||
onRetry={optionalSourceError ? retryFailedSources : () => void retryRowDetails()}
|
||
/>
|
||
<InboxCollectionToolbar
|
||
streamlined={streamlinedUiEnabled}
|
||
ariaLabel={`${surfaceLabel} controls`}
|
||
context={toolbarContext ?? (
|
||
<Tabs value={tab} onValueChange={(value) => navigate(`/inbox/${value}`)}>
|
||
<PageTabBar
|
||
items={[
|
||
{ value: "mine", label: "Mine" },
|
||
{ value: "recent", label: "Recent" },
|
||
{ value: "unread", label: "Unread" },
|
||
{ value: "blocked", label: "Blocked" },
|
||
{ value: "all", label: "All" },
|
||
]}
|
||
/>
|
||
</Tabs>
|
||
)}
|
||
search={(
|
||
<div className="relative ml-auto w-full sm:w-(--sz-220px)">
|
||
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
|
||
<Input
|
||
type="search"
|
||
placeholder={`Search ${surfaceLabel.toLowerCase()}…`}
|
||
value={searchQuery}
|
||
onChange={(e) => setSearchQuery(e.target.value)}
|
||
onKeyDown={(e) => {
|
||
if (shouldBlurPageSearchOnEnter({
|
||
key: e.key,
|
||
isComposing: e.nativeEvent.isComposing,
|
||
})) {
|
||
e.currentTarget.blur();
|
||
return;
|
||
}
|
||
|
||
if (shouldBlurPageSearchOnEscape({
|
||
key: e.key,
|
||
isComposing: e.nativeEvent.isComposing,
|
||
currentValue: e.currentTarget.value,
|
||
})) {
|
||
e.currentTarget.blur();
|
||
}
|
||
}}
|
||
className="h-8 w-full pl-8 text-xs"
|
||
data-page-search-target="true"
|
||
/>
|
||
</div>
|
||
)}
|
||
controls={(
|
||
<>
|
||
{tab === "blocked" ? (
|
||
<>
|
||
<IssueFiltersPopover
|
||
state={issueFilters}
|
||
onChange={updateIssueFilters}
|
||
activeFilterCount={activeIssueFilterCount}
|
||
agents={agents}
|
||
creators={creatorOptions}
|
||
projects={projects?.map((project) => ({ id: project.id, name: project.name }))}
|
||
labels={labels?.map((label) => ({ id: label.id, name: label.name, color: label.color }))}
|
||
currentUserId={currentUserId}
|
||
enableExternalObjectFilters={externalObjectsEnabled}
|
||
enableAgentCreatedVisibilityFilter
|
||
buttonVariant="outline"
|
||
iconOnly
|
||
presentation={streamlinedUiEnabled ? "streamlined" : "legacy"}
|
||
/>
|
||
<Popover>
|
||
<PopoverTrigger asChild>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
size="icon"
|
||
className={cn("h-8 w-8 shrink-0", blockedGroupBy !== "none" && "bg-accent")}
|
||
title="Group"
|
||
>
|
||
<Layers className="h-3.5 w-3.5" />
|
||
</Button>
|
||
</PopoverTrigger>
|
||
<PopoverContent align="end" className="w-44 p-0">
|
||
<div className="space-y-0.5 p-2">
|
||
{BLOCKED_GROUP_OPTIONS.map(([value, label]) => (
|
||
<button
|
||
key={value}
|
||
type="button"
|
||
className={cn(
|
||
"flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",
|
||
blockedGroupBy === value ? "bg-accent/50 text-foreground" : "text-muted-foreground hover:bg-accent/50",
|
||
)}
|
||
onClick={() => setBlockedGroupBy(value)}
|
||
>
|
||
<span>{label}</span>
|
||
{blockedGroupBy === value ? <Check className="h-3.5 w-3.5" /> : null}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</PopoverContent>
|
||
</Popover>
|
||
<IssueColumnPicker
|
||
availableColumns={availableIssueColumns}
|
||
visibleColumnSet={visibleIssueColumnSet}
|
||
onToggleColumn={toggleIssueColumn}
|
||
showDateGroupSeparators={filterPreferences.showDateGroupSeparators}
|
||
onToggleDateGroupSeparators={(enabled) => {
|
||
updateFilterPreferences((previous) => ({
|
||
...previous,
|
||
showDateGroupSeparators: enabled,
|
||
}));
|
||
}}
|
||
onResetColumns={() => setIssueColumns(DEFAULT_INBOX_ISSUE_COLUMNS)}
|
||
title="Choose which columns stay visible"
|
||
iconOnly
|
||
/>
|
||
<Popover>
|
||
<PopoverTrigger asChild>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
size="icon"
|
||
className="h-8 w-8 shrink-0"
|
||
title="Sort"
|
||
>
|
||
<ArrowUpDown className="h-3.5 w-3.5" />
|
||
</Button>
|
||
</PopoverTrigger>
|
||
<PopoverContent align="end" className="w-48 p-0">
|
||
<div className="space-y-0.5 p-2">
|
||
{BLOCKED_SORT_OPTIONS.map(([value, label]) => (
|
||
<button
|
||
key={value}
|
||
type="button"
|
||
className={cn(
|
||
"flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",
|
||
blockedSortBy === value ? "bg-accent/50 text-foreground" : "text-muted-foreground hover:bg-accent/50",
|
||
)}
|
||
onClick={() => setBlockedSortBy(value)}
|
||
>
|
||
<span>{label}</span>
|
||
{blockedSortBy === value ? <Check className="h-3.5 w-3.5" /> : null}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</PopoverContent>
|
||
</Popover>
|
||
</>
|
||
) : showGeneralIssueToolbarControls ? (
|
||
<>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
size="icon"
|
||
className={cn("hidden h-8 w-8 shrink-0 sm:inline-flex", nestingEnabled && "bg-accent")}
|
||
onClick={toggleNesting}
|
||
title={nestingEnabled ? "Disable parent-child nesting" : "Enable parent-child nesting"}
|
||
>
|
||
<ListTree className="h-3.5 w-3.5" />
|
||
</Button>
|
||
<IssueFiltersPopover
|
||
state={issueFilters}
|
||
onChange={updateIssueFilters}
|
||
activeFilterCount={activeFilterCount}
|
||
agents={agents}
|
||
creators={creatorOptions}
|
||
projects={projects?.map((project) => ({ id: project.id, name: project.name }))}
|
||
labels={labels?.map((label) => ({ id: label.id, name: label.name, color: label.color }))}
|
||
currentUserId={currentUserId}
|
||
enableExternalObjectFilters={externalObjectsEnabled}
|
||
enableAgentCreatedVisibilityFilter
|
||
buttonVariant="outline"
|
||
iconOnly
|
||
presentation={streamlinedUiEnabled ? "streamlined" : "legacy"}
|
||
inboxScopeFilters={tab === "all" ? {
|
||
category: allCategoryFilter,
|
||
approvalStatus: allApprovalFilter,
|
||
showApprovalStatus: showApprovalsCategory,
|
||
onCategoryChange: updateAllCategoryFilter,
|
||
onApprovalStatusChange: updateAllApprovalFilter,
|
||
onClear: () => {
|
||
updateFilterPreferences((previous) => ({
|
||
...previous,
|
||
allCategoryFilter: "everything",
|
||
allApprovalFilter: "all",
|
||
}));
|
||
},
|
||
} : undefined}
|
||
/>
|
||
<Popover>
|
||
<PopoverTrigger asChild>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
size="icon"
|
||
className={cn("h-8 w-8 shrink-0", groupBy !== "none" && "bg-accent")}
|
||
title="Group"
|
||
>
|
||
<Layers className="h-3.5 w-3.5" />
|
||
</Button>
|
||
</PopoverTrigger>
|
||
<PopoverContent align="end" className="w-40 p-2">
|
||
<div className="space-y-0.5">
|
||
{([
|
||
["none", "None"],
|
||
["type", "Type"],
|
||
["assignee", "Responsible"],
|
||
["project", "Project"],
|
||
...(isolatedWorkspacesEnabled ? ([["workspace", "Workspace"]] as const) : []),
|
||
] as const).map(([value, label]) => (
|
||
<button
|
||
key={value}
|
||
type="button"
|
||
className={cn(
|
||
"flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",
|
||
groupBy === value ? "bg-accent/50 text-foreground" : "text-muted-foreground hover:bg-accent/50",
|
||
)}
|
||
onClick={() => updateGroupBy(value)}
|
||
>
|
||
<span>{label}</span>
|
||
{groupBy === value ? <Check className="h-3.5 w-3.5" /> : null}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</PopoverContent>
|
||
</Popover>
|
||
<IssueColumnPicker
|
||
availableColumns={availableIssueColumns}
|
||
visibleColumnSet={visibleIssueColumnSet}
|
||
onToggleColumn={toggleIssueColumn}
|
||
showDateGroupSeparators={filterPreferences.showDateGroupSeparators}
|
||
onToggleDateGroupSeparators={(enabled) => {
|
||
updateFilterPreferences((previous) => ({
|
||
...previous,
|
||
showDateGroupSeparators: enabled,
|
||
}));
|
||
}}
|
||
onResetColumns={() => setIssueColumns(DEFAULT_INBOX_ISSUE_COLUMNS)}
|
||
title="Choose which columns stay visible"
|
||
iconOnly
|
||
rowPresentation={streamlinedUiEnabled ? "task" : "legacy"}
|
||
/>
|
||
{canMarkAllRead && (
|
||
<>
|
||
<Button
|
||
type="button"
|
||
variant="outline"
|
||
size="sm"
|
||
className="h-8 shrink-0"
|
||
onClick={() => setShowMarkAllReadConfirm(true)}
|
||
disabled={markAllReadMutation.isPending}
|
||
>
|
||
{markAllReadMutation.isPending ? "Marking…" : "Mark all as read"}
|
||
</Button>
|
||
<Dialog open={showMarkAllReadConfirm} onOpenChange={setShowMarkAllReadConfirm}>
|
||
<DialogContent className="sm:max-w-md">
|
||
<DialogHeader>
|
||
<DialogTitle>Mark all as read?</DialogTitle>
|
||
<DialogDescription>
|
||
This will mark {unreadIssueIds.length} unread {unreadIssueIds.length === 1 ? "item" : "items"} as read.
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
<DialogFooter>
|
||
<Button variant="outline" onClick={() => setShowMarkAllReadConfirm(false)}>
|
||
Cancel
|
||
</Button>
|
||
<Button
|
||
onClick={() => {
|
||
setShowMarkAllReadConfirm(false);
|
||
markAllReadMutation.mutate(unreadIssueIds);
|
||
}}
|
||
>
|
||
Mark all as read
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
</>
|
||
)}
|
||
</>
|
||
) : null}
|
||
</>
|
||
)}
|
||
feedback={issueFilterFeedback ? (
|
||
<p className="text-xs text-muted-foreground" data-testid="inbox-filter-scope-feedback">
|
||
{issueFilterFeedback}
|
||
</p>
|
||
) : null}
|
||
/>
|
||
|
||
{listError && (
|
||
<div role="alert" className="flex items-center gap-2 text-sm text-destructive">
|
||
<p>Unable to load the inbox: {describeError(listError).body}</p>
|
||
<Button variant="outline" size="sm" onClick={() => { retryFailedSources(); if (externalObjectSummariesError) retryExternalObjectSummaries(); }}>Retry</Button>
|
||
</div>
|
||
)}
|
||
{actionError && <p className="text-sm text-destructive">{actionError}</p>}
|
||
|
||
{tab === "blocked" ? (
|
||
<div className="-mx-2 sm:mx-0">
|
||
<BlockedInboxView
|
||
companyId={selectedCompanyId!}
|
||
searchQuery={searchQuery}
|
||
agentNameById={agentById} agents={agents}
|
||
userLabelById={companyUserLabelMap}
|
||
issueLinkState={issueLinkState}
|
||
groupBy={blockedGroupBy}
|
||
sortBy={blockedSortBy}
|
||
issueFilters={issueFilters}
|
||
currentUserId={currentUserId}
|
||
liveIssueIds={liveIssueIds}
|
||
subtreeLiveCounts={subtreeLiveCounts}
|
||
workspaceFilterContext={inboxWorkspaceGrouping}
|
||
showStatusColumn={visibleIssueColumnSet.has("status") && availableIssueColumnSet.has("status")}
|
||
showIdentifierColumn={visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")}
|
||
showUpdatedColumn={visibleIssueColumnSet.has("updated") && availableIssueColumnSet.has("updated")}
|
||
presentation={streamlinedUiEnabled ? "task" : "legacy"}
|
||
/>
|
||
</div>
|
||
) : null}
|
||
|
||
{tab !== "blocked" && !allLoaded && !listError && (
|
||
<PageSkeleton variant="inbox" collectionHeading={groupBy !== "none" ? "group" : filterPreferences.showDateGroupSeparators ? "date" : null} />
|
||
)}
|
||
|
||
{tab !== "blocked" && allLoaded && !listError && !optionalSourceError && visibleSections.length === 0 && (
|
||
<EmptyState
|
||
icon={searchQuery.trim() ? Search : InboxIcon}
|
||
message={
|
||
searchQuery.trim()
|
||
? "No inbox items match your search."
|
||
: tab === "mine"
|
||
? "Inbox zero."
|
||
: tab === "unread"
|
||
? "No new inbox items."
|
||
: tab === "recent"
|
||
? "No recent inbox items."
|
||
: "No inbox items match these filters."
|
||
}
|
||
/>
|
||
)}
|
||
|
||
{tab !== "blocked" && allLoaded && !listError && showWorkItemsSection && (
|
||
<>
|
||
{showSeparatorBefore("work_items") && <Separator />}
|
||
<div>
|
||
<div
|
||
ref={listRef}
|
||
className="-mx-2 overflow-hidden sm:mx-0"
|
||
onPointerDownCapture={noteInboxSortInteraction}
|
||
onWheelCapture={noteInboxSortInteraction}
|
||
>
|
||
{(() => {
|
||
const renderInboxIssue = ({
|
||
issue,
|
||
depth,
|
||
selected,
|
||
hasChildren = false,
|
||
isExpanded = false,
|
||
childCount = 0,
|
||
collapseParentId = null,
|
||
allowArchive = canArchiveTaskFromTab,
|
||
}: {
|
||
issue: Issue;
|
||
depth: number;
|
||
selected: boolean;
|
||
hasChildren?: boolean;
|
||
isExpanded?: boolean;
|
||
childCount?: number;
|
||
collapseParentId?: string | null;
|
||
allowArchive?: boolean;
|
||
}) => {
|
||
issue = enrichIssueRow(issue);
|
||
const isUnread = issue.isUnreadForMe && !fadingOutIssues.has(issue.id);
|
||
const isFading = fadingOutIssues.has(issue.id);
|
||
const isArchiving = archivingIssueIds.has(issue.id);
|
||
const project = issue.projectId ? projectById.get(issue.projectId) ?? null : null;
|
||
const assigneeUserProfile = issue.assigneeUserId
|
||
? companyUserProfileMap.get(issue.assigneeUserId) ?? null
|
||
: null;
|
||
const originatingActor = deriveOriginatingActor(issue);
|
||
const originatingUserId = originatingActor?.kind === "user" ? originatingActor.id : null;
|
||
const originatingViaAgentId =
|
||
originatingActor?.kind === "user" ? originatingActor.viaAgentId ?? null : null;
|
||
const isLive = liveIssueIds.has(issue.id);
|
||
const loadedSubtreeLiveCount = subtreeLiveCounts.get(issue.id) ?? 0;
|
||
const runningDescendantCount = resolveIssueRunningDescendantCount(issue, subtreeCounts.running.get(issue.id) ?? 0);
|
||
const blockerAttention = resolveInboxIssueBlockerAttention(issue, {
|
||
isLive,
|
||
loadedSubtreeLiveCount,
|
||
});
|
||
const showStatus = visibleIssueColumnSet.has("status") && availableIssueColumnSet.has("status");
|
||
const showSubtreeLiveChip = !(
|
||
showStatus
|
||
&& issue.status === "blocked"
|
||
&& blockerAttention?.state === "covered"
|
||
);
|
||
const rowStatusIcon = (
|
||
<StatusIcon {...taskStatusIconProps(issue)} blockerAttention={blockerAttention} size="md" />
|
||
);
|
||
return (
|
||
<IssueRow
|
||
key={`issue:${issue.id}`}
|
||
issue={issue}
|
||
presentation={streamlinedUiEnabled ? "task" : "legacy"}
|
||
stableLayout
|
||
issueLinkState={issueLinkState}
|
||
treeGuides={depth}
|
||
chevronInGuide={streamlinedUiEnabled && depth > 0 && hasChildren}
|
||
selected={selected}
|
||
className={
|
||
isArchiving
|
||
? "pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out"
|
||
: "transition-all duration-200 ease-out"
|
||
}
|
||
leadingControl={streamlinedUiEnabled && nestingEnabled && hasChildren && collapseParentId ? (
|
||
<button
|
||
type="button"
|
||
data-slot="icon-button"
|
||
className="inline-flex h-4 w-4 shrink-0 items-center justify-center"
|
||
aria-label={isExpanded ? "Collapse sub-tasks" : "Expand sub-tasks"}
|
||
onClick={(event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
toggleInboxParentCollapse(collapseParentId);
|
||
}}
|
||
>
|
||
<ChevronRight className={cn("h-3.5 w-3.5 transition-transform", isExpanded && "rotate-90")} />
|
||
</button>
|
||
) : streamlinedUiEnabled ? (
|
||
<span data-slot="task-row-disclosure-spacer" className={cn("h-4 w-4 shrink-0", !nestingEnabled && "hidden sm:block")} aria-hidden="true" />
|
||
) : undefined}
|
||
statusSlot={streamlinedUiEnabled ? rowStatusIcon : undefined}
|
||
metadata={streamlinedUiEnabled ? (
|
||
<InboxIssueMetaLeading
|
||
issue={issue}
|
||
isLive={isLive}
|
||
waiting={issueWaitingOf(liveIssueIds, issue.id)}
|
||
subtreeLiveCount={runningDescendantCount}
|
||
showSubtreeLiveChip={showSubtreeLiveChip}
|
||
showStatus={false}
|
||
showIdentifier={false}
|
||
/>
|
||
) : undefined}
|
||
showIdentifier={streamlinedUiEnabled
|
||
? visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")
|
||
: undefined}
|
||
desktopMetaLeading={!streamlinedUiEnabled ? (
|
||
<>
|
||
{nestingEnabled ? (
|
||
depth === 0 && hasChildren && collapseParentId ? (
|
||
<button
|
||
type="button"
|
||
data-slot="icon-button"
|
||
className="hidden w-4 shrink-0 items-center justify-center sm:inline-flex"
|
||
onClick={(event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
toggleInboxParentCollapse(collapseParentId);
|
||
}}
|
||
>
|
||
<ChevronRight className={cn("h-3.5 w-3.5 transition-transform", isExpanded && "rotate-90")} />
|
||
</button>
|
||
) : (
|
||
<span className="hidden w-4 shrink-0 sm:block" />
|
||
)
|
||
) : null}
|
||
<InboxIssueMetaLeading
|
||
issue={issue}
|
||
isLive={isLive}
|
||
waiting={issueWaitingOf(liveIssueIds, issue.id)}
|
||
subtreeLiveCount={runningDescendantCount}
|
||
showSubtreeLiveChip={showSubtreeLiveChip}
|
||
showStatus={showStatus}
|
||
showIdentifier={visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")}
|
||
statusSlot={rowStatusIcon}
|
||
/>
|
||
</>
|
||
) : undefined}
|
||
titleSuffix={hasChildren && !isExpanded ? (
|
||
<span className="ml-1.5 text-xs text-muted-foreground">
|
||
({childCount} sub-task{childCount !== 1 ? "s" : ""})
|
||
</span>
|
||
) : undefined}
|
||
mobileTitleMeta={streamlinedUiEnabled ? issueActivityTimestamp(issue) : undefined}
|
||
mobileMeta={streamlinedUiEnabled ? undefined : issueActivityText(issue).toLowerCase()}
|
||
mobileLeading={!streamlinedUiEnabled ? (
|
||
depth === 0 && hasChildren && collapseParentId ? (
|
||
<button
|
||
type="button"
|
||
data-slot="icon-button"
|
||
onClick={(event) => {
|
||
event.preventDefault();
|
||
event.stopPropagation();
|
||
toggleInboxParentCollapse(collapseParentId);
|
||
}}
|
||
>
|
||
<ChevronRight className={cn("h-3.5 w-3.5 transition-transform", isExpanded && "rotate-90")} />
|
||
</button>
|
||
) : (
|
||
<StatusIcon {...taskStatusIconProps(issue)} blockerAttention={blockerAttention} size="md" />
|
||
)
|
||
) : undefined}
|
||
unreadState={isUnread ? "visible" : isFading ? "fading" : "hidden"}
|
||
showUnreadIndicator={false}
|
||
onMarkRead={() => markReadMutation.mutate(issue.id)}
|
||
onArchive={allowArchive ? () => archiveIssueMutation.mutate(issue.id) : undefined}
|
||
archiveDisabled={isArchiving}
|
||
desktopTrailing={
|
||
(streamlinedUiEnabled ? visibleTaskDataColumns : visibleTrailingIssueColumns).length > 0 ? (
|
||
<InboxIssueTrailingColumns
|
||
issue={issue}
|
||
columns={streamlinedUiEnabled ? visibleTaskDataColumns : visibleTrailingIssueColumns}
|
||
projectName={project?.name ?? null}
|
||
projectColor={project?.color ?? null}
|
||
workspaceName={resolveIssueWorkspaceName(issue, {
|
||
executionWorkspaceById,
|
||
projectWorkspaceById,
|
||
defaultProjectWorkspaceIdByProjectId,
|
||
})}
|
||
assigneeName={agentName(issue.assigneeAgentId)}
|
||
assigneeAgent={agents?.find((agent) => agent.id === issue.assigneeAgentId)}
|
||
creatorAgent={agents?.find((agent) => agent.id === issue.createdByAgentId)}
|
||
assigneeUserName={
|
||
formatAssigneeUserLabel(issue.assigneeUserId, currentUserId, companyUserLabelMap)
|
||
?? assigneeUserProfile?.label
|
||
?? null
|
||
}
|
||
assigneeUserAvatarUrl={assigneeUserProfile?.image ?? null}
|
||
creatorAgentName={agentName(issue.createdByAgentId)}
|
||
creatorUserName={originatingUserId ? (companyUserProfileMap.get(originatingUserId)?.label ?? null) : null}
|
||
creatorUserAvatarUrl={originatingUserId ? (companyUserProfileMap.get(originatingUserId)?.image ?? null) : null}
|
||
viaAgentName={originatingViaAgentId ? agentName(originatingViaAgentId) : null}
|
||
currentUserId={currentUserId}
|
||
parentIdentifier={issue.parentId ? (issueById.get(issue.parentId)?.identifier ?? null) : null}
|
||
parentTitle={issue.parentId ? (issueById.get(issue.parentId)?.title ?? null) : null}
|
||
/>
|
||
) : undefined
|
||
}
|
||
trailingMeta={streamlinedUiEnabled && showTaskTimestamp ? issueActivityTimestamp(issue) : null}
|
||
/>
|
||
);
|
||
};
|
||
|
||
let previousDateGroup: TaskDateGroup | null = null;
|
||
let previousTimestamp = Number.POSITIVE_INFINITY;
|
||
const legacyTodayCutoff = Date.now() - 24 * 60 * 60 * 1000;
|
||
return groupedSections.flatMap((group, groupIndex) => {
|
||
const elements: ReactNode[] = [];
|
||
const isGroupCollapsed = collapsedGroupKeys.has(group.key);
|
||
if (
|
||
group.searchSection !== "none"
|
||
&& group.searchSection !== groupedSections[groupIndex - 1]?.searchSection
|
||
) {
|
||
elements.push(
|
||
<div
|
||
key={`${group.searchSection}-search-divider`}
|
||
className="flex items-center gap-3 border-y border-border/70 bg-muted/30 px-4 py-2"
|
||
>
|
||
<div className="h-px flex-1 bg-border/80" />
|
||
<span className="shrink-0 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">
|
||
{group.searchSection === "archived" ? "Archived" : "Other results"}
|
||
</span>
|
||
<div className="h-px flex-1 bg-border/80" />
|
||
</div>,
|
||
);
|
||
}
|
||
if (group.label) {
|
||
const groupNavIdx = groupFlatIndex.get(group.key) ?? -1;
|
||
const isGroupSelected = groupNavIdx >= 0 && selectedIndex === groupNavIdx;
|
||
const canCreateIssueInGroup = group.displayItems.some((item) => item.kind === "issue");
|
||
elements.push(
|
||
<div
|
||
key={`group-${group.key}`}
|
||
data-inbox-item
|
||
className={cn(groupIndex > 0 && "pt-2")}
|
||
onClick={() => {
|
||
if (groupNavIdx >= 0) setSelectedIndex(groupNavIdx);
|
||
}}
|
||
onMouseEnter={() => {
|
||
if (groupNavIdx >= 0) setSelectedIndexFromPointer(groupNavIdx);
|
||
}}
|
||
>
|
||
{/* Left inset aligns the header chevron with the nested
|
||
task chevrons. Read rows no longer reserve a
|
||
mark-read column, so inbox rows sit at pl-1 before
|
||
their chevron — same as the tasks list. */}
|
||
<div className={cn("rounded-lg px-3 sm:pl-0 sm:pr-4", isGroupSelected ? "bg-accent/50" : "hover:bg-accent/50")}>
|
||
<IssueGroupHeader
|
||
label={group.label}
|
||
collapsible
|
||
collapsed={isGroupCollapsed}
|
||
onToggle={() => toggleGroupCollapse(group.key)}
|
||
trailing={canCreateIssueInGroup ? (
|
||
<Button
|
||
variant="ghost"
|
||
size="icon-xs"
|
||
className="-mr-2 text-muted-foreground"
|
||
title={`New task in ${group.label}`}
|
||
aria-label={`New task in ${group.label}`}
|
||
onClick={(event) => {
|
||
event.stopPropagation();
|
||
openCreateIssueForGroup(group);
|
||
}}
|
||
>
|
||
<Plus className="h-3 w-3" />
|
||
</Button>
|
||
) : null}
|
||
/>
|
||
</div>
|
||
</div>,
|
||
);
|
||
}
|
||
if (isGroupCollapsed) return elements;
|
||
|
||
for (let index = 0; index < group.displayItems.length; index += 1) {
|
||
const item = group.displayItems[index]!;
|
||
const navIdx = topFlatIndex.get(`${group.key}:${getInboxWorkItemKey(item)}`) ?? 0;
|
||
const wrapItem = (key: string, isSelected: boolean, child: ReactNode) => (
|
||
<div
|
||
key={`sel-${key}`}
|
||
data-inbox-item
|
||
className="relative"
|
||
onClick={() => setSelectedIndex(navIdx)}
|
||
onMouseEnter={() => setSelectedIndexFromPointer(navIdx)}
|
||
>
|
||
{child}
|
||
</div>
|
||
);
|
||
const currentDateGroup = taskDateGroup(item.timestamp);
|
||
const dateGroupLabel = streamlinedUiEnabled
|
||
&& filterPreferences.showDateGroupSeparators
|
||
&& groupBy === "none"
|
||
? taskDateGroupSeparator(previousDateGroup, currentDateGroup)
|
||
: null;
|
||
previousDateGroup = currentDateGroup;
|
||
const showLegacyEarlierDivider = !streamlinedUiEnabled
|
||
&& groupBy === "none"
|
||
&& item.timestamp > 0
|
||
&& item.timestamp < legacyTodayCutoff
|
||
&& previousTimestamp >= legacyTodayCutoff;
|
||
previousTimestamp = item.timestamp > 0 ? item.timestamp : previousTimestamp;
|
||
if (dateGroupLabel) {
|
||
elements.push(
|
||
<div
|
||
key={`date-divider-${group.key}-${currentDateGroup}-${index}`}
|
||
className="flex items-center gap-3 px-3 py-1.5 sm:pl-0 sm:pr-4"
|
||
data-testid="inbox-date-group"
|
||
role="separator"
|
||
aria-label={dateGroupLabel}
|
||
>
|
||
<span className="h-px min-w-0 flex-1 bg-border/80" aria-hidden="true" data-date-group-rule="" />
|
||
<span
|
||
className="shrink-0 text-(length:--text-nano) font-medium uppercase tracking-wider text-muted-foreground/70"
|
||
data-date-group-label=""
|
||
>
|
||
{dateGroupLabel}
|
||
</span>
|
||
<span className="h-px min-w-0 flex-1 bg-border/80" aria-hidden="true" data-date-group-rule="" />
|
||
</div>,
|
||
);
|
||
} else if (showLegacyEarlierDivider) {
|
||
elements.push(
|
||
<div key={`earlier-divider-${group.key}-${index}`} className="my-2 flex items-center gap-3 px-4">
|
||
<div className="flex-1 border-t border-border" />
|
||
<span
|
||
className="shrink-0 text-(length:--text-micro) font-medium uppercase tracking-wider text-muted-foreground/70"
|
||
data-date-group-label=""
|
||
>
|
||
Earlier
|
||
</span>
|
||
</div>,
|
||
);
|
||
}
|
||
const isSelected = selectedIndex === navIdx;
|
||
|
||
if (item.kind === "approval") {
|
||
const approvalKey = `approval:${item.approval.id}`;
|
||
const isArchiving = archivingNonIssueIds.has(approvalKey);
|
||
const row = (
|
||
<ApprovalInboxRow
|
||
key={approvalKey}
|
||
approval={item.approval}
|
||
selected={isSelected}
|
||
requesterName={agentName(item.approval.requestedByAgentId)}
|
||
onApprove={() => approveMutation.mutate(item.approval.id)}
|
||
onReject={() => rejectMutation.mutate(item.approval.id)}
|
||
isPending={approveMutation.isPending || rejectMutation.isPending}
|
||
unreadState={nonIssueUnreadState(approvalKey)}
|
||
onMarkRead={() => handleMarkNonIssueRead(approvalKey)}
|
||
onArchive={canArchiveFromTab ? () => handleArchiveNonIssue(approvalKey) : undefined}
|
||
archiveDisabled={isArchiving}
|
||
className={
|
||
isArchiving
|
||
? "pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out"
|
||
: "transition-all duration-200 ease-out"
|
||
}
|
||
/>
|
||
);
|
||
elements.push(wrapItem(approvalKey, isSelected, canArchiveFromTab ? (
|
||
<SwipeToArchive
|
||
key={approvalKey}
|
||
selected={isSelected}
|
||
disabled={isArchiving}
|
||
onArchive={() => handleArchiveNonIssue(approvalKey)}
|
||
>
|
||
{row}
|
||
</SwipeToArchive>
|
||
) : <InboxRowSurface selected={isSelected}>{row}</InboxRowSurface>));
|
||
continue;
|
||
}
|
||
|
||
if (item.kind === "failed_run") {
|
||
const runKey = `run:${item.run.id}`;
|
||
const isArchiving = archivingNonIssueIds.has(runKey);
|
||
const row = (
|
||
<FailedRunInboxRow
|
||
key={runKey}
|
||
run={item.run}
|
||
selected={isSelected}
|
||
issueById={issueById}
|
||
agentName={agentName(item.run.agentId)}
|
||
issueLinkState={issueLinkState}
|
||
onDismiss={() => dismissInboxItem(runKey)}
|
||
onRetry={() => retryRunMutation.mutate(item.run)}
|
||
isRetrying={retryingRunIds.has(item.run.id)}
|
||
unreadState={nonIssueUnreadState(runKey)}
|
||
onMarkRead={() => handleMarkNonIssueRead(runKey)}
|
||
onArchive={canArchiveFromTab ? () => handleArchiveNonIssue(runKey) : undefined}
|
||
archiveDisabled={isArchiving}
|
||
className={
|
||
isArchiving
|
||
? "pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out"
|
||
: "transition-all duration-200 ease-out"
|
||
}
|
||
/>
|
||
);
|
||
elements.push(wrapItem(runKey, isSelected, canArchiveFromTab ? (
|
||
<SwipeToArchive
|
||
key={runKey}
|
||
selected={isSelected}
|
||
disabled={isArchiving}
|
||
onArchive={() => handleArchiveNonIssue(runKey)}
|
||
>
|
||
{row}
|
||
</SwipeToArchive>
|
||
) : <InboxRowSurface selected={isSelected}>{row}</InboxRowSurface>));
|
||
continue;
|
||
}
|
||
|
||
if (item.kind === "join_request") {
|
||
const joinKey = `join:${item.joinRequest.id}`;
|
||
const isArchiving = archivingNonIssueIds.has(joinKey);
|
||
const row = (
|
||
<JoinRequestInboxRow
|
||
key={joinKey}
|
||
joinRequest={item.joinRequest}
|
||
selected={isSelected}
|
||
onApprove={() => approveJoinMutation.mutate(item.joinRequest)}
|
||
onReject={() => rejectJoinMutation.mutate(item.joinRequest)}
|
||
isPending={approveJoinMutation.isPending || rejectJoinMutation.isPending}
|
||
unreadState={nonIssueUnreadState(joinKey)}
|
||
onMarkRead={() => handleMarkNonIssueRead(joinKey)}
|
||
onArchive={canArchiveFromTab ? () => handleArchiveNonIssue(joinKey) : undefined}
|
||
archiveDisabled={isArchiving}
|
||
className={
|
||
isArchiving
|
||
? "pointer-events-none -translate-x-4 scale-(--s-0_98) opacity-0 transition-all duration-200 ease-out"
|
||
: "transition-all duration-200 ease-out"
|
||
}
|
||
/>
|
||
);
|
||
elements.push(wrapItem(joinKey, isSelected, canArchiveFromTab ? (
|
||
<SwipeToArchive
|
||
key={joinKey}
|
||
selected={isSelected}
|
||
disabled={isArchiving}
|
||
onArchive={() => handleArchiveNonIssue(joinKey)}
|
||
>
|
||
{row}
|
||
</SwipeToArchive>
|
||
) : <InboxRowSurface selected={isSelected}>{row}</InboxRowSurface>));
|
||
continue;
|
||
}
|
||
|
||
const issue = item.issue;
|
||
const childIssues = group.childrenByIssueId.get(issue.id) ?? [];
|
||
const hasChildren = childIssues.length > 0;
|
||
const isExpanded = hasChildren && !collapsedInboxParents.has(issue.id);
|
||
const canArchiveIssue = canArchiveTaskFromTab && group.searchSection === "none";
|
||
const renderChildIssueRows = (
|
||
children: Issue[],
|
||
depth: number,
|
||
seen: ReadonlySet<string>,
|
||
): ReactNode[] =>
|
||
children.flatMap((child) => {
|
||
if (seen.has(child.id)) return [];
|
||
const nextSeen = new Set(seen);
|
||
nextSeen.add(child.id);
|
||
const childNavIdx = childFlatIndex.get(child.id) ?? -1;
|
||
const isChildSelected = selectedIndex === childNavIdx;
|
||
const grandchildIssues = group.childrenByIssueId.get(child.id) ?? [];
|
||
const childHasChildren = grandchildIssues.length > 0;
|
||
const childIsExpanded = childHasChildren && !collapsedInboxParents.has(child.id);
|
||
const childRow = renderInboxIssue({
|
||
issue: child,
|
||
depth,
|
||
selected: isChildSelected,
|
||
hasChildren: childHasChildren,
|
||
isExpanded: childIsExpanded,
|
||
childCount: grandchildIssues.length,
|
||
collapseParentId: child.id,
|
||
allowArchive: canArchiveIssue,
|
||
});
|
||
const isChildArchiving = archivingIssueIds.has(child.id);
|
||
const row = (
|
||
<div
|
||
key={`sel-issue:${child.id}`}
|
||
data-inbox-item
|
||
className="relative"
|
||
onClick={() => {
|
||
if (childNavIdx >= 0) setSelectedIndex(childNavIdx);
|
||
}}
|
||
onMouseEnter={() => {
|
||
if (childNavIdx >= 0) setSelectedIndexFromPointer(childNavIdx);
|
||
}}
|
||
>
|
||
{canArchiveIssue ? (
|
||
<SwipeToArchive
|
||
key={`issue:${child.id}`}
|
||
selected={isChildSelected}
|
||
disabled={isChildArchiving}
|
||
onArchive={() => archiveIssueMutation.mutate(child.id)}
|
||
>
|
||
{childRow}
|
||
</SwipeToArchive>
|
||
) : <InboxRowSurface selected={isChildSelected}>{childRow}</InboxRowSurface>}
|
||
</div>
|
||
);
|
||
|
||
return childIsExpanded
|
||
? [row, ...renderChildIssueRows(grandchildIssues, depth + 1, nextSeen)]
|
||
: [row];
|
||
});
|
||
const parentRow = renderInboxIssue({
|
||
issue,
|
||
depth: 0,
|
||
selected: isSelected,
|
||
hasChildren,
|
||
isExpanded,
|
||
childCount: childIssues.length,
|
||
collapseParentId: issue.id,
|
||
allowArchive: canArchiveIssue,
|
||
});
|
||
|
||
elements.push(wrapItem(`issue:${issue.id}`, isSelected, canArchiveIssue ? (
|
||
<SwipeToArchive
|
||
key={`issue:${issue.id}`}
|
||
selected={isSelected}
|
||
disabled={archivingIssueIds.has(issue.id)}
|
||
onArchive={() => archiveIssueMutation.mutate(issue.id)}
|
||
>
|
||
{parentRow}
|
||
</SwipeToArchive>
|
||
) : <InboxRowSurface selected={isSelected}>{parentRow}</InboxRowSurface>));
|
||
|
||
if (isExpanded) {
|
||
elements.push(...renderChildIssueRows(childIssues, 1, new Set([issue.id])));
|
||
}
|
||
}
|
||
|
||
return elements;
|
||
});
|
||
})()}
|
||
</div>
|
||
</div>
|
||
</>
|
||
)}
|
||
|
||
{allLoaded && !listError && showAlertsSection && (
|
||
<>
|
||
{showSeparatorBefore("alerts") && <Separator />}
|
||
<div>
|
||
<h3 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||
Alerts
|
||
</h3>
|
||
<div className="divide-y divide-border border border-border">
|
||
{showAggregateAgentError && (
|
||
<div className="group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50">
|
||
<Link
|
||
to="/agents"
|
||
className="flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit"
|
||
>
|
||
<AlertTriangle className="h-4 w-4 shrink-0 text-red-600 dark:text-red-400" />
|
||
<span className="text-sm">
|
||
<span className="font-medium">{dashboard!.agents.error}</span>{" "}
|
||
{dashboard!.agents.error === 1 ? "agent has" : "agents have"} errors
|
||
</span>
|
||
</Link>
|
||
<button
|
||
type="button"
|
||
onClick={() => dismissAlert("alert:agent-errors")}
|
||
className="rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100"
|
||
aria-label="Dismiss"
|
||
>
|
||
<X className="h-3.5 w-3.5" />
|
||
</button>
|
||
</div>
|
||
)}
|
||
{showBudgetAlert && (
|
||
<div className="group/alert relative flex items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50">
|
||
<Link
|
||
to="/costs"
|
||
className="flex flex-1 cursor-pointer items-center gap-3 no-underline text-inherit"
|
||
>
|
||
<AlertTriangle className="h-4 w-4 shrink-0 text-yellow-400" />
|
||
<span className="text-sm">
|
||
Budget at{" "}
|
||
<span className="font-medium">{dashboard!.costs.monthUtilizationPercent}%</span>{" "}
|
||
utilization this month
|
||
</span>
|
||
</Link>
|
||
<button
|
||
type="button"
|
||
onClick={() => dismissAlert("alert:budget")}
|
||
className="rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/alert:opacity-100"
|
||
aria-label="Dismiss"
|
||
>
|
||
<X className="h-3.5 w-3.5" />
|
||
</button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
</>
|
||
)}
|
||
|
||
</div>
|
||
);
|
||
}
|