diff --git a/apps/mobile/src/features/issues/IssueListRow.tsx b/apps/mobile/src/features/issues/IssueListRow.tsx index 3ed3db77e293a..05ab7971a05bc 100644 --- a/apps/mobile/src/features/issues/IssueListRow.tsx +++ b/apps/mobile/src/features/issues/IssueListRow.tsx @@ -13,7 +13,7 @@ import { THREAD_LIST_V2_SIDEBAR_ROW_CONTAINER_STYLE, THREAD_LIST_V2_SIDEBAR_ROW_STYLE, } from "../threads/thread-list-v2-row-appearance"; -import { issueStatus } from "./issuePresentation"; +import { IssueStatusIcon, issueStatus } from "./issuePresentation"; export const IssueListRow = memo(function IssueListRow(props: { readonly item: EnvironmentIssueEntry; @@ -58,7 +58,7 @@ export const IssueListRow = memo(function IssueListRow(props: { className={cn("self-start", props.sidebar ? "pt-0.5" : "pt-2.5")} style={props.depth ? { marginLeft: props.depth * 20 } : undefined} > - + props.onOpen(issue)} className="min-h-10 flex-row items-center gap-2 active:opacity-70" > - + {issue.displayKey} {issue.title} @@ -55,7 +55,7 @@ export function IssueRelations(props: { ["Blocking", detail.blocks ?? []], ]; const related = groups.filter(([, issues]) => issues.length > 0); - if (!project && !detail.branchName && related.length === 0) return null; + if (!project && !detail.branchName && !detail.priorityLabel && related.length === 0) return null; const openRelated = (issue: IssueRelatedRef) => navigation.dispatch( @@ -120,6 +120,21 @@ export function IssueRelations(props: { ) : null} + {detail.priorityLabel ? ( + + + + {/* Mobile rows have no label column, so the value names itself. */} + {/^no priority$/i.test(detail.priorityLabel) + ? detail.priorityLabel + : `${detail.priorityLabel} priority`} + + + ) : null} {related.map(([label, issues]) => ( {label} diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 532069f8ab743..e7d0e9de69dd0 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -57,6 +57,7 @@ import { issueIdentity, issueParamsKey, issueTarget, type IssueParams } from "./ import { IssueLabelPill, issueCommandError, + IssueStatusIcon, issueStatus, useIssueAccess, } from "./issuePresentation"; @@ -111,8 +112,13 @@ function IssueStateControl(props: { disabled={!moves.length || props.busy} className="min-h-8 flex-row items-center gap-1.5 active:opacity-70" > - - {status.label} + + {/* A Linear state's colour is its glyph's; the name stays neutral beside it. */} + + {status.label} + {moves.length ? ( ) : null} diff --git a/apps/mobile/src/features/issues/issuePresentation.tsx b/apps/mobile/src/features/issues/issuePresentation.tsx index 3fb6a77e07ca8..4c66bbed4aa34 100644 --- a/apps/mobile/src/features/issues/issuePresentation.tsx +++ b/apps/mobile/src/features/issues/issuePresentation.tsx @@ -1,14 +1,16 @@ import { useAtomValue } from "@effect/atom-react"; import { issueWriteAccess } from "@t3tools/client-runtime/issue-presentation"; +import { issueStateGlyph } from "@t3tools/client-runtime/issue-state-glyph"; import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import type { IssueDetail, IssueLabel, IssueState } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; -import { View } from "react-native"; +import { useColorScheme, View } from "react-native"; +import Svg, { Circle, Path } from "react-native-svg"; -import type { AppSymbolName } from "../../components/ui/AppSymbol"; +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { issueEnvironment } from "../../state/issues"; import { ENVIRONMENT_REQUEST_INTERRUPTED } from "../../state/query"; @@ -47,6 +49,47 @@ export function issueStatus(state: IssueState): { }; } +/** + * The state's mark: Linear's per-type glyph in the state's colour where the tracker has workflow + * types, otherwise the open or closed symbol. The same shapes the web draws. + */ +export function IssueStatusIcon(props: { readonly state: IssueState; readonly size: number }) { + const scheme = useColorScheme() === "dark" ? "dark" : "light"; + const glyph = issueStateGlyph(props.state, scheme); + if (glyph === null) { + const status = issueStatus(props.state); + return ; + } + return ( + + {glyph.primitives.map((primitive) => + primitive.tag === "circle" ? ( + + ) : ( + + ), + )} + + ); +} + /** What this device may do to the issue, and the first thing in the way when it may not. */ export function useIssueAccess(params: IssueParams, detail: IssueDetail | null | undefined) { const connected = usePullRequestConnected(params.environmentId); diff --git a/apps/web/src/components/LinearIssueContextChip.tsx b/apps/web/src/components/LinearIssueContextChip.tsx index 3cb578df3acb5..4029d2e0fa564 100644 --- a/apps/web/src/components/LinearIssueContextChip.tsx +++ b/apps/web/src/components/LinearIssueContextChip.tsx @@ -1,24 +1,38 @@ -import type { LinearIssueContextRecord } from "@t3tools/contracts"; -import { CircleCheckIcon, CircleIcon, CircleXIcon } from "lucide-react"; +import { IssueStateType, type LinearIssueContextRecord } from "@t3tools/contracts"; +import { CircleIcon } from "lucide-react"; +import * as Schema from "effect/Schema"; import { linearIssueExtrasSummary } from "@t3tools/shared/linearLaunch"; import { ContextChip, ContextChipLabel } from "./ContextChip"; import ChatMarkdown from "./ChatMarkdown"; import { LinearIcon } from "./Icons"; import { cn } from "~/lib/utils"; +import { IssueStateIcon as LinearStateIcon } from "./issue/issuePresentation"; import { PreviewCard, PreviewCardPopup, PreviewCardTrigger } from "./ui/preview-card"; -/** Records name Linear's own state types; newer ones carry `open`, `completed` or `canceled`. */ +const isStateType = Schema.is(IssueStateType); +const CLOSED_TYPES: ReadonlyArray = ["completed", "canceled", "duplicate"]; + +/** Records carry Linear's state type; some older ones only `open`, which has no glyph. */ function IssueStateIcon({ type, + name, className, }: { readonly type: string; + readonly name: string; readonly className?: string; }) { - const Icon = - type === "completed" ? CircleCheckIcon : type === "canceled" ? CircleXIcon : CircleIcon; - return ; + if (!isStateType(type)) { + return ( + + ); + } + const category = CLOSED_TYPES.includes(type) ? "closed" : "open"; + return ; } function LinearIssuePreview({ record }: { readonly record: LinearIssueContextRecord }) { @@ -33,7 +47,7 @@ function LinearIssuePreview({ record }: { readonly record: LinearIssueContextRec
{crumbs.join(" › ")}
- +
{record.identifier}{" "} @@ -66,7 +80,7 @@ function LinearIssuePreview({ record }: { readonly record: LinearIssueContextRec
{record.subIssues.slice(0, 5).map((sub) => (
- + {sub.identifier} {sub.title}
diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 92e665af22747..a584c2fb41fdc 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -67,7 +67,7 @@ import { isElectron } from "~/env"; import type { DesktopPreviewOverlay } from "~/previewStateStore"; import type { RightPanelSurface } from "~/rightPanelStore"; import { cn } from "~/lib/utils"; -import { issueStatePresentation } from "~/components/issue/issuePresentation"; +import { IssueStateIcon } from "~/components/issue/issuePresentation"; import { issueEnvironment } from "~/state/issues"; import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings"; import { readLocalApi } from "~/localApi"; @@ -795,14 +795,7 @@ function IssueSurfaceIcon({ }), ).data; if (detail === null) return ; - const presentation = issueStatePresentation(detail.state); - return ( - - ); + return ; } function PullRequestSurfaceIcon({ diff --git a/apps/web/src/components/WorkspaceBreadcrumb.tsx b/apps/web/src/components/WorkspaceBreadcrumb.tsx index 591ce30d07d06..fb62d5a98f670 100644 --- a/apps/web/src/components/WorkspaceBreadcrumb.tsx +++ b/apps/web/src/components/WorkspaceBreadcrumb.tsx @@ -6,12 +6,24 @@ interface WorkspaceBreadcrumbProps { readonly ariaLabel: string; readonly children: ReactNode; readonly className?: string; + /** Wraps onto more lines instead of squeezing the current level out of a narrow pane. */ + readonly wrap?: boolean; } -export function WorkspaceBreadcrumb({ ariaLabel, children, className }: WorkspaceBreadcrumbProps) { +export function WorkspaceBreadcrumb({ + ariaLabel, + children, + className, + wrap = false, +}: WorkspaceBreadcrumbProps) { return ( diff --git a/apps/web/src/components/issue/IssueBrowseView.tsx b/apps/web/src/components/issue/IssueBrowseView.tsx index 5c22dabba85f4..003efad7755c3 100644 --- a/apps/web/src/components/issue/IssueBrowseView.tsx +++ b/apps/web/src/components/issue/IssueBrowseView.tsx @@ -39,6 +39,7 @@ import { issueEnvironment } from "~/state/issues"; import { useEnvironmentQuery } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; +import { IssueGlyph } from "./issuePresentation"; import { IssueRow, type IssueRowTarget } from "./IssueRow"; import { appendIssueBrowseEntries, @@ -126,7 +127,7 @@ export function IssueBrowseView({ } const breadcrumb = ( - + {crumbs.map((crumb, index) => ( {index > 0 ? ( @@ -134,16 +135,18 @@ export function IssueBrowseView({ ) : null} - + {/* An ancestor may shrink too: a long project name truncates on its own line. */} + {crumb.target === null ? ( {crumb.label} ) : ( )} @@ -175,6 +178,8 @@ export function IssueBrowseView({ ) : teams.length === 0 && teamsError ? ( } error={teamsError} onRetry={onRetryTeams} refreshing={teamsPending} @@ -302,6 +307,8 @@ function BrowseLevel({ {toolbar} {query.error !== null && !query.isPending ? ( } error={query.error} onRetry={query.refresh} refreshing={query.isPending} diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index a819be73af6c7..59410880da595 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -73,7 +73,12 @@ import { IssueCommentComposer } from "./IssueCommentComposer"; import { IssueDetailGhost } from "./IssueDetailGhost"; import { ReactionBar } from "../pullRequest/PullRequestReactions"; import { PullRequestsUnavailableState } from "../pullRequest/PullRequestsUnavailableState"; -import { issueTrackerPresentation, issueStatePresentation } from "./issuePresentation"; +import { + IssueGlyph, + IssueStateIcon, + issueTrackerPresentation, + issueStatePresentation, +} from "./issuePresentation"; import { LinearIssueLaunchBar, LinearIssueRelations } from "../linear/LinearIssueDetailExtras"; /** @@ -481,6 +486,7 @@ export function IssueDetailPanel({ return ( } error={detailQuery.error} onRetry={detailQuery.refresh} /> @@ -563,12 +569,7 @@ export function IssueDetailPanel({ refreshIssueLists(environmentId); }; - const currentStateIcon = ( - - ); + const currentStateIcon = ; const stateControl: ReactNode = otherStates.length > 0 ? ( @@ -588,13 +589,9 @@ export function IssueDetailPanel({ {otherStates.map((state) => { - const presentation = issueStatePresentation(state); return ( void moveTo(state.name)}> - + {state.name} ); @@ -624,7 +621,11 @@ export function IssueDetailPanel({ {detail.scope} } > diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index b28847af09b86..330c32c97ff8c 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -458,12 +458,15 @@ export function IssuesPage() { const listBody: ReactNode = !issuesSupported ? ( } error="Update this environment's T3 Code server to browse issues." /> ) : noneAnswered && list.isPending ? ( ) : noneAnswered && list.error ? ( } error={list.error} onRetry={list.refresh} refreshing={list.isPending} diff --git a/apps/web/src/components/issue/issuePresentation.tsx b/apps/web/src/components/issue/issuePresentation.tsx index a8a02f41f5a47..4dda7ff661f45 100644 --- a/apps/web/src/components/issue/issuePresentation.tsx +++ b/apps/web/src/components/issue/issuePresentation.tsx @@ -1,9 +1,11 @@ import type { IssueState, IssueTrackerKind } from "@t3tools/contracts"; +import { issueStateGlyph } from "@t3tools/client-runtime/issue-state-glyph"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { CircleCheckIcon, CircleDotIcon, CircleSlashIcon, TicketIcon } from "lucide-react"; import { cn } from "~/lib/utils"; import { LinearIcon, type Icon } from "~/components/Icons"; +import { useRenderedAppearance } from "~/hooks/useTheme"; import { getSourceControlPresentationForKind } from "~/sourceControlPresentation"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -52,17 +54,74 @@ export function issueStatePresentation(state: IssueState) { }; } +/** + * The state's mark: Linear's per-type glyph in the state's colour where the tracker has workflow + * types, otherwise the open or closed icon. Decorative unless `labelled`. + */ +export function IssueStateIcon({ + state, + className, + labelled = false, +}: { + state: IssueState; + className?: string | undefined; + labelled?: boolean; +}) { + const appearance = useRenderedAppearance(); + const presentation = issueStatePresentation(state); + const glyph = issueStateGlyph(state, appearance === "dark" ? "dark" : "light"); + const accessibility = labelled + ? ({ role: "img", "aria-label": presentation.label } as const) + : ({ "aria-hidden": true } as const); + if (glyph === null) { + return ( + + ); + } + return ( + + {glyph.primitives.map((primitive) => + primitive.tag === "circle" ? ( + + ) : ( + + ), + )} + + ); +} + export function IssueStateGlyph({ state, className }: { state: IssueState; className?: string }) { const presentation = issueStatePresentation(state); return ( {/* The list row is itself a button, so the trigger stays a span. */} }> - + {presentation.label} diff --git a/apps/web/src/components/linear/LinearIssueDetailExtras.tsx b/apps/web/src/components/linear/LinearIssueDetailExtras.tsx index 5a9af66072350..cba9b64d6eeb1 100644 --- a/apps/web/src/components/linear/LinearIssueDetailExtras.tsx +++ b/apps/web/src/components/linear/LinearIssueDetailExtras.tsx @@ -19,11 +19,13 @@ import type { import { sortBlockers } from "@t3tools/shared/linearLaunch"; import { ChevronDownIcon, - CircleCheckIcon, - CircleIcon, - CircleXIcon, + ListTreeIcon, + OctagonAlertIcon, + CornerLeftUpIcon, FolderKanbanIcon, GitBranchIcon, + HandIcon, + SignalIcon, MessageSquarePlusIcon, WorkflowIcon, } from "lucide-react"; @@ -36,6 +38,7 @@ import { useEnvironmentQuery } from "../../state/query"; import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; import { linearContextReference } from "../../lib/composerContextRecords"; import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { IssueStateGlyph } from "../issue/issuePresentation"; import { PullRequestMetaRow } from "../pullRequest/PullRequestSummaryTab"; import { Button } from "../ui/button"; import { Group, GroupSeparator } from "../ui/group"; @@ -174,16 +177,6 @@ export function LinearIssueLaunchBar({ ); } -function RelatedStateIcon({ issue }: { readonly issue: IssueRelatedRef }) { - const Icon = - issue.state.category === "open" - ? CircleIcon - : issue.state.closeReason === "completed" - ? CircleCheckIcon - : CircleXIcon; - return ; -} - function RelatedIssue({ issue, onOpen, @@ -193,7 +186,7 @@ function RelatedIssue({ }) { const body = ( <> - + {issue.displayKey} {issue.title} @@ -258,17 +251,34 @@ export function LinearIssueRelations({ value: {detail.branchName}, }); } - const groups: Array<[string, ReadonlyArray]> = [ - ["Parent", detail.parent ? [detail.parent] : []], - ["Sub-issues", detail.subIssues ?? []], - ["Blocked by", sortBlockers(detail.blockedBy ?? [])], - ["Blocking", detail.blocks ?? []], + if (detail.priorityLabel) { + rows.push({ + key: "priority", + icon: , + label: "Priority", + value: {detail.priorityLabel}, + }); + } + // None of these may be a circle: the related issues' own status glyphs are circles. + const groups: Array<[string, ReactNode, ReadonlyArray]> = [ + [ + "Parent", + , + detail.parent ? [detail.parent] : [], + ], + ["Sub-issues", , detail.subIssues ?? []], + [ + "Blocked by", + , + sortBlockers(detail.blockedBy ?? []), + ], + ["Blocking", , detail.blocks ?? []], ]; - for (const [label, issues] of groups) { + for (const [label, icon, issues] of groups) { if (issues.length === 0) continue; rows.push({ key: label, - icon: , + icon, label, value: , }); diff --git a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx index 95fe4f7671371..634a4f86538b2 100644 --- a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx @@ -1,5 +1,6 @@ import { RefreshIcon } from "~/components/ui/refresh-icon"; import { ExternalLinkIcon } from "lucide-react"; +import type { ReactNode } from "react"; import { Button } from "../ui/button"; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; @@ -11,18 +12,18 @@ export function PullRequestsUnavailableState({ onRetry, refreshing = false, host, + icon, }: { title?: string; error: string; onRetry?: () => void; refreshing?: boolean; host?: { readonly url: string; readonly openLabel: string }; + icon?: ReactNode; }) { return ( - - - + {icon ?? } {title} {error} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index a2497aed38342..2cb92ae4ad7d2 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -603,6 +603,10 @@ "types": "./src/issuePresentation.ts", "default": "./src/issuePresentation.ts" }, + "./issue-state-glyph": { + "types": "./src/issueStateGlyph.ts", + "default": "./src/issueStateGlyph.ts" + }, "./issue-list": { "types": "./src/issueList.ts", "default": "./src/issueList.ts" diff --git a/packages/client-runtime/src/issueBrowse.test.ts b/packages/client-runtime/src/issueBrowse.test.ts index d00cbc32cc10c..7988088f65370 100644 --- a/packages/client-runtime/src/issueBrowse.test.ts +++ b/packages/client-runtime/src/issueBrowse.test.ts @@ -10,6 +10,7 @@ import { describe, expect, it } from "vite-plus/test"; import { appendIssueBrowseEntries, issueBrowseTeams, + issueContainerProgressLabel, nestIssueBrowseEntries, splitIssueContainers, } from "./issueBrowse.ts"; @@ -62,6 +63,16 @@ describe("splitIssueContainers", () => { }); }); +describe("issueContainerProgressLabel", () => { + it("rounds a 0..1 progress to a whole percent, as Linear does", () => { + expect( + [0.75, 6 / 7, 2 / 3, 0.625, 0, 1, 1.2, -0.1, null, Number.NaN].map( + issueContainerProgressLabel, + ), + ).toEqual(["75%", "86%", "67%", "63%", "0%", "100%", "100%", "0%", null, null]); + }); +}); + describe("issueBrowseTeams", () => { it("lists every team of a connected tracker, served by its bound project or any other", () => { const answer = { diff --git a/packages/client-runtime/src/issueStateGlyph.test.ts b/packages/client-runtime/src/issueStateGlyph.test.ts new file mode 100644 index 0000000000000..e516684227343 --- /dev/null +++ b/packages/client-runtime/src/issueStateGlyph.test.ts @@ -0,0 +1,86 @@ +import type { IssueState, IssueStateType } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { issueStateGlyph } from "./issueStateGlyph.ts"; + +const TYPES: ReadonlyArray = [ + "triage", + "backlog", + "unstarted", + "started", + "completed", + "canceled", + "duplicate", +]; +const colorOf = (state: IssueState, scheme: "light" | "dark") => + issueStateGlyph(state, scheme)!.color; +const fillOf = (state: IssueState) => { + const pie = issueStateGlyph(state, "light")!.primitives.find((p) => p.key === "pie"); + return pie?.tag === "path" ? pie.d : null; +}; + +const state = (type: IssueStateType, extra: Partial = {}): IssueState => ({ + category: type === "completed" || type === "canceled" || type === "duplicate" ? "closed" : "open", + name: type, + type, + ...extra, +}); + +describe("issueStateGlyph", () => { + it("draws each Linear type with its own shape", () => { + const shapes = Object.fromEntries( + TYPES.map((type) => [ + type, + issueStateGlyph(state(type), "light")!.primitives.map((primitive) => + primitive.tag === "circle" + ? `${primitive.fill === null ? "ring" : "disc"}${primitive.dash ? "-dashed" : ""}` + : primitive.fill === null + ? "mark" + : "pie", + ), + ]), + ); + expect(shapes).toEqual({ + triage: ["disc", "mark"], + backlog: ["ring-dashed"], + unstarted: ["ring"], + started: ["ring", "pie"], + completed: ["disc", "mark"], + canceled: ["disc", "mark"], + duplicate: ["disc", "mark"], + }); + }); + + it("keeps the done and not-done marks apart", () => { + const mark = (type: IssueStateType) => + issueStateGlyph(state(type), "light")!.primitives.find((p) => p.tag === "path"); + expect(mark("completed")).not.toEqual(mark("canceled")); + expect(mark("canceled")).toEqual(mark("duplicate")); + }); + + it("leaves a tracker without workflow types to its open and closed marks", () => { + expect(issueStateGlyph({ category: "open", name: "Open" }, "light")).toBeNull(); + }); + + it("fills a started state by its place on the workflow, half when unknown", () => { + const path = (fill?: number) => + fillOf(state("started", fill === undefined ? {} : { startedFill: fill })); + expect(path(0.75)).toContain("A3 3 0 1 1 5.000 8.000"); + expect(path(0.25)).toContain("A3 3 0 0 1 11.000 8.000"); + expect(path()).toContain("A3 3 0 0 1 8.000 11.000"); + expect(path(0)).toEqual(path()); + expect(path(1)).toEqual(path()); + }); + + it("uses the state colour, else the type's, and drops one the theme would lose", () => { + expect(colorOf(state("completed", { color: "#26b5ce" }), "light")).toBe("#26b5ce"); + expect(colorOf(state("started"), "dark")).toBe("#f2c94c"); + expect(colorOf(state("unstarted", { color: "#e2e2e2" }), "light")).toBe("#9ca3af"); + expect(colorOf(state("unstarted", { color: "#e2e2e2" }), "dark")).toBe("#e2e2e2"); + expect(colorOf(state("completed", { color: "#101010" }), "dark")).toBe("#9ca3af"); + expect(colorOf(state("started", { color: "#f2c94c" }), "light")).toBe("#f2c94c"); + expect(colorOf(state("backlog", { color: "nonsense" }), "light")).toBe("#bec2c8"); + // Every type has a fallback colour of its own. + expect(new Set(TYPES.map((type) => colorOf(state(type), "light"))).size).toBeGreaterThan(4); + }); +}); diff --git a/packages/client-runtime/src/issueStateGlyph.ts b/packages/client-runtime/src/issueStateGlyph.ts new file mode 100644 index 0000000000000..29488632c180c --- /dev/null +++ b/packages/client-runtime/src/issueStateGlyph.ts @@ -0,0 +1,171 @@ +import type { IssueState, IssueStateType } from "@t3tools/contracts"; + +/** Linear's own colours per workflow type, for a state that arrives without one. */ +const ISSUE_STATE_DEFAULT_COLORS: Record = { + triage: "#fc7840", + backlog: "#bec2c8", + unstarted: "#9aa0a6", + started: "#f2c94c", + completed: "#5e6ad2", + canceled: "#95a2b3", + duplicate: "#95a2b3", +}; + +/** Used for a state colour that would vanish on the theme's background. */ +const NEUTRAL_INK = "#9ca3af"; +const SYMBOL_INK = "#ffffff"; +/** Without the team's started states, a started state reads as half done. */ +const DEFAULT_STARTED_FILL = 0.5; + +type IssueGlyphPrimitive = + | { + readonly tag: "circle"; + readonly key: string; + readonly cx: number; + readonly cy: number; + readonly r: number; + readonly fill: string | null; + readonly stroke: string | null; + readonly strokeWidth: number; + readonly dash: string | null; + } + | { + readonly tag: "path"; + readonly key: string; + readonly d: string; + readonly fill: string | null; + readonly stroke: string | null; + readonly strokeWidth: number; + }; + +interface IssueStateGlyph { + readonly color: string; + /** Drawn in a 16 × 16 box, so web and mobile share one set of shapes. */ + readonly viewBox: 16; + readonly primitives: ReadonlyArray; +} + +/** Relative luminance and chroma (0..255 channel spread) of a `#rrggbb` colour. */ +function inkOf(hex: string): { readonly luminance: number; readonly chroma: number } | null { + const match = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); + if (match === null) return null; + const value = Number.parseInt(match[1]!, 16); + const channels = [(value >> 16) & 255, (value >> 8) & 255, value & 255]; + const channel = (shift: number) => { + const c = ((value >> shift) & 255) / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }; + return { + luminance: 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0), + chroma: Math.max(...channels) - Math.min(...channels), + }; +} + +/** The state's colour, or its type's default; a colour too pale or too dark for the theme goes neutral. */ +function issueStateColor( + type: IssueStateType, + state: Pick, + scheme: "light" | "dark", +): string { + const color = state.color?.trim() || ISSUE_STATE_DEFAULT_COLORS[type]; + const ink = inkOf(color); + if (ink === null) return ISSUE_STATE_DEFAULT_COLORS[type]; + // Only a grey can vanish: Linear's yellow and green stay readable on both themes. + const grey = ink.chroma < 24; + if (grey && scheme === "light" && ink.luminance > 0.6) return NEUTRAL_INK; + if (grey && scheme === "dark" && ink.luminance < 0.03) return NEUTRAL_INK; + return color.startsWith("#") ? color : `#${color}`; +} + +function startedStateFill(state: Pick): number { + const fill = state.startedFill; + return fill !== undefined && Number.isFinite(fill) && fill > 0 && fill < 1 + ? fill + : DEFAULT_STARTED_FILL; +} + +const CENTER = 8; +const CHECK = "M5 8.3 L7.1 10.4 L11 5.9"; +const CROSS = "M5.7 5.7 L10.3 10.3 M10.3 5.7 L5.7 10.3"; +// An arrow into a bar: Linear's triage mark. +const TRIAGE = "M4.8 8 H10.4 M8.3 5.8 L10.5 8 L8.3 10.2 M11.6 5.6 V10.4"; + +function pie(fill: number, color: string): IssueGlyphPrimitive { + const radius = 3; + const angle = 2 * Math.PI * fill; + const x = (CENTER + radius * Math.sin(angle)).toFixed(3); + const y = (CENTER - radius * Math.cos(angle)).toFixed(3); + const large = fill > 0.5 ? 1 : 0; + return { + tag: "path", + key: "pie", + d: `M${CENTER} ${CENTER} L${CENTER} ${CENTER - radius} A${radius} ${radius} 0 ${large} 1 ${x} ${y} Z`, + fill: color, + stroke: null, + strokeWidth: 0, + }; +} + +const ring = (color: string, dash: string | null = null): IssueGlyphPrimitive => ({ + tag: "circle", + key: "ring", + cx: CENTER, + cy: CENTER, + r: 6, + fill: null, + stroke: color, + strokeWidth: 1.5, + dash, +}); + +const disc = (color: string): IssueGlyphPrimitive => ({ + tag: "circle", + key: "disc", + cx: CENTER, + cy: CENTER, + r: 7, + fill: color, + stroke: null, + strokeWidth: 0, + dash: null, +}); + +const mark = (d: string): IssueGlyphPrimitive => ({ + tag: "path", + key: "mark", + d, + fill: null, + stroke: SYMBOL_INK, + strokeWidth: 1.6, +}); + +/** + * Linear's status glyph for a state, or null when the tracker reports no workflow type (git + * hosts), which keep their open and closed marks. + */ +export function issueStateGlyph( + state: IssueState, + scheme: "light" | "dark", +): IssueStateGlyph | null { + const type = state.type; + if (type === undefined) return null; + const color = issueStateColor(type, state, scheme); + const primitives: ReadonlyArray = (() => { + switch (type) { + case "backlog": + return [ring(color, "2.356 2.356")]; + case "unstarted": + return [ring(color)]; + case "started": + return [ring(color), pie(startedStateFill(state), color)]; + case "completed": + return [disc(color), mark(CHECK)]; + case "canceled": + case "duplicate": + return [disc(color), mark(CROSS)]; + case "triage": + return [disc(color), mark(TRIAGE)]; + } + })(); + return { color, viewBox: 16, primitives }; +} diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 62b813e4a1fa1..0284a6edad20c 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -44,11 +44,29 @@ export type IssueLabel = typeof IssueLabel.Type; export const IssueStateCategory = Schema.Literals(["open", "closed"]); export type IssueStateCategory = typeof IssueStateCategory.Type; +/** A workflow state's kind in trackers that have one (Linear); it picks the status glyph. */ +export const IssueStateType = Schema.Literals([ + "triage", + "backlog", + "unstarted", + "started", + "completed", + "canceled", + "duplicate", +]); +export type IssueStateType = typeof IssueStateType.Type; + export const IssueState = Schema.Struct({ category: IssueStateCategory, name: TrimmedNonEmptyString, /** How a closed state ended, where the tracker says: `completed`, or its word for not done. */ closeReason: Schema.optional(TrimmedNonEmptyString), + /** The tracker's own workflow type. Absent where states are just open or closed. */ + type: Schema.optional(IssueStateType), + /** The state's `#rrggbb` colour, where the tracker has one. */ + color: Schema.optional(TrimmedNonEmptyString), + /** For a started state: how far along the workflow it sits, 0..1 exclusive of the ends. */ + startedFill: Schema.optional(Schema.Number), }); export type IssueState = typeof IssueState.Type; diff --git a/packages/issue-tracker-linear/src/server/LinearApi.graphql b/packages/issue-tracker-linear/src/server/LinearApi.graphql index af62098d7a0af..99699aabc0f29 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.graphql +++ b/packages/issue-tracker-linear/src/server/LinearApi.graphql @@ -17,6 +17,7 @@ fragment LinearWorkflowState on WorkflowState { name type position + color } fragment LinearLabel on IssueLabel { @@ -343,6 +344,21 @@ query T3CommentReactions($id: String!) { } } +query T3StartedStates($after: String) { + workflowStates(first: 250, after: $after, filter: { type: { eq: "started" } }) { + nodes { + id + position + team { + key + } + } + pageInfo { + ...LinearPageInfo + } + } +} + query T3TeamProjects($key: String!) { teams(first: 1, filter: { key: { eq: $key } }) { nodes { diff --git a/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts b/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts index 09f49ac37d49f..d331232a5dfb6 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts +++ b/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts @@ -50,7 +50,9 @@ export const LinearWorkflowState = Schema.Struct({ /** The type of the state. One of "triage", "backlog", "unstarted", "started", "completed", "canceled", "duplicate". */ type: Schema.String, /** The position of the state in the team's workflow. States are displayed in ascending order of position within their type group. */ - position: Shared.Float + position: Shared.Float, + /** The state's UI color as a HEX string. */ + color: Schema.String }) export interface LinearWorkflowState extends Schema.Struct.Type {} @@ -264,7 +266,7 @@ export const T3Issues = GraphQL.query("T3Issues", { fragments: [ { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}botActor{...LinearBot}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] }, { name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] }, - { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] }, + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position color}"] }, { name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] }, { name: "LinearBot", body: ["on ActorBot{name userDisplayName avatarUrl}"] }, { name: "LinearLabel", body: ["on IssueLabel{id name color}"] } @@ -486,7 +488,7 @@ export const T3Issue = GraphQL.query("T3Issue", { fragments: [ { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}botActor{...LinearBot}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] }, { name: "LinearIssueRef", body: ["on Issue{id identifier title url state{...LinearWorkflowState}}"] }, - { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] }, + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position color}"] }, { name: "LinearComment", body: ["on Comment{id body createdAt url user{...LinearUser}botActor{...LinearBot}reactions{...LinearReaction}}"] }, { name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] }, { name: "LinearReaction", body: ["on Reaction{id emoji user{...LinearUser}}"] }, @@ -627,7 +629,7 @@ export const T3Team = GraphQL.query("T3Team", { { name: "issueLabels", body: ["(first:250 filter:{team:{null:true}}){nodes{...LinearTeamLabel}pageInfo{...LinearPageInfo}}"] } ], fragments: [ - { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] }, + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position color}"] }, { name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] }, { name: "LinearTeamLabel", body: ["on IssueLabel{...LinearLabel description}"] }, { name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] }, @@ -894,6 +896,49 @@ export declare namespace T3CommentReactions { export type Result = typeof T3CommentReactions.result.Type } +/** A state in a team's workflow, representing an issue status such as Triage, Backlog, Todo, In Progress, In Review, Done, or Canceled. Each team has its own set of workflow states that define the progression of issues through the team's process. Workflow states have a type that categorizes them (triage, backlog, unstarted, started, completed, canceled), a position that determines their display order, and a color for visual identification. States can be inherited from parent teams to sub-teams. */ +export const NodesWorkflowState = Schema.Struct({ + /** The unique identifier of the entity. */ + id: Shared.ID, + /** The position of the state in the team's workflow. States are displayed in ascending order of position within their type group. */ + position: Shared.Float, + /** The team that this workflow state belongs to. Each team has its own set of workflow states. */ + team: LinearIssueTeamTeam +}) +export interface NodesWorkflowState extends Schema.Struct.Type {} + +export const WorkflowStatesWorkflowStateConnection = Schema.Struct({ + nodes: Schema.Array(NodesWorkflowState), + pageInfo: LinearPageInfo +}) +export interface WorkflowStatesWorkflowStateConnection extends Schema.Struct.Type {} + +/** `query T3StartedStates` */ +export const T3StartedStates = GraphQL.query("T3StartedStates", { + document: { + variables: [ + { name: "after", body: "String" } + ], + selections: [ + { name: "workflowStates", body: ["(first:250 after:$", "after", " filter:{type:{eq:\"started\"}}){nodes{id position team{key}}pageInfo{...LinearPageInfo}}"] } + ], + fragments: [ + { name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] } + ] + }, + variables: { + after: Schema.optional(Schema.NullOr(Schema.String)) + }, + result: Schema.Struct({ + /** All issue workflow states (issue statuses). Returns a paginated list of workflow states visible to the authenticated user, across all teams they have access to. */ + workflowStates: WorkflowStatesWorkflowStateConnection + }) +}) +export declare namespace T3StartedStates { + export type Variables = typeof T3StartedStates.variables.Type + export type Result = typeof T3StartedStates.result.Type +} + /** A custom project status within a workspace. Statuses are grouped by type (backlog, planned, started, paused, completed, canceled) and define the lifecycle stages a project can move through. Each workspace can customize the names and colors of its project statuses. */ export const ProjectStatus = Schema.Struct({ /** The name of the status. */ @@ -1029,16 +1074,16 @@ export const NodesChildrenIssueConnection = Schema.Struct({ export interface NodesChildrenIssueConnection extends Schema.Struct.Type {} /** A state in a team's workflow, representing an issue status such as Triage, Backlog, Todo, In Progress, In Review, Done, or Canceled. Each team has its own set of workflow states that define the progression of issues through the team's process. Workflow states have a type that categorizes them (triage, backlog, unstarted, started, completed, canceled), a position that determines their display order, and a color for visual identification. States can be inherited from parent teams to sub-teams. */ -export const WorkflowState = Schema.Struct({ +export const StateWorkflowState = Schema.Struct({ /** The type of the state. One of "triage", "backlog", "unstarted", "started", "completed", "canceled", "duplicate". */ type: Schema.String }) -export interface WorkflowState extends Schema.Struct.Type {} +export interface StateWorkflowState extends Schema.Struct.Type {} /** An issue is the core work item in Linear. Issues belong to a team, have a workflow status, can be assigned to users, carry a priority level, and can be organized into projects and cycles. Issues support sub-issues (parent-child hierarchy up to 10 levels deep), labels, due dates, estimates, and SLA tracking. They can also be linked to other issues via relations, attached to releases, and tracked through their full history of changes. */ export const NodesIssueIssue = Schema.Struct({ /** The workflow state (issue status) that the issue is currently in. Workflow states represent the issue's progress through the team's workflow, such as Triage, Todo, In Progress, Done, or Canceled. */ - state: WorkflowState + state: StateWorkflowState }) export interface NodesIssueIssue extends Schema.Struct.Type {} @@ -1088,7 +1133,7 @@ export const T3BrowseIssues = GraphQL.query("T3BrowseIssues", { fragments: [ { name: "LinearIssue", body: ["on Issue{id identifier number title url description createdAt updatedAt completedAt canceledAt state{...LinearWorkflowState}team{key}creator{...LinearUser}botActor{...LinearBot}assignee{...LinearUser}labels{nodes{...LinearLabel}}}"] }, { name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] }, - { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] }, + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position color}"] }, { name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] }, { name: "LinearBot", body: ["on ActorBot{name userDisplayName avatarUrl}"] }, { name: "LinearLabel", body: ["on IssueLabel{id name color}"] } @@ -1110,4 +1155,4 @@ export declare namespace T3BrowseIssues { } /** Every operation in LinearApi.graphql. */ -export const LinearApiGraphQLGroup = GraphQLGroup.make(T3Viewer, T3Issues, T3Issue, T3Comments, T3Team, T3IssueCreate, T3IssueUpdate, T3CommentCreate, T3ReactionCreate, T3ReactionDelete, T3IssueReactions, T3CommentReactions, T3TeamProjects, T3ProjectMilestones, T3BrowseIssues) +export const LinearApiGraphQLGroup = GraphQLGroup.make(T3Viewer, T3Issues, T3Issue, T3Comments, T3Team, T3IssueCreate, T3IssueUpdate, T3CommentCreate, T3ReactionCreate, T3ReactionDelete, T3IssueReactions, T3CommentReactions, T3StartedStates, T3TeamProjects, T3ProjectMilestones, T3BrowseIssues) diff --git a/packages/issue-tracker-linear/src/server/LinearApi.ts b/packages/issue-tracker-linear/src/server/LinearApi.ts index 61f8f5fb821bf..f8a21dd184e30 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.ts +++ b/packages/issue-tracker-linear/src/server/LinearApi.ts @@ -136,6 +136,15 @@ export class LinearApi extends Context.Service< { readonly nodes: ReadonlyArray; readonly nextCursor: string | null }, IssueTrackerError >; + /** Every started state of the workspace, to place each on its team's workflow. */ + readonly listStartedStates: () => Effect.Effect< + ReadonlyArray<{ + readonly id: string; + readonly position: number; + readonly team: { readonly key: string }; + }>, + IssueTrackerError + >; /** Null when no team has that key. */ readonly listProjects: ( teamKey: string, @@ -361,6 +370,21 @@ export const make = Effect.gen(function* () { ), ); + // Every page: a team cut off part-way would get wrong fills, not just the default. + const startedStatesFrom = ( + after: string | null, + ): ReturnType => + call("listStartedStates", (linear) => linear.T3StartedStates({ after })).pipe( + Effect.flatMap(({ workflowStates: page }) => { + const cursor = nextCursor(page.pageInfo); + return cursor === null + ? Effect.succeed(page.nodes) + : startedStatesFrom(cursor).pipe(Effect.map((rest) => [...page.nodes, ...rest])); + }), + ); + const listStartedStates: LinearApi["Service"]["listStartedStates"] = () => + startedStatesFrom(null); + const listProjects: LinearApi["Service"]["listProjects"] = (key) => call("listProjects", (linear) => linear.T3TeamProjects({ key })).pipe( Effect.map((data) => data.teams.nodes[0]?.projects.nodes ?? null), @@ -472,6 +496,7 @@ export const make = Effect.gen(function* () { getIssue, getComments, getTeam, + listStartedStates, listProjects, listMilestones, browseIssues, diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts index 10a4e5a3d2d02..b2b377251f53e 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts @@ -25,6 +25,7 @@ const state = (name: string, type: string, position = 0) => ({ name, type, position, + color: "#5e6ad2", }); const issue = ( @@ -181,6 +182,25 @@ describe("LinearIssueTracker", () => { Effect.gen(function* () { const { tracker, requests } = fakeLinear({ T3Viewer: () => ({ viewer: JULIUS, teams: { nodes: [] } }), + // Two started states on ENG, split over two pages, beside DES's own: In Progress sits a + // third of the way, In Review two thirds. + T3StartedStates: (variables) => + variables.after === "cur_states" + ? { + workflowStates: { + nodes: [ + { id: "st_in-review", position: 2, team: { key: "ENG" } }, + { id: "st_des-doing", position: 0.5, team: { key: "DES" } }, + ], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + } + : { + workflowStates: { + nodes: [{ id: "st_in-progress", position: 1, team: { key: "ENG" } }], + pageInfo: { hasNextPage: true, endCursor: "cur_states" }, + }, + }, T3Issues: (variables) => { expect(variables.filter).toMatchObject({ team: { key: { eq: "ENG" } }, @@ -201,6 +221,8 @@ describe("LinearIssueTracker", () => { completedAt: "2026-07-03T00:00:00.000Z", }), issue("ENG-1"), + // A workflow type newer than this client keeps the open or closed mark. + issue("ENG-3", { state: state("Paused", "paused") }), ], pageInfo: { hasNextPage: true, endCursor: "cur_2" }, }, @@ -223,11 +245,32 @@ describe("LinearIssueTracker", () => { }); expect(page.nextCursor).toBe("cur_2"); expect(page.items.map((item) => [item.key, item.displayKey, item.state])).toEqual([ - ["ENG-2", "ENG-2", { category: "closed", name: "Done", closeReason: "completed" }], - ["ENG-1", "ENG-1", { category: "open", name: "In Progress" }], + [ + "ENG-2", + "ENG-2", + { + category: "closed", + name: "Done", + closeReason: "completed", + type: "completed", + color: "#5e6ad2", + }, + ], + [ + "ENG-1", + "ENG-1", + { + category: "open", + name: "In Progress", + type: "started", + color: "#5e6ad2", + startedFill: 1 / 3, + }, + ], + ["ENG-3", "ENG-3", { category: "open", name: "Paused", color: "#5e6ad2" }], ]); // A listing carries no comment totals, whatever the row's position. - expect(page.items.map((item) => item.commentCount)).toEqual([0, 0]); + expect(page.items.map((item) => item.commentCount)).toEqual([0, 0, 0]); expect(page.items[0]).toMatchObject({ closedAt: "2026-07-03T00:00:00.000Z", author: { login: "julius", name: "julius" }, @@ -235,7 +278,9 @@ describe("LinearIssueTracker", () => { labels: [{ name: "Bug", color: "#f00" }], }); // The stored key goes in as-is, not as a bearer token. - expect(requests.map((request) => request.authorization)).toEqual(["lin_api_stored"]); + expect(new Set(requests.map((request) => request.authorization))).toEqual( + new Set(["lin_api_stored"]), + ); // Linear's reset header is an absolute time in epoch milliseconds. const resetAt = 4_102_444_800_000; @@ -263,6 +308,45 @@ describe("LinearIssueTracker", () => { }), ); + it.effect("reads started fills again after a failed read instead of keeping the fallback", () => + Effect.gen(function* () { + let reads = 0; + const { tracker } = fakeLinear({ + T3StartedStates: () => + ++reads === 1 + ? new Response(JSON.stringify({ errors: [{ message: "Rate limited" }] }), { + status: 429, + headers: { "content-type": "application/json" }, + }) + : { + workflowStates: { + nodes: [{ id: "st_in-progress", position: 1, team: { key: "ENG" } }], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + T3Issues: () => ({ + issues: { nodes: [issue("ENG-1")], pageInfo: { hasNextPage: false, endCursor: null } }, + }), + }); + const api = yield* tracker; + const fill = () => + api + .listIssues({ + ...target, + state: "open", + involvement: "all", + viewer: "julius", + sort: "created", + limit: 50, + }) + .pipe(Effect.map((page) => page.items[0]?.state.startedFill)); + expect(yield* fill()).toBeUndefined(); + expect(yield* fill()).toBe(0.5); + expect(yield* fill()).toBe(0.5); + expect(reads).toBe(2); + }), + ); + it.effect("reacts to a comment only when it belongs to the issue named", () => Effect.gen(function* () { const created: Array = []; @@ -475,7 +559,10 @@ describe("LinearIssueTracker", () => { projectMilestones: { nodes: [ { id: "ms_2", name: "GA", progress: 0, targetDate: null, sortOrder: 2 }, - { id: "ms_1", name: "Beta", progress: 1, targetDate: null, sortOrder: 1 }, + { id: "ms_1", name: "Beta", progress: 100, targetDate: null, sortOrder: 1 }, + // Linear's milestone progress is a percentage: 75 is three quarters, not done. + { id: "ms_3", name: "RC", progress: 75, targetDate: null, sortOrder: 3 }, + { id: "ms_4", name: "Early", progress: 0.5, targetDate: null, sortOrder: 4 }, ], }, }, @@ -525,9 +612,17 @@ describe("LinearIssueTracker", () => { state: "open", limit: 50, }); - expect(project.containers.map((milestone) => [milestone.name, milestone.completed])).toEqual([ - ["Beta", true], - ["GA", false], + expect( + project.containers.map((milestone) => [ + milestone.name, + milestone.progress, + milestone.completed, + ]), + ).toEqual([ + ["Beta", 1, true], + ["GA", 0, false], + ["RC", 0.75, false], + ["Early", 0.005, false], ]); expect(project.items[0]).toMatchObject({ key: "ENG-7", diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts index 9da24eb10ace1..adadccbbdc4eb 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts @@ -3,9 +3,12 @@ * (`ENG-123`). A workflow state is closed when its type is `completed` or `canceled`, so closing * picks the team's first state of that type, as Linear's own "Done" and "Canceled" do. */ +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Schema from "effect/Schema"; import { + IssueStateType, type IssueActor, type IssueCapabilities, type IssueComment, @@ -129,10 +132,45 @@ function parseIdentifier(key: string): string | null { return /^[A-Za-z][A-Za-z0-9]*-[1-9]\d*$/.test(key.trim()) ? key.trim().toUpperCase() : null; } -function toState(state: LinearApi.LinearWorkflowState): IssueState { +/** A started state's place on its team's workflow, by state id: Linear's pie fill, 0..1. */ +type StartedFills = ReadonlyMap; + +/** (index + 1) / (count + 1) among the team's started states, ordered by `position`. */ +function startedFillsOf( + states: ReadonlyArray<{ + readonly id: string; + readonly position: number; + readonly team: { readonly key: string }; + }>, +): StartedFills { + const byTeam = new Map>(); + for (const state of states) { + const team = byTeam.get(state.team.key); + if (team) team.push(state); + else byTeam.set(state.team.key, [state]); + } + const fills = new Map(); + for (const team of byTeam.values()) { + team + .toSorted((a, b) => a.position - b.position) + .forEach((state, index) => fills.set(state.id, (index + 1) / (team.length + 1))); + } + return fills; +} + +const isStateType = Schema.is(IssueStateType); + +function toState(state: LinearApi.LinearWorkflowState, fills: StartedFills): IssueState { + const type = isStateType(state.type) ? state.type : undefined; + const fill = state.type === "started" ? fills.get(state.id) : undefined; + const look = { + ...(type === undefined ? {} : { type }), + ...(state.color ? { color: state.color } : {}), + ...(fill === undefined ? {} : { startedFill: fill }), + }; return CLOSED_STATE_TYPES.includes(state.type) - ? { category: "closed", name: state.name, closeReason: state.type } - : { category: "open", name: state.name }; + ? { category: "closed", name: state.name, closeReason: state.type, ...look } + : { category: "open", name: state.name, ...look }; } /** @@ -166,14 +204,18 @@ function userName(user: LinearApi.LinearUser): string { } /** Linear's connections report no totals, so a listing shows no comment count. */ -function toSummary(issue: LinearApi.LinearIssue, commentCount = 0): TrackerIssueSummary { +function toSummary( + issue: LinearApi.LinearIssue, + fills: StartedFills, + commentCount = 0, +): TrackerIssueSummary { return { key: issue.identifier, displayKey: issue.identifier, title: issue.title, url: issue.url, author: actorOf(issue.creator, issue.botActor), - state: toState(issue.state), + state: toState(issue.state, fills), createdAt: issue.createdAt, updatedAt: issue.updatedAt, closedAt: issue.completedAt ?? issue.canceledAt ?? null, @@ -185,18 +227,18 @@ function toSummary(issue: LinearApi.LinearIssue, commentCount = 0): TrackerIssue type LinearIssueRefNode = NonNullable; -function toRelated(issue: LinearIssueRefNode): IssueRelatedRef { +function toRelated(issue: LinearIssueRefNode, fills: StartedFills): IssueRelatedRef { return { key: issue.identifier, displayKey: issue.identifier, title: issue.title, url: issue.url, - state: toState(issue.state), + state: toState(issue.state, fills), }; } /** Linear stores "A blocks B" once, on A; B finds it among its inverse relations. */ -function detailExtras(issue: LinearApi.LinearIssueDetail) { +function detailExtras(issue: LinearApi.LinearIssueDetail, fills: StartedFills) { const containers: IssueContainerRef[] = [ ...(issue.project === null ? [] @@ -215,14 +257,14 @@ function detailExtras(issue: LinearApi.LinearIssueDetail) { ...(issue.branchName ? { branchName: issue.branchName } : {}), ...(issue.priorityLabel ? { priorityLabel: issue.priorityLabel } : {}), containers, - ...(issue.parent === null ? {} : { parent: toRelated(issue.parent) }), - subIssues: issue.children.nodes.map(toRelated), + ...(issue.parent === null ? {} : { parent: toRelated(issue.parent, fills) }), + subIssues: issue.children.nodes.map((child) => toRelated(child, fills)), blockedBy: issue.inverseRelations.nodes .filter((relation) => relation.type === "blocks") - .map((relation) => toRelated(relation.issue)), + .map((relation) => toRelated(relation.issue, fills)), blocks: issue.relations.nodes .filter((relation) => relation.type === "blocks") - .map((relation) => toRelated(relation.relatedIssue)), + .map((relation) => toRelated(relation.relatedIssue, fills)), }; } @@ -243,15 +285,17 @@ function toProjectContainer(project: LinearApi.LinearProject): IssueContainer { }; } +/** Linear reports a milestone's progress as a percentage (0..100), a project's as 0..1. */ function toMilestoneContainer(milestone: LinearApi.LinearMilestone): IssueContainer { + const progress = Math.min(1, Math.max(0, milestone.progress / 100)); return { kind: "milestone", id: milestone.id, name: milestone.name, - progress: milestone.progress, + progress, targetDate: milestone.targetDate ?? null, status: null, - completed: milestone.progress >= 1, + completed: progress >= 1, url: null, }; } @@ -486,6 +530,15 @@ export const make: Effect.Effect (Exit.isSuccess(exit) ? Duration.minutes(5) : Duration.zero), + ); + /** Fill data is decoration: a failed read leaves started states at the client's default. */ + const startedFills = cachedStartedFills.pipe( + Effect.orElseSucceed((): StartedFills => new Map()), + ); + const viewerId: Effect.Effect = linear.viewer().pipe( Effect.map((data) => data.viewer.id), Effect.orElseSucceed(() => null), @@ -551,39 +604,47 @@ export const make: Effect.Effect ({ - items: page.nodes.map((node) => toSummary(node)), - nextCursor: page.nextCursor, - })), - ); + return Effect.all( + [ + linear.listIssues({ + filter, + first: input.limit, + after: input.cursor, + orderBy: input.sort === "created" ? "createdAt" : "updatedAt", + }), + startedFills, + ], + { concurrency: 2 }, + ).pipe( + Effect.map(([page, fills]) => ({ + items: page.nodes.map((node) => toSummary(node, fills)), + nextCursor: page.nextCursor, + })), + ); }, getIssue: Effect.fn("LinearIssueTracker.getIssue")(function* (input) { const identifier = yield* requireIdentifier("getIssue", input.key); // One read of the viewer: the id matches reactions, the handle is what the client sees. - const [issue, me] = yield* Effect.all([ - linear.getIssue(identifier, COMMENTS_PAGE), - linear.viewer().pipe( - Effect.map((data) => data.viewer), - Effect.orElseSucceed(() => null), - ), - ]); + const [issue, me, fills] = yield* Effect.all( + [ + linear.getIssue(identifier, COMMENTS_PAGE), + linear.viewer().pipe( + Effect.map((data) => data.viewer), + Effect.orElseSucceed(() => null), + ), + startedFills, + ], + { concurrency: 3 }, + ); const viewer = me?.id ?? null; if (issue === null) return yield* notFound("getIssue"); return { - ...toSummary(issue, issue.comments.nodes.length), + ...toSummary(issue, fills, issue.comments.nodes.length), body: issue.description ?? "", viewer: me === null ? null : toActor(me).login, viewerPermissions: VIEWER_PERMISSIONS, - states: inWorkflowOrder(issue.team.states.nodes).map(toState), + states: inWorkflowOrder(issue.team.states.nodes).map((node) => toState(node, fills)), reactions: toReactions(issue.reactions, viewer), comments: issue.comments.nodes.map((comment) => toComment(comment, viewer)), commentsCursor: issue.comments.pageInfo.hasNextPage @@ -591,7 +652,7 @@ export const make: Effect.Effect ({ - ...toSummary(node), + ...toSummary(node, fills), parentKey: node.parent?.identifier ?? null, subIssueCount: node.children.nodes.length, blocked: node.inverseRelations.nodes.some( diff --git a/packages/shared/src/linearIssueMarkdown.ts b/packages/shared/src/linearIssueMarkdown.ts index 7f2753f183c5d..bca61a3cb5cce 100644 --- a/packages/shared/src/linearIssueMarkdown.ts +++ b/packages/shared/src/linearIssueMarkdown.ts @@ -8,6 +8,7 @@ export type LinearIssueSnapshot = Omit< const SUB_ISSUE_CHECKBOX: Readonly> = { completed: "[x]", canceled: "[-]", + duplicate: "[-]", }; /** One text rendering of an issue, shared by the agent's context payload and pipeline input. */ diff --git a/packages/shared/src/linearLaunch.test.ts b/packages/shared/src/linearLaunch.test.ts index 64979c6547350..3157df99e5207 100644 --- a/packages/shared/src/linearLaunch.test.ts +++ b/packages/shared/src/linearLaunch.test.ts @@ -118,5 +118,13 @@ describe("linear issue launch context", () => { it("names a closed state by how it closed", () => { expect([open, done, canceled].map(issueStateType)).toEqual(["open", "completed", "canceled"]); + expect( + issueStateType({ + category: "closed", + name: "Dup", + closeReason: "duplicate", + type: "duplicate", + }), + ).toBe("duplicate"); }); }); diff --git a/packages/shared/src/linearLaunch.ts b/packages/shared/src/linearLaunch.ts index a31a9c981d61f..e04f01f2c711b 100644 --- a/packages/shared/src/linearLaunch.ts +++ b/packages/shared/src/linearLaunch.ts @@ -27,8 +27,12 @@ const COMMENT_TRUNCATION_MARKER = " [comment truncated]"; const INPUT_TRUNCATION_NOTE = "\n\n[The rest of this issue was left out: it exceeds the input size limit.]"; -/** `completed`, `canceled` (any other way of closing) or `open`: what the checkboxes key off. */ +/** + * Linear's workflow type where the tracker reports one (the chip draws its glyph), otherwise + * `completed`, `canceled` (any other way of closing) or `open`. The checkboxes key off it. + */ export function issueStateType(state: IssueState): string { + if (state.type !== undefined) return state.type; if (state.category === "open") return "open"; return state.closeReason === "completed" ? "completed" : "canceled"; }