@devries-cameron20 / t3code Mirror · read-only / commits / 49fad98aec
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 08:30 UTC

refactor(issues): move issues between their tracker's own states (#37930)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Julius Marminge committed Nov 16, 2026 at 22:00 UTC 49fad98aecba1e1f11da0c4e9476c4ef31e31cbc
30 files changed +516 -359
apps/mobile/src/features/issues/IssueRouteScreen.tsx
+10 -52
@@ -1,13 +1,9 @@
1 import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
2 -import {
3 - issueCloseReasonLabel,
4 - issueEventSentence,
5 -} from "@t3tools/client-runtime/issue-presentation";
2 +import { issueEventSentence } from "@t3tools/client-runtime/issue-presentation";
3 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4 import { prependIssueComments } from "@t3tools/client-runtime/state/issues";
5 import type {
6 IssueComment,
10 - IssueDetail,
7 IssueEvent,
8 IssueLinkedPullRequest,
9 IssueReaction,
@@ -100,43 +96,12 @@ function IssueReactions(props: {
96
97 function IssueStateControl(props: {
98 readonly state: IssueState;
103 - readonly detail: IssueDetail | null;
99 readonly states: ReadonlyArray<IssueState>;
100 readonly busy: boolean;
106 - readonly onMove: (state: string, closeReason?: string) => void;
101 + readonly onMove: (state: string) => void;
102 }) {
103 const status = issueStatus(props.state);
109 - const reasons = props.detail?.capabilities.closeReasons ?? [];
110 - const moves = props.states.flatMap(
111 - (
112 - state,
113 - ): ReadonlyArray<{
114 - readonly id: string;
115 - readonly state: string;
116 - readonly reason?: string;
117 - readonly title: string;
118 - }> =>
119 - state.category === "closed" && reasons.length > 0
120 - ? reasons.map((reason) => ({
121 - // No NUL separator: it ends the native string, and UIKit drops a duplicate id.
122 - id: `${state.name}:${reason}`,
123 - state: state.name,
124 - reason,
125 - title: `${state.name === "closed" ? "Close" : state.name} as ${issueCloseReasonLabel(reason).toLowerCase()}`,
126 - }))
127 - : [
128 - {
129 - id: state.name,
130 - state: state.name,
131 - title:
132 - state.category === "open" && state.name === "open"
133 - ? "Reopen"
134 - : state.name === "closed"
135 - ? "Close"
136 - : `Move to ${state.name}`,
137 - },
138 - ],
139 - );
104 + const moves = props.states;
105 const trigger = (
106 <Pressable
107 accessibilityRole={moves.length ? "button" : undefined}
@@ -157,10 +122,11 @@ function IssueStateControl(props: {
122 <View className="self-start">
123 <Menu
124 title="Issue state"
160 - actions={moves.map((move) => ({ id: move.id, title: move.title }))}
125 + // The name is the id: unique within a workflow, and a NUL separator would end the native string.
126 + actions={moves.map((move) => ({ id: move.name, title: move.name }))}
127 onPressAction={({ nativeEvent }) => {
162 - const move = moves.find((candidate) => candidate.id === nativeEvent.event);
163 - if (move) props.onMove(move.state, move.reason);
128 + if (moves.some((move) => move.name === nativeEvent.event))
129 + props.onMove(nativeEvent.event);
130 }}
131 >
132 {trigger}
@@ -171,10 +137,9 @@ function IssueStateControl(props: {
137
138 function IssueIdentity(props: {
139 readonly issue: IssueSummary;
174 - readonly detail: IssueDetail | null;
140 readonly access: IssueAccess | null;
141 readonly busy: boolean;
177 - readonly onMove: (state: string, closeReason?: string) => void;
142 + readonly onMove: (state: string) => void;
143 readonly onEditLabels: () => void;
144 readonly onEditAssignees: () => void;
145 }) {
@@ -185,7 +150,6 @@ function IssueIdentity(props: {
150 <View className="gap-3">
151 <IssueStateControl
152 state={issue.state}
188 - detail={props.detail}
153 states={access?.states ?? []}
154 busy={props.busy}
155 onMove={props.onMove}
@@ -468,13 +432,8 @@ function IssueRoute({ params }: { readonly params: IssueParams }) {
432 access?.comment === true
433 ? run("comment", () => postComment({ ...target, input: { ...target.input, body } }))
434 : Promise.resolve(false);
471 - const moveTo = (state: string, closeReason?: string) =>
472 - void run("state", () =>
473 - setState({
474 - ...target,
475 - input: { ...target.input, state, ...(closeReason === undefined ? {} : { closeReason }) },
476 - }),
477 - );
435 + const moveTo = (state: string) =>
436 + void run("state", () => setState({ ...target, input: { ...target.input, state } }));
437
438 const showComposer = detail?.capabilities.comment === true;
439 const commentBlocked =
@@ -592,7 +551,6 @@ function IssueRoute({ params }: { readonly params: IssueParams }) {
551 <View className="gap-5">
552 <IssueIdentity
553 issue={issue}
595 - detail={detail}
554 access={access}
555 busy={busy === "state"}
556 onMove={moveTo}
apps/mobile/src/features/issues/issuePresentation.tsx
+5 -5
@@ -1,5 +1,5 @@
1 import { useAtomValue } from "@effect/atom-react";
2 -import { issueStateLabel, issueWriteAccess } from "@t3tools/client-runtime/issue-presentation";
2 +import { issueWriteAccess } from "@t3tools/client-runtime/issue-presentation";
3 import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
@@ -16,15 +16,15 @@ import { pullRequestLabelColor } from "../pull-requests/pullRequestList";
16 import { usePullRequestConnected } from "../pull-requests/usePullRequestConnected";
17 import { issueTarget, type IssueParams } from "./issueParams";
18
19 -// Open and completed wear the pull request colors for open and merged; not planned is grey,
20 -// because work that stopped must not look like work that finished.
19 +// Open and completed wear the pull request colors for open and merged; closed any other way
20 +// than completed is grey, because work that stopped must not look like work that finished.
21 export function issueStatus(state: IssueState): {
22 readonly label: string;
23 readonly icon: AppSymbolName;
24 readonly tint: string;
25 readonly text: string;
26 } {
27 - const label = issueStateLabel(state);
27 + const label = state.name;
28 if (state.category === "open")
29 return {
30 label,
@@ -32,7 +32,7 @@ export function issueStatus(state: IssueState): {
32 tint: "accent-adaptive-emerald-600-400",
33 text: "text-adaptive-emerald-600-400",
34 };
35 - if (state.closeReason === "not-planned")
35 + if (state.closeReason !== undefined && state.closeReason !== "completed")
36 return {
37 label,
38 icon: "slash.circle",
apps/server/src/issue/IssueService.test.ts
+3 -12
@@ -101,6 +101,7 @@ function issue(key: string, updatedAt = "2026-07-02T00:00:00Z"): TrackerIssueDet
101 body: "",
102 viewer: "julius",
103 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
104 + states: [],
105 comments: [],
106 commentsCursor: null,
107 events: [],
@@ -122,11 +123,6 @@ function fakeTracker(overrides: Partial<IssueTrackerApi> = {}): IssueTrackerApi
123 linkedPullRequests: true,
124 events: true,
125 search: true,
125 - states: [
126 - { category: "open", name: "open" },
127 - { category: "closed", name: "closed" },
128 - ],
129 - closeReasons: ["completed"],
126 },
127 getViewer: () => Effect.succeed("julius"),
128 listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
@@ -323,13 +319,8 @@ describe("IssueService", () => {
319 });
320 const ref = { projectId: "web" as ProjectId, tracker: GITHUB, scope: "acme/web", key: "1" };
321
326 - yield* service.setState({ ...ref, state: "closed", closeReason: "completed" });
327 - const unknownState = yield* Effect.flip(service.setState({ ...ref, state: "In Review" }));
328 - expect(unknownState._tag).toBe("IssueOperationError");
329 - const unknownReason = yield* Effect.flip(
330 - service.setState({ ...ref, state: "closed", closeReason: "not-planned" }),
331 - );
332 - expect(unknownReason._tag).toBe("IssueOperationError");
322 + // The state is the tracker's own name, passed through: the tracker is what proves it.
323 + yield* service.setState({ ...ref, state: "In Review" });
324 const reaction = yield* Effect.flip(
325 service.react({ ...ref, content: "heart", reacted: true }),
326 );
apps/server/src/issue/IssueService.ts
+2 -10
@@ -575,15 +575,8 @@ const make = Effect.gen(function* () {
575 const setState: IssueService["Service"]["setState"] = (input) =>
576 requireWritable(input, "setState").pipe(
577 Effect.flatMap((project) => {
578 - const { capabilities } = project.api;
579 - const target = capabilities.states.find((state) => state.name === input.state);
580 - if (project.api.setState === undefined || target === undefined)
581 - return Effect.fail(unsupported("setState", `the state "${input.state}"`));
582 - if (
583 - input.closeReason !== undefined &&
584 - (target.category !== "closed" || !capabilities.closeReasons.includes(input.closeReason))
585 - )
586 - return Effect.fail(unsupported("setState", `the close reason "${input.closeReason}"`));
578 + if (project.api.setState === undefined)
579 + return Effect.fail(unsupported("setState", "changing an issue's state"));
580 return project.api
581 .setState({
582 cwd: project.project.workspaceRoot,
@@ -591,7 +584,6 @@ const make = Effect.gen(function* () {
584 scope: project.scope,
585 key: input.key,
586 state: input.state,
594 - closeReason: input.closeReason,
587 })
588 .pipe(Effect.mapError(toIssueError("setState")));
589 }),
apps/server/src/mcp/toolkits/issues/handlers.test.ts
+1 -2
@@ -122,9 +122,8 @@ const detail: IssueDetail = {
122 linkedPullRequests: true,
123 events: true,
124 search: true,
125 - states: [],
126 - closeReasons: [],
125 },
126 + states: [],
127 viewerPermissions: { setState: true, comment: true, edit: true, labels: true, assignees: true },
128 viewer: null,
129 body: "",
apps/server/src/mcp/toolkits/issues/handlers.ts
+1 -1
@@ -198,6 +198,7 @@ const make = Effect.gen(function* () {
198 state: detail.state,
199 writable: detail.writable,
200 capabilities: detail.capabilities,
201 + states: detail.states,
202 author: detail.author?.login ?? null,
203 assignees: detail.assignees.map((actor) => actor.login),
204 labels: detail.labels.map((label) => label.name),
@@ -252,7 +253,6 @@ const make = Effect.gen(function* () {
253 yield* issues.setState({
254 ...refOf(target),
255 state: input.state,
255 - ...(input.closeReason === undefined ? {} : { closeReason: input.closeReason }),
256 });
257 return identityOf(target);
258 }),
apps/server/src/mcp/toolkits/issues/tools.ts
+3 -8
@@ -171,6 +171,7 @@ export const ReadIssueResult = Schema.Struct({
171 /** False for an issue outside every project's own scope: it can be read, not changed. */
172 writable: Schema.Boolean,
173 capabilities: IssueCapabilities,
174 + states: Schema.Array(IssueState),
175 author: Schema.NullOr(Schema.String),
176 assignees: Schema.Array(Schema.String),
177 labels: Schema.Array(Schema.String),
@@ -315,18 +316,12 @@ const CommentOnIssueTool = Tool.make("comment_on_issue", {
316 .annotate(Tool.OpenWorld, true);
317
318 const SetIssueStateTool = Tool.make("set_issue_state", {
318 - description:
319 - "Move an issue to a state its tracker offers. read_issue lists them under capabilities.states.",
319 + description: "Move an issue to one of its states. read_issue lists them under states.",
320 parameters: Schema.Struct({
321 ...IssueTargetInput.fields,
322 state: TrimmedNonEmptyString.annotate({
323 - description: "A state name from capabilities.states.",
323 + description: "A state name from read_issue's states.",
324 }),
325 - closeReason: Schema.optional(
326 - TrimmedNonEmptyString.annotate({
327 - description: "From capabilities.closeReasons, for a closing state.",
328 - }),
329 - ),
325 }),
326 success: IssueWriteResult,
327 failure: IssueToolError,
apps/server/src/provider/agentContextBudget.json
+1 -1
@@ -1,5 +1,5 @@
1 {
2 "claudeSystemAppendBytes": 5930,
3 "codexAdditionalContextBytes": 7324,
4 - "mcpToolListJsonBytes": 52199
4 + "mcpToolListJsonBytes": 52145
5 }
apps/web/src/components/issue/IssueDetailPanel.tsx
+48 -71
@@ -1,9 +1,5 @@
1 import { useAtomValue } from "@effect/atom-react";
2 -import {
3 - issueCloseReasonLabel,
4 - issueEventSentence,
5 - issueWriteAccess,
6 -} from "@t3tools/client-runtime/issue-presentation";
2 +import { issueEventSentence, issueWriteAccess } from "@t3tools/client-runtime/issue-presentation";
3 import { prependIssueComments } from "@t3tools/client-runtime/state/issues";
4 import {
5 issueAssigneeHeld,
@@ -505,11 +501,9 @@ export function IssueDetailPanel({
501 const canLabel = access.labels;
502 const canAssign = access.assignees;
503 const canReact = access.react;
508 - const canSetState = access.states.length > 0;
504 const otherStates = access.states;
505 const tracker = issueTrackerPresentation(detail.tracker);
511 - const closingStates = otherStates.filter((state) => state.category === "closed");
512 - const openingStates = otherStates.filter((state) => state.category === "open");
506 + const currentState = issueStatePresentation(detail.state);
507
508 const loadOlder = async () => {
509 if (nextCursor === null || loadingOlder) return;
@@ -546,12 +540,12 @@ export function IssueDetailPanel({
540 setEditing(null);
541 };
542
549 - const moveTo = async (state: string, closeReason?: string) => {
543 + const moveTo = async (state: string) => {
544 if (changingState) return;
545 setChangingState(true);
546 const result = await setState({
547 environmentId,
554 - input: { ...reference, state, ...(closeReason === undefined ? {} : { closeReason }) },
548 + input: { ...reference, state },
549 });
550 setChangingState(false);
551 if (result._tag === "Failure") {
@@ -565,64 +559,50 @@ export function IssueDetailPanel({
559 refreshIssueLists(environmentId);
560 };
561
568 - const stateControl: ReactNode = canSetState ? (
569 - <span className="flex shrink-0 items-center gap-1">
570 - {openingStates.length === 1 && closingStates.length === 0 ? (
571 - <Button
572 - size="xs"
573 - variant="outline"
574 - disabled={changingState}
575 - onClick={() => void moveTo(openingStates[0]!.name)}
576 - >
577 - Reopen
578 - </Button>
579 - ) : null}
580 - {closingStates.length === 1 &&
581 - detail.capabilities.closeReasons.length === 0 &&
582 - openingStates.length === 0 ? (
583 - <Button
584 - size="xs"
585 - variant="outline"
586 - disabled={changingState}
587 - onClick={() => void moveTo(closingStates[0]!.name)}
562 + const currentStateIcon = (
563 + <currentState.Icon
564 + aria-hidden
565 + className={cn("size-3.5 shrink-0", currentState.toneClassName)}
566 + />
567 + );
568 + const stateControl: ReactNode =
569 + otherStates.length > 0 ? (
570 + <Menu>
571 + <MenuTrigger
572 + render={
573 + <Button
574 + size="xs"
575 + variant="outline"
576 + aria-label={`Issue state, ${currentState.label}`}
577 + disabled={changingState}
578 + />
579 + }
580 >
589 - Close
590 - </Button>
591 - ) : null}
592 - {(closingStates.length > 0 && detail.capabilities.closeReasons.length > 0) ||
593 - otherStates.length > 1 ? (
594 - <Menu>
595 - <MenuTrigger render={<Button size="xs" variant="outline" disabled={changingState} />}>
596 - {detail.state.category === "open" ? "Close" : "Change state"}
597 - <ChevronDownIcon aria-hidden className="size-3" />
598 - </MenuTrigger>
599 - <MenuPopup align="end">
600 - {otherStates.flatMap((state) =>
601 - state.category === "closed" && detail.capabilities.closeReasons.length > 0
602 - ? detail.capabilities.closeReasons.map((reason) => (
603 - <MenuItem
604 - key={`${state.name}:${reason}`}
605 - onClick={() => void moveTo(state.name, reason)}
606 - >
607 - {state.name === "closed" ? "Close" : state.name} as{" "}
608 - {issueCloseReasonLabel(reason).toLowerCase()}
609 - </MenuItem>
610 - ))
611 - : [
612 - <MenuItem key={state.name} onClick={() => void moveTo(state.name)}>
613 - {state.category === "open" && state.name === "open"
614 - ? "Reopen"
615 - : state.name === "closed"
616 - ? "Close"
617 - : `Move to ${state.name}`}
618 - </MenuItem>,
619 - ],
620 - )}
621 - </MenuPopup>
622 - </Menu>
623 - ) : null}
624 - </span>
625 - ) : null;
581 + {currentStateIcon}
582 + {currentState.label}
583 + <ChevronDownIcon aria-hidden className="size-3" />
584 + </MenuTrigger>
585 + <MenuPopup align="end">
586 + {otherStates.map((state) => {
587 + const presentation = issueStatePresentation(state);
588 + return (
589 + <MenuItem key={state.name} onClick={() => void moveTo(state.name)}>
590 + <presentation.Icon
591 + aria-hidden
592 + className={cn("size-3.5 shrink-0", presentation.toneClassName)}
593 + />
594 + {state.name}
595 + </MenuItem>
596 + );
597 + })}
598 + </MenuPopup>
599 + </Menu>
600 + ) : (
601 + <span className="flex shrink-0 items-center gap-1 font-medium">
602 + {currentStateIcon}
603 + {currentState.label}
604 + </span>
605 + );
606
607 return (
608 <div className="relative flex h-full min-h-0 flex-col">
@@ -640,10 +620,7 @@ export function IssueDetailPanel({
620 {detail.scope}
621 </span>
622 <InlineButton
643 - className={cn(
644 - "shrink-0 font-medium",
645 - issueStatePresentation(detail.state).toneClassName,
646 - )}
623 + className={cn("shrink-0 font-medium", currentState.toneClassName)}
624 aria-label={`Open ${detail.displayKey} on ${tracker.providerName}`}
625 render={<a href={detail.url} target="_blank" rel="noopener noreferrer" />}
626 >
apps/web/src/components/issue/issuePresentation.tsx
+6 -7
@@ -1,4 +1,3 @@
1 -import { issueStateLabel } from "@t3tools/client-runtime/issue-presentation";
1 import type { IssueState, IssueTrackerKind } from "@t3tools/contracts";
2 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 import { CircleCheckIcon, CircleDotIcon, CircleSlashIcon, TicketIcon } from "lucide-react";
@@ -27,28 +26,28 @@ export function issueTrackerPresentation(tracker: IssueTrackerKind | string) {
26
27 /**
28 * Open and completed borrow the ink the pull-request states use for open and merged, so green
30 - * and violet mean the same thing on both pages; not planned wears a draft's grey, because work
31 - * that stopped must not look like work that finished. The tracker's own state name is the label,
29 + * and violet mean the same thing on both pages; closed any other way than completed wears a
30 + * draft's grey, because work that stopped must not look like work that finished. The tracker's own state name is the label,
31 * so a workflow tracker's "In Review" reads as itself.
32 */
33 export function issueStatePresentation(state: IssueState) {
34 if (state.category === "open") {
35 return {
36 ...PULL_REQUEST_STATE_PRESENTATION.open,
38 - label: issueStateLabel(state),
37 + label: state.name,
38 Icon: CircleDotIcon,
39 };
40 }
42 - if (state.closeReason === "not-planned") {
41 + if (state.closeReason !== undefined && state.closeReason !== "completed") {
42 return {
43 ...PULL_REQUEST_STATE_PRESENTATION.draft,
45 - label: issueStateLabel(state),
44 + label: state.name,
45 Icon: CircleSlashIcon,
46 };
47 }
48 return {
49 ...PULL_REQUEST_STATE_PRESENTATION.merged,
51 - label: issueStateLabel(state),
50 + label: state.name,
51 Icon: CircleCheckIcon,
52 };
53 }
packages/client-runtime/src/issuePresentation.test.ts
+35 -14
@@ -1,21 +1,42 @@
1 -import type { IssueDetail } from "@t3tools/contracts";
1 +import type { IssueDetail, IssueState } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3
4 import { issueWriteAccess } from "./issuePresentation.ts";
5
6 +const workflow: ReadonlyArray<IssueState> = [
7 + { category: "open", name: "Backlog" },
8 + { category: "open", name: "Todo" },
9 + { category: "open", name: "In Progress" },
10 + { category: "closed", name: "Done", closeReason: "completed" },
11 + { category: "closed", name: "Canceled", closeReason: "canceled" },
12 + { category: "closed", name: "Duplicate", closeReason: "duplicate" },
13 +];
14 +
15 +function issue(overrides: { writable?: boolean; setState?: boolean; states?: typeof workflow }) {
16 + return {
17 + writable: overrides.writable ?? true,
18 + state: { category: "open", name: "Todo" },
19 + states: overrides.states ?? workflow,
20 + capabilities: {},
21 + viewerPermissions: { setState: overrides.setState ?? true },
22 + } as unknown as IssueDetail;
23 +}
24 +
25 describe("issueWriteAccess", () => {
7 - it("does not offer the category an issue is already in under a workflow name", () => {
8 - const detail = {
9 - writable: true,
10 - state: { category: "open", name: "Todo" },
11 - capabilities: {
12 - states: [
13 - { category: "open", name: "open" },
14 - { category: "closed", name: "closed" },
15 - ],
16 - },
17 - viewerPermissions: { setState: true },
18 - } as unknown as IssueDetail;
19 - expect(issueWriteAccess(detail, true).states).toEqual([{ category: "closed", name: "closed" }]);
26 + it("offers every other state of the issue's workflow, in the tracker's order", () => {
27 + expect(issueWriteAccess(issue({}), true).states.map((state) => state.name)).toEqual([
28 + "Backlog",
29 + "In Progress",
30 + "Done",
31 + "Canceled",
32 + "Duplicate",
33 + ]);
34 + });
35 +
36 + it("offers no state when the issue cannot be moved", () => {
37 + expect(issueWriteAccess(issue({ setState: false }), true).states).toEqual([]);
38 + expect(issueWriteAccess(issue({ writable: false }), true).states).toEqual([]);
39 + expect(issueWriteAccess(issue({}), false).states).toEqual([]);
40 + expect(issueWriteAccess(issue({ states: [] }), true).states).toEqual([]);
41 });
42 });
packages/client-runtime/src/issuePresentation.ts
+4 -19
@@ -1,19 +1,11 @@
1 -import type { IssueDetail, IssueEvent, IssueState } from "@t3tools/contracts";
1 +import type { IssueDetail, IssueEvent } from "@t3tools/contracts";
2
3 /** "completed" → "Completed"; a reason the tracker spells with a dash reads as words. */
4 -export function issueCloseReasonLabel(reason: string): string {
4 +function issueCloseReasonLabel(reason: string): string {
5 const words = reason.replace(/[-_]+/g, " ").trim();
6 return words.charAt(0).toUpperCase() + words.slice(1);
7 }
8
9 -/** The tracker's own state name is the label, so a workflow tracker's "In Review" reads as itself. */
10 -export function issueStateLabel(state: IssueState): string {
11 - if (state.category === "open") return state.name === "open" ? "Open" : state.name;
12 - if (state.closeReason === "not-planned") return "Closed as not planned";
13 - if (state.name !== "closed") return state.name;
14 - return state.closeReason === "completed" ? "Closed as completed" : "Closed";
15 -}
16 -
9 export function issueEventSentence(event: IssueEvent): string {
10 switch (event.kind) {
11 case "closed":
@@ -51,13 +43,6 @@ export function issueWriteAccess(detail: IssueDetail, canWrite: boolean) {
43 : null;
44 const may = (capability: boolean, permission: boolean) =>
45 blocked === null && capability && permission;
54 - // A tracker with a workflow of its own offers the two categories by name ("open", "closed")
55 - // while its issues carry workflow names ("Todo"), so the category alone says it is already there.
56 - const others = detail.capabilities.states.filter(
57 - (state) =>
58 - state.category !== detail.state.category ||
59 - (state.name !== detail.state.name && state.name !== state.category),
60 - );
46 return {
47 blocked,
48 comment: may(detail.capabilities.comment, detail.viewerPermissions.comment),
@@ -66,8 +51,8 @@ export function issueWriteAccess(detail: IssueDetail, canWrite: boolean) {
51 assignees: may(detail.capabilities.assignees, detail.viewerPermissions.assignees),
52 react: blocked === null && detail.capabilities.reactions,
53 /** The states the issue can move to; empty when the viewer may not move it. */
69 - states: may(detail.capabilities.states.length > 0, detail.viewerPermissions.setState)
70 - ? others
54 + states: may(true, detail.viewerPermissions.setState)
55 + ? detail.states.filter((state) => state.name !== detail.state.name)
56 : [],
57 };
58 }
packages/contracts/src/issue.ts
+11 -15
@@ -36,10 +36,10 @@ export const IssueLabel = PullRequestLabel;
36 export type IssueLabel = typeof IssueLabel.Type;
37
38 /**
39 - * Where an issue stands, in two parts: the category every tracker has, and the name this tracker
40 - * gives it. GitHub only has the two; Linear and Jira have a workflow of their own ("In Review",
41 - * "Backlog"), which `name` carries verbatim so the page can show the tracker's word while every
42 - * filter and badge keys off `category`.
39 + * Where an issue stands: the tracker's own name for the state ("In Review", "Closed as not
40 + * planned"), which is what people read and what a move is asked for by, and the category every
41 + * tracker has, which only filters and colours key off. Nothing moves an issue to "open" or
42 + * "closed": it moves to one of the states its `IssueDetail.states` lists.
43 */
44 export const IssueStateCategory = Schema.Literals(["open", "closed"]);
45 export type IssueStateCategory = typeof IssueStateCategory.Type;
@@ -47,7 +47,7 @@ export type IssueStateCategory = typeof IssueStateCategory.Type;
47 export const IssueState = Schema.Struct({
48 category: IssueStateCategory,
49 name: TrimmedNonEmptyString,
50 - /** Why it was closed, where the tracker records one (GitHub: `completed` / `not-planned`). */
50 + /** How a closed state ended, where the tracker says: `completed`, or its word for not done. */
51 closeReason: Schema.optional(TrimmedNonEmptyString),
52 });
53 export type IssueState = typeof IssueState.Type;
@@ -193,14 +193,6 @@ export const IssueCapabilities = Schema.Struct({
193 events: Schema.Boolean,
194 /** The tracker narrows a listing by free text itself. */
195 search: Schema.Boolean,
196 - /**
197 - * The states this tracker can be asked to move an issue into, by name. A git host offers
198 - * `open` and `closed`; a workflow tracker offers its own columns. Empty means state cannot be
199 - * changed from here.
200 - */
201 - states: Schema.Array(IssueState),
202 - /** Reasons a close can carry. Empty means a close takes none. */
203 - closeReasons: Schema.Array(TrimmedNonEmptyString),
196 });
197 export type IssueCapabilities = typeof IssueCapabilities.Type;
198
@@ -226,6 +218,11 @@ export const IssueDetail = Schema.Struct({
218 writable: Schema.Boolean,
219 capabilities: IssueCapabilities,
220 viewerPermissions: IssueViewerPermissions,
221 + /**
222 + * Every state this issue can be in, in the tracker's workflow order, its current one included.
223 + * Empty means its state cannot be changed from here.
224 + */
225 + states: Schema.Array(IssueState),
226 /** The signed-in account, so a comment edit is offered only on the viewer's own remarks. */
227 viewer: Schema.NullOr(TrimmedNonEmptyString),
228 body: Schema.String,
@@ -360,9 +357,8 @@ export type IssueUpdateInput = typeof IssueUpdateInput.Type;
357 /** Moves the issue to one of the states the tracker declared in `capabilities.states`. */
358 export const IssueSetStateInput = Schema.Struct({
359 ...IssueRef.fields,
360 + /** The name of one of the issue's `states`. */
361 state: TrimmedNonEmptyString,
364 - /** Only meaningful for a closing state on a tracker that declared `closeReasons`. */
365 - closeReason: Schema.optional(TrimmedNonEmptyString),
362 });
363 export type IssueSetStateInput = typeof IssueSetStateInput.Type;
364
packages/issue-tracker-linear/src/server/LinearApi.graphql
+7
@@ -119,6 +119,13 @@ query T3Issues($first: Int!, $after: String, $filter: IssueFilter!, $orderBy: Pa
119 query T3Issue($id: String!, $comments: Int!) {
120 issue(id: $id) {
121 ...LinearIssue
122 + team {
123 + states(first: 100) {
124 + nodes {
125 + ...LinearWorkflowState
126 + }
127 + }
128 + }
129 comments(first: $comments, orderBy: createdAt) {
130 nodes {
131 ...LinearComment
packages/issue-tracker-linear/src/server/LinearApi.graphql.ts
+57 -9
@@ -120,11 +120,11 @@ export const LinearComment = Schema.Struct({
120 export interface LinearComment extends Schema.Struct.Type<typeof LinearComment.fields> {}
121
122 /** A team is the primary organizational unit in Linear. Issues belong to teams, and each team has its own workflow states, cycles, labels, and settings. Teams can be public (visible to all workspace members), private (visible only to team members), or restricted (visible only within an enclosing private-team boundary). Teams can also have sub-teams that inherit settings from their parent. */
123 -export const TeamTeam = Schema.Struct({
123 +export const LinearIssueTeamTeam = Schema.Struct({
124 /** The team's unique key, used as a prefix in issue identifiers (e.g., 'ENG' in 'ENG-123') and in URLs. */
125 key: Schema.String
126 })
127 -export interface TeamTeam extends Schema.Struct.Type<typeof TeamTeam.fields> {}
127 +export interface LinearIssueTeamTeam extends Schema.Struct.Type<typeof LinearIssueTeamTeam.fields> {}
128
129 export const LinearIssueLabelsIssueLabelConnection = Schema.Struct({
130 nodes: Schema.Array(LinearLabel)
@@ -163,7 +163,7 @@ export const LinearIssue = Schema.Struct({
163 /** 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. */
164 state: LinearWorkflowState,
165 /** The team that the issue belongs to. Every issue must belong to exactly one team, which determines the available workflow states, labels, and other team-specific configuration. */
166 - team: TeamTeam,
166 + team: LinearIssueTeamTeam,
167 /** The user who created the issue. Null if the creator's account has been deleted or if the issue was created by an integration or system process. */
168 creator: Schema.NullOr(LinearUser),
169 /** The bot that created the issue, if applicable. */
@@ -267,6 +267,20 @@ export declare namespace T3Issues {
267 export type Result = typeof T3Issues.result.Type
268 }
269
270 +export const TeamStatesWorkflowStateConnection = Schema.Struct({
271 + nodes: Schema.Array(LinearWorkflowState)
272 +})
273 +export interface TeamStatesWorkflowStateConnection extends Schema.Struct.Type<typeof TeamStatesWorkflowStateConnection.fields> {}
274 +
275 +/** A team is the primary organizational unit in Linear. Issues belong to teams, and each team has its own workflow states, cycles, labels, and settings. Teams can be public (visible to all workspace members), private (visible only to team members), or restricted (visible only within an enclosing private-team boundary). Teams can also have sub-teams that inherit settings from their parent. */
276 +export const IssueTeamTeam = Schema.Struct({
277 + /** The team's unique key, used as a prefix in issue identifiers (e.g., 'ENG' in 'ENG-123') and in URLs. */
278 + key: Schema.String,
279 + /** The states that define the workflow associated with the team. */
280 + states: TeamStatesWorkflowStateConnection
281 +})
282 +export interface IssueTeamTeam extends Schema.Struct.Type<typeof IssueTeamTeam.fields> {}
283 +
284 export const CommentConnection = Schema.Struct({
285 nodes: Schema.Array(LinearComment),
286 pageInfo: LinearPageInfo
@@ -327,7 +341,41 @@ export interface IssueHistoryConnection extends Schema.Struct.Type<typeof IssueH
341
342 /** 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. */
343 export const T3IssueIssueIssue = Schema.Struct({
330 - ...LinearIssue.fields,
344 + /** The unique identifier of the entity. */
345 + id: Shared.ID,
346 + /** Issue's human readable identifier (e.g. ENG-123). */
347 + identifier: Schema.String,
348 + /** The issue's unique number, scoped to the issue's team. Together with the team key, this forms the issue's human-readable identifier (e.g., ENG-123). */
349 + number: Shared.Float,
350 + /** The issue's title. This is the primary human-readable summary of the work item. */
351 + title: Schema.String,
352 + /** Issue URL. */
353 + url: Schema.String,
354 + /** The issue's description in markdown format. */
355 + description: Schema.NullOr(Schema.String),
356 + /** The time at which the entity was created. */
357 + createdAt: Shared.DateTime,
358 + /**
359 + * The last time at which the entity was meaningfully updated. This is the same as the creation time if the entity hasn't
360 + * been updated after creation.
361 + */
362 + updatedAt: Shared.DateTime,
363 + /** The time at which the issue was moved into completed state. */
364 + completedAt: Schema.NullOr(Shared.DateTime),
365 + /** The time at which the issue was moved into canceled state. */
366 + canceledAt: Schema.NullOr(Shared.DateTime),
367 + /** 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. */
368 + state: LinearWorkflowState,
369 + /** The team that the issue belongs to. Every issue must belong to exactly one team, which determines the available workflow states, labels, and other team-specific configuration. */
370 + team: IssueTeamTeam,
371 + /** The user who created the issue. Null if the creator's account has been deleted or if the issue was created by an integration or system process. */
372 + creator: Schema.NullOr(LinearUser),
373 + /** The bot that created the issue, if applicable. */
374 + botActor: Schema.NullOr(LinearBot),
375 + /** The user to whom the issue is assigned. Null if the issue is unassigned. */
376 + assignee: Schema.NullOr(LinearUser),
377 + /** Labels associated with this issue. */
378 + labels: LinearIssueLabelsIssueLabelConnection,
379 /** Comments associated with the issue, including inline comments on the issue's description. */
380 comments: CommentConnection,
381 /** Reactions associated with the issue. */
@@ -347,16 +395,16 @@ export const T3Issue = GraphQL.query("T3Issue", {
395 { name: "comments", body: "Int!" }
396 ],
397 selections: [
350 - { name: "issue", body: ["(id:$", "id", "){...LinearIssue comments(first:$", "comments", " orderBy:createdAt){nodes{...LinearComment}pageInfo{...LinearPageInfo}}reactions{...LinearReaction}attachments(first:50){nodes{url title sourceType metadata}}history(first:100 orderBy:createdAt){nodes{id createdAt actor{...LinearUser}botActor{...LinearBot}fromState{...LinearWorkflowState}toState{...LinearWorkflowState}fromAssignee{...LinearUser}toAssignee{...LinearUser}addedLabels{...LinearLabel}removedLabels{...LinearLabel}fromTitle toTitle}}}"] }
398 + { name: "issue", body: ["(id:$", "id", "){...LinearIssue team{states(first:100){nodes{...LinearWorkflowState}}}comments(first:$", "comments", " orderBy:createdAt){nodes{...LinearComment}pageInfo{...LinearPageInfo}}reactions{...LinearReaction}attachments(first:50){nodes{url title sourceType metadata}}history(first:100 orderBy:createdAt){nodes{id createdAt actor{...LinearUser}botActor{...LinearBot}fromState{...LinearWorkflowState}toState{...LinearWorkflowState}fromAssignee{...LinearUser}toAssignee{...LinearUser}addedLabels{...LinearLabel}removedLabels{...LinearLabel}fromTitle toTitle}}}"] }
399 ],
400 fragments: [
401 { 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}}}"] },
402 + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] },
403 { name: "LinearComment", body: ["on Comment{id body createdAt url user{...LinearUser}botActor{...LinearBot}reactions{...LinearReaction}}"] },
404 { name: "LinearPageInfo", body: ["on PageInfo{hasNextPage endCursor}"] },
405 { name: "LinearReaction", body: ["on Reaction{id emoji user{...LinearUser}}"] },
406 { name: "LinearUser", body: ["on User{id name displayName email avatarUrl}"] },
407 { name: "LinearBot", body: ["on ActorBot{name userDisplayName avatarUrl}"] },
359 - { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] },
408 { name: "LinearLabel", body: ["on IssueLabel{id name color}"] }
409 ]
410 },
@@ -415,11 +463,11 @@ export declare namespace T3Comments {
463 export type Result = typeof T3Comments.result.Type
464 }
465
418 -export const WorkflowStateConnection = Schema.Struct({
466 +export const NodesStatesWorkflowStateConnection = Schema.Struct({
467 nodes: Schema.Array(LinearWorkflowState),
468 pageInfo: LinearPageInfo
469 })
422 -export interface WorkflowStateConnection extends Schema.Struct.Type<typeof WorkflowStateConnection.fields> {}
470 +export interface NodesStatesWorkflowStateConnection extends Schema.Struct.Type<typeof NodesStatesWorkflowStateConnection.fields> {}
471
472 export const NodesLabelsIssueLabelConnection = Schema.Struct({
473 nodes: Schema.Array(LinearTeamLabel),
@@ -466,7 +514,7 @@ export const T3TeamTeamsNodesTeam = Schema.Struct({
514 /** The team's name. */
515 name: Schema.String,
516 /** The states that define the workflow associated with the team. */
469 - states: WorkflowStateConnection,
517 + states: NodesStatesWorkflowStateConnection,
518 /** Labels associated with the team. */
519 labels: NodesLabelsIssueLabelConnection,
520 /** Users who are members of this team. Supports filtering and pagination. */
packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts
+29 -10
@@ -42,7 +42,18 @@ const issue = (
42 completedAt: null,
43 canceledAt: null,
44 state: state("In Progress", "started"),
45 - team: { key: identifier.split("-")[0] },
45 + // The detail query also asks for the team's workflow; a listing ignores it.
46 + team: {
47 + key: identifier.split("-")[0],
48 + states: {
49 + nodes: [
50 + state("Canceled", "canceled", 3),
51 + state("Done", "completed", 2),
52 + state("In Progress", "started", 1),
53 + state("Todo", "unstarted", 0),
54 + ],
55 + },
56 + },
57 creator: JULIUS,
58 botActor: null,
59 assignee: THEO,
@@ -123,7 +134,7 @@ describe("LinearIssueTracker", () => {
134 T3Issues: (variables) => {
135 expect(variables.filter).toMatchObject({
136 team: { key: { eq: "ENG" } },
126 - state: { type: { nin: ["completed", "canceled"] } },
137 + state: { type: { nin: ["completed", "canceled", "duplicate"] } },
138 // "Assigned to me" survives an assignee filter: both must hold.
139 assignee: { displayName: { eq: "julius" } },
140 and: [
@@ -306,6 +317,13 @@ describe("LinearIssueTracker", () => {
317 const api = yield* tracker;
318 const detail = yield* api.getIssue({ ...target, key: "eng-7" });
319 expect(detail.viewer).toBe("julius");
320 + // The team's own workflow, in Linear's order, with the category each state falls in.
321 + expect(detail.states.map((entry) => [entry.name, entry.category])).toEqual([
322 + ["Todo", "open"],
323 + ["In Progress", "open"],
324 + ["Done", "closed"],
325 + ["Canceled", "closed"],
326 + ]);
327 expect(detail.commentsCursor).toBe("cmt_cur");
328 expect(detail.comments[0]?.reactions).toEqual([
329 { content: "thumbs-up", count: 1, actors: [], viewerHasReacted: true },
@@ -371,7 +389,7 @@ describe("LinearIssueTracker", () => {
389 );
390 const api = yield* tracker;
391 const unauthenticated = yield* Effect.flip(
374 - api.setState({ ...target, key: "ENG-1", state: "closed" }),
392 + api.setState({ ...target, key: "ENG-1", state: "Done" }),
393 );
394 expect(unauthenticated.reason).toBe("unauthenticated");
395
@@ -407,16 +425,17 @@ describe("LinearIssueTracker", () => {
425 });
426 const live = yield* connected.tracker;
427 // An identifier from another team resolves in Linear, so the team is checked before writing.
410 - const foreign = yield* Effect.flip(
411 - live.setState({ ...target, key: "OPS-3", state: "closed" }),
412 - );
428 + const foreign = yield* Effect.flip(live.setState({ ...target, key: "OPS-3", state: "Done" }));
429 expect(foreign.detail).toContain("OPS");
414 - yield* live.setState({ ...target, key: "ENG-1", state: "closed", closeReason: "canceled" });
415 - yield* live.setState({ ...target, key: "ENG-1", state: "closed" });
416 - yield* live.setState({ ...target, key: "ENG-1", state: "open" });
430 + // A move names one of the team's own states; nothing is asked for as "open" or "closed".
431 + yield* live.setState({ ...target, key: "ENG-1", state: "Canceled" });
432 + yield* live.setState({ ...target, key: "ENG-1", state: "Todo" });
433 + const unknown = yield* Effect.flip(
434 + live.setState({ ...target, key: "ENG-1", state: "closed" }),
435 + );
436 + expect(unknown.detail).toContain('no "closed" state');
437 expect(updates.map((update) => update.input)).toEqual([
438 { stateId: "st_canceled" },
419 - { stateId: "st_done" },
439 { stateId: "st_todo" },
440 ]);
441 }),
packages/issue-tracker-linear/src/server/LinearIssueTracker.ts
+24 -16
@@ -56,11 +56,6 @@ const CAPABILITIES: IssueCapabilities = {
56 linkedPullRequests: true,
57 events: true,
58 search: true,
59 - states: [
60 - { category: "open", name: "open" },
61 - { category: "closed", name: "closed" },
62 - ],
63 - closeReasons: ["completed", "canceled"],
59 };
60
61 /** Everything granted: Linear's API reports no per-issue permissions and refuses with a message. */
@@ -73,7 +68,27 @@ const VIEWER_PERMISSIONS: IssueViewerPermissions = {
68 };
69
70 const COMMENTS_PAGE = 50;
76 -const CLOSED_STATE_TYPES = ["completed", "canceled"];
71 +const CLOSED_STATE_TYPES = ["completed", "canceled", "duplicate"];
72 +/** The order Linear lists a workflow in; within a type, its own `position` decides. */
73 +const STATE_TYPE_ORDER = [
74 + "triage",
75 + "backlog",
76 + "unstarted",
77 + "started",
78 + "completed",
79 + "canceled",
80 + "duplicate",
81 +];
82 +
83 +function inWorkflowOrder(
84 + states: ReadonlyArray<LinearApi.LinearWorkflowState>,
85 +): ReadonlyArray<LinearApi.LinearWorkflowState> {
86 + return states.toSorted(
87 + (a, b) =>
88 + STATE_TYPE_ORDER.indexOf(a.type) - STATE_TYPE_ORDER.indexOf(b.type) ||
89 + (a.position ?? 0) - (b.position ?? 0),
90 + );
91 +}
92
93 /** Linear reacts with the emoji itself; GitHub's names are the contract's vocabulary. */
94 const EMOJI_BY_CONTENT: Record<IssueReactionContent, string> = {
@@ -484,6 +499,7 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
499 body: issue.description ?? "",
500 viewer: me === null ? null : toActor(me).login,
501 viewerPermissions: VIEWER_PERMISSIONS,
502 + states: inWorkflowOrder(issue.team.states.nodes).map(toState),
503 reactions: toReactions(issue.reactions, viewer),
504 comments: issue.comments.nodes.map((comment) => toComment(comment, viewer)),
505 commentsCursor: issue.comments.pageInfo.hasNextPage
@@ -546,17 +562,9 @@ export const make: Effect.Effect<StandaloneIssueTrackerApi, never, LinearApi.Lin
562 setState: Effect.fn("LinearIssueTracker.setState")(function* (input) {
563 const { identifier } = yield* requireTeamIssue("setState", input);
564 const scope = yield* requireTeam("setState", input.scope);
549 - const states = scope.team.states.nodes.toSorted(
550 - (a, b) => (a.position ?? 0) - (b.position ?? 0),
551 - );
552 - const wanted =
553 - input.state === "closed"
554 - ? states.find((state) => state.type === (input.closeReason ?? "completed"))
555 - : (states.find((state) => state.type === "unstarted") ??
556 - states.find((state) => state.type === "backlog") ??
557 - states.find((state) => state.type === "triage"));
565 + const wanted = scope.team.states.nodes.find((state) => state.name === input.state);
566 if (wanted === undefined)
559 - return yield* failed("setState", "This team has no workflow state for that change.");
567 + return yield* failed("setState", `This team's workflow has no "${input.state}" state.`);
568 yield* linear.updateIssue(identifier, { stateId: wanted.id });
569 }),
570
packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts
+43
@@ -24,6 +24,7 @@ const WORK_ITEM = {
24 "System.AssignedTo": "Theo <theo@acme.test>",
25 "System.Tags": "bug; ui; bug",
26 "System.TeamProject": "Web App",
27 + "System.WorkItemType": "Bug",
28 "System.CommentCount": 2,
29 "System.Description": "<p>Typing drops focus.</p>",
30 },
@@ -36,6 +37,8 @@ const WORK_ITEM = {
37 /** A custom process: "Shipped" is finished only because its category says so. */
38 const WORK_ITEM_TYPES = {
39 value: [
40 + // Another type's workflow, which a Bug cannot be moved through.
41 + { name: "Epic", states: [{ name: "Funded", category: "Proposed" }] },
42 {
43 name: "Bug",
44 states: [
@@ -163,6 +166,11 @@ describe("AzureDevOpsIssueTracker", () => {
166 url: "https://dev.azure.com/acme/Web%20App/_workitems/edit/7",
167 // The project's own state name survives; the category is what the list filters by.
168 state: { category: "closed", name: "Shipped" },
169 + // Its own type's workflow, in Azure's order, not the stock list or another type's.
170 + states: [
171 + { category: "open", name: "Active" },
172 + { category: "closed", name: "Shipped" },
173 + ],
174 author: { login: "octo@acme.test", name: "Octo Cat" },
175 assignees: [{ login: "Theo <theo@acme.test>" }],
176 labels: [
@@ -340,6 +348,9 @@ describe("AzureDevOpsIssueTracker", () => {
348 // `az` would send the contents of that file as the tag.
349 Effect.flip(api.update!({ ...own, labels: ["@/etc/hostname"] })),
350 Effect.flip(api.getIssue({ ...target, scope: "acme/@secrets" })),
351 + // A stock state and another type's state, neither in this Bug's custom workflow.
352 + Effect.flip(api.setState!({ ...own, state: "Closed" })),
353 + Effect.flip(api.setState!({ ...own, state: "Funded" })),
354 ]);
355 expect(refusals.map((error) => error.reason)).toEqual([
356 "not-found",
@@ -347,11 +358,43 @@ describe("AzureDevOpsIssueTracker", () => {
358 "failed",
359 "failed",
360 "failed",
361 + "failed",
362 + "failed",
363 ]);
364 expect(writes).toEqual([]);
365 }),
366 );
367
368 + it.effect("moves a work item to a state of its own type, custom ones included", () =>
369 + Effect.gen(function* () {
370 + const writes: string[][] = [];
371 + const api = yield* tracker((args) => {
372 + if (args[0] === "boards" && args[2] !== "show") writes.push([...args]);
373 + return answer(args);
374 + });
375 + const own = { cwd: "/w", host: "dev.azure.com", scope: "acme/Web App", key: "7" };
376 + yield* api.setState!({ ...own, state: "Shipped" });
377 + expect(writes.map((args) => args[args.indexOf("--state") + 1])).toEqual(["Shipped"]);
378 + // A type that reports no states falls back to the stock workflow, plus where the item is.
379 + const stock = yield* tracker((args) =>
380 + args[args.indexOf("--resource") + 1] === "workitemtypes"
381 + ? encode({ value: [{ name: "Bug" }] })
382 + : answer(args),
383 + );
384 + expect((yield* stock.getIssue(own)).states.map((state) => state.name)).toEqual([
385 + "New",
386 + "To Do",
387 + "Active",
388 + "Doing",
389 + "Resolved",
390 + "Done",
391 + "Closed",
392 + "Removed",
393 + "Shipped",
394 + ]);
395 + }),
396 + );
397 +
398 it.effect("sends text that starts with @ on stdin, where az reads no file for it", () =>
399 Effect.gen(function* () {
400 const writes: Array<{ args: string[]; stdin: string | undefined }> = [];
packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts
+32 -30
@@ -24,6 +24,7 @@ import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
24 import {
25 azureDevOpsReactionType,
26 closedStateNames,
27 + workItemStates,
28 decodeCommentsJson,
29 decodeProfileJson,
30 decodeUpdatesJson,
@@ -37,11 +38,6 @@ import { decodePullRequestJson } from "./azureDevOpsPullRequestJson.ts";
38
39 const KIND = IssueTrackerKind.make("azure-devops");
40
40 -/**
41 - * The states the stock Basic, Agile and Scrum processes carry, which is what a project that has
42 - * not customised its workflow can be moved between. A project with states of its own refuses a
43 - * name it lacks at write time, with Azure's own message.
44 - */
41 const CAPABILITIES: IssueCapabilities = {
42 create: true,
43 edit: true,
@@ -55,17 +51,6 @@ const CAPABILITIES: IssueCapabilities = {
51 linkedPullRequests: true,
52 events: true,
53 search: true,
58 - states: [
59 - { category: "open", name: "New" },
60 - { category: "open", name: "To Do" },
61 - { category: "open", name: "Active" },
62 - { category: "open", name: "Doing" },
63 - { category: "closed", name: "Resolved" },
64 - { category: "closed", name: "Done" },
65 - { category: "closed", name: "Closed" },
66 - { category: "closed", name: "Removed" },
67 - ],
68 - closeReasons: [],
54 };
55
56 /**
@@ -718,13 +703,14 @@ export const make: Effect.Effect<
703 getIssue: (input) =>
704 target("getIssue", input).pipe(
705 Effect.flatMap((scope) =>
721 - closedStates({ ...scope, cwd: input.cwd, operation: "getIssue" }).pipe(
722 - Effect.flatMap((closed) =>
723 - workItem({ ...scope, cwd: input.cwd, operation: "getIssue", closed }).pipe(
724 - Effect.map((item) => ({ item, closed })),
725 - ),
726 - ),
727 - Effect.flatMap(({ item, closed }) =>
706 + workItemTypes({ ...scope, cwd: input.cwd, operation: "getIssue" }).pipe(
707 + Effect.flatMap((types) => {
708 + const closed = closedStateNames(types);
709 + return workItem({ ...scope, cwd: input.cwd, operation: "getIssue", closed }).pipe(
710 + Effect.map((item) => ({ item, closed, states: workItemStates(types, item) })),
711 + );
712 + }),
713 + Effect.flatMap(({ item, closed, states }) =>
714 Effect.all(
715 [
716 comments({ ...scope, cwd: input.cwd, operation: "getIssue" }),
@@ -735,6 +721,9 @@ export const make: Effect.Effect<
721 ).pipe(
722 Effect.map(([conversation, events, links]) => ({
723 ...item,
724 + // Its type's own entry, so the category is the one that type gives the name.
725 + state: states.find((state) => state.name === item.state.name) ?? item.state,
726 + states,
727 // Nothing cheap names the viewer here; the service already read it per host.
728 viewer: null,
729 viewerPermissions: VIEWER_PERMISSIONS,
@@ -886,14 +875,27 @@ export const make: Effect.Effect<
875
876 setState: (input) =>
877 target("setState", input).pipe(
889 - Effect.flatMap((scope) => owned("setState", input.cwd, scope)),
878 + // The read also proves the item is the scope's own, as `owned` does for other writes.
879 Effect.flatMap((scope) =>
891 - update({
892 - ...scope,
893 - cwd: input.cwd,
894 - operation: "setState",
895 - args: ["--state", input.state],
896 - }),
880 + workItem({ ...scope, cwd: input.cwd, operation: "setState", closed: new Set() }).pipe(
881 + Effect.flatMap((item) =>
882 + workItemTypes({ ...scope, cwd: input.cwd, operation: "setState" }).pipe(
883 + Effect.map((types) => workItemStates(types, item)),
884 + ),
885 + ),
886 + Effect.filterOrFail(
887 + (states) => states.some((state) => state.name === input.state),
888 + () => refused("setState", `This work item has no "${input.state}" state.`),
889 + ),
890 + Effect.flatMap(() =>
891 + update({
892 + ...scope,
893 + cwd: input.cwd,
894 + operation: "setState",
895 + args: ["--state", input.state],
896 + }),
897 + ),
898 + ),
899 ),
900 ),
901
packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts
+41 -7
@@ -34,17 +34,28 @@ const STOCK_CLOSED_STATES: ClosedStates = new Set([
34
35 const FINISHED_CATEGORIES: ReadonlySet<string> = new Set(["Resolved", "Completed", "Removed"]);
36
37 +/** The stock Basic, Agile and Scrum states, for a work item whose type reports none. */
38 +const STOCK_STATES: ReadonlyArray<IssueState> = [
39 + { category: "open", name: "New" },
40 + { category: "open", name: "To Do" },
41 + { category: "open", name: "Active" },
42 + { category: "open", name: "Doing" },
43 + { category: "closed", name: "Resolved" },
44 + { category: "closed", name: "Done" },
45 + { category: "closed", name: "Closed" },
46 + { category: "closed", name: "Removed" },
47 +];
48 +
49 +type WorkItemTypes = ReadonlyArray<{
50 + readonly name: string;
51 + readonly states?: ReadonlyArray<{ readonly name: string; readonly category: string }> | undefined;
52 +}>;
53 +
54 /**
55 * A project's finished states, from its work item types' state categories. Custom processes
56 * name their own columns, so the category, not the name, says whether one is finished.
57 */
41 -export function closedStateNames(
42 - types: ReadonlyArray<{
43 - readonly states?:
44 - | ReadonlyArray<{ readonly name: string; readonly category: string }>
45 - | undefined;
46 - }>,
47 -): ClosedStates {
58 +export function closedStateNames(types: WorkItemTypes): ClosedStates {
59 const names = types.flatMap((type) =>
60 (type.states ?? []).flatMap((state) =>
61 FINISHED_CATEGORIES.has(state.category) ? [state.name.toLowerCase()] : [],
@@ -72,6 +83,7 @@ const Fields = Schema.Struct({
83 "System.Description": Schema.optional(Schema.NullOr(Schema.String)),
84 "System.Tags": Schema.optional(Schema.NullOr(Schema.String)),
85 "System.TeamProject": Schema.optional(Schema.NullOr(Schema.String)),
86 + "System.WorkItemType": Schema.optional(Schema.NullOr(Schema.String)),
87 "System.CreatedBy": Schema.optional(IdentityValue),
88 "System.AssignedTo": Schema.optional(IdentityValue),
89 });
@@ -151,6 +163,7 @@ function toLabels(tags: string | null | undefined): ReadonlyArray<IssueLabel> {
163 export interface AzureDevOpsWorkItem extends TrackerIssueSummary {
164 readonly body: string;
165 readonly project: string | null;
166 + readonly workItemType: string | null;
167 readonly relations: ReadonlyArray<typeof Relation.Type>;
168 }
169
@@ -181,10 +194,31 @@ function toWorkItem(raw: typeof WorkItem.Type, closed: ClosedStates): AzureDevOp
194 commentCount: Math.max(0, fields["System.CommentCount"] ?? 0),
195 body: fields["System.Description"] ?? "",
196 project,
197 + workItemType: trimmed(fields["System.WorkItemType"]),
198 relations: raw.relations ?? [],
199 };
200 }
201
202 +/**
203 + * The states a work item can be in: its own type's, in the order Azure lists them, which differ
204 + * per type and per process. The item's current state is always among them, even when the type
205 + * could not be read and the stock list stands in.
206 + */
207 +export function workItemStates(
208 + types: WorkItemTypes,
209 + item: Pick<AzureDevOpsWorkItem, "workItemType" | "state">,
210 +): ReadonlyArray<IssueState> {
211 + const type = types.find((entry) => entry.name.toLowerCase() === item.workItemType?.toLowerCase());
212 + const own = (type?.states ?? []).flatMap((state): ReadonlyArray<IssueState> => {
213 + const name = trimmed(state.name);
214 + return name === null
215 + ? []
216 + : [{ category: FINISHED_CATEGORIES.has(state.category) ? "closed" : "open", name }];
217 + });
218 + const states = own.length === 0 ? STOCK_STATES : own;
219 + return states.some((state) => state.name === item.state.name) ? states : [...states, item.state];
220 +}
221 +
222 /** The `{ count, value }` page `wit/workitems` answers; a row this cannot place is skipped. */
223 export function decodeWorkItemsJson(
224 raw: string,
packages/source-control-core/src/server/IssueTracker.ts
+8 -5
@@ -5,6 +5,7 @@
5 import * as Schema from "effect/Schema";
6 import type * as Effect from "effect/Effect";
7 import type {
8 + IssueState,
9 IssueCandidates,
10 IssueCapabilities,
11 IssueComment,
@@ -82,6 +83,8 @@ export interface TrackerIssueDetail extends TrackerIssueSummary {
83 readonly body: string;
84 readonly viewer: string | null;
85 readonly viewerPermissions: IssueViewerPermissions;
86 + /** Every state the issue can be in, in workflow order; `setState` is asked for one by name. */
87 + readonly states: ReadonlyArray<IssueState>;
88 readonly reactions?: ReadonlyArray<IssueReaction>;
89 readonly comments: ReadonlyArray<IssueComment>;
90 /** Where older comments carry on; null once the conversation is whole. */
@@ -154,12 +157,12 @@ export interface IssueTrackerApi {
157 },
158 ) => Effect.Effect<void, IssueTrackerError>;
159
157 - /** Only called with a state name from `capabilities.states`. */
160 + /**
161 + * Moves the issue to the state `getIssue` listed under that name, and refuses any other: the
162 + * name comes from a client, so the tracker is what proves it.
163 + */
164 readonly setState?: (
159 - input: IssueTarget & {
160 - readonly state: string;
161 - readonly closeReason?: string | undefined;
162 - },
165 + input: IssueTarget & { readonly state: string },
166 ) => Effect.Effect<void, IssueTrackerError>;
167
168 /**
packages/source-control-forgejo/src/server/ForgejoIssueTracker.test.ts
+25 -1
@@ -174,7 +174,11 @@ describe("ForgejoIssueTracker", () => {
174 expect(issue).toMatchObject({
175 key: "42",
176 displayKey: "#42",
177 - state: { category: "open", name: "open" },
177 + state: { category: "open", name: "Open" },
178 + states: [
179 + { category: "open", name: "Open" },
180 + { category: "closed", name: "Closed" },
181 + ],
182 author: { login: "octocat", name: "Octo Cat", avatarUrl: null },
183 createdAt: "2026-06-30T22:00:00.000Z",
184 labels: [{ name: "bug", color: "d73a4a" }],
@@ -280,6 +284,26 @@ describe("ForgejoIssueTracker", () => {
284 }),
285 );
286
287 + it.effect("moves an issue to a state by its name and refuses any other name", () =>
288 + Effect.gen(function* () {
289 + const writes: unknown[] = [];
290 + const api = yield* tracker((input) => {
291 + writes.push([input.method, input.path, input.body]);
292 + return { stdout: "{}" };
293 + });
294 + const target = { cwd: "/w", host: "forgejo.test:3000", scope: "acme/web", key: "42" };
295 + yield* api.setState!({ ...target, state: "Closed" });
296 + yield* api.setState!({ ...target, state: "Open" });
297 + // The category is not a state name: nothing is sent for it.
298 + const error = yield* Effect.flip(api.setState!({ ...target, state: "closed" }));
299 + expect(error).toMatchObject({ operation: "setState", reason: "failed" });
300 + expect(writes).toEqual([
301 + ["PATCH", "repos/acme/web/issues/42", { state: "closed" }],
302 + ["PATCH", "repos/acme/web/issues/42", { state: "open" }],
303 + ]);
304 + }),
305 + );
306 +
307 it.effect("lists issues by page and leaves pull requests out of the rows", () =>
308 Effect.gen(function* () {
309 const paths: string[] = [];
packages/source-control-forgejo/src/server/ForgejoIssueTracker.ts
+11 -9
@@ -25,6 +25,7 @@ import {
25 ForgejoIssueRepository,
26 ForgejoIssueTemplate,
27 ForgejoTimelineEntry,
28 + ISSUE_STATES,
29 forgejoIssue,
30 forgejoIssueComment,
31 forgejoIssueEvent,
@@ -53,11 +54,6 @@ const CAPABILITIES: IssueCapabilities = {
54 linkedPullRequests: true,
55 events: true,
56 search: true,
56 - states: [
57 - { category: "open", name: "open" },
58 - { category: "closed", name: "closed" },
59 - ],
60 - closeReasons: [],
57 };
58
59 /** Forgejo's own ceiling on a page, which a self-hosted server may lower. */
@@ -464,6 +460,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
460 body: issue.body ?? "",
461 viewer,
462 viewerPermissions: permissions(repository, issue, viewer),
463 + states: ISSUE_STATES,
464 reactions: forgejoReactions(reactions, viewer),
465 comments: conversation.comments,
466 commentsCursor: conversation.nextCursor,
@@ -553,12 +550,17 @@ export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli>
550 Effect.asVoid,
551 ),
552
556 - setState: (input) =>
557 - issueTarget("setState", input).pipe(
553 + setState: (input) => {
554 + const wanted = ISSUE_STATES.find((state) => state.name === input.state);
555 + if (wanted === undefined) {
556 + return Effect.fail(refused("setState", `A Forgejo issue has no "${input.state}" state.`));
557 + }
558 + return issueTarget("setState", input).pipe(
559 Effect.flatMap(({ path }) =>
559 - write(input, "setState", { path, method: "PATCH", body: { state: input.state } }),
560 + write(input, "setState", { path, method: "PATCH", body: { state: wanted.category } }),
561 ),
561 - ),
562 + );
563 + },
564
565 setReaction: (input) =>
566 issueTarget("setReaction", input).pipe(
packages/source-control-forgejo/src/server/forgejoIssueJson.ts
+8 -5
@@ -7,7 +7,7 @@
7 import * as DateTime from "effect/DateTime";
8 import * as Option from "effect/Option";
9 import * as Schema from "effect/Schema";
10 -import type { IssueComment, IssueEvent, IssueTemplate } from "@t3tools/contracts";
10 +import type { IssueComment, IssueEvent, IssueState, IssueTemplate } from "@t3tools/contracts";
11 import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
12
13 import {
@@ -84,6 +84,12 @@ function toIsoUtc(value: string): string {
84 return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso });
85 }
86
87 +const OPEN: IssueState = { category: "open", name: "Open" };
88 +const CLOSED: IssueState = { category: "closed", name: "Closed" };
89 +
90 +/** Forgejo has exactly the two states and records no reason for a close. */
91 +export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
92 +
93 export function forgejoIssue(issue: typeof ForgejoIssue.Type): TrackerIssueSummary {
94 return {
95 key: String(issue.number),
@@ -91,10 +97,7 @@ export function forgejoIssue(issue: typeof ForgejoIssue.Type): TrackerIssueSumma
97 title: issue.title,
98 url: issue.html_url,
99 author: forgejoActor(issue.user),
94 - state:
95 - issue.state === "closed"
96 - ? { category: "closed", name: "closed" }
97 - : { category: "open", name: "open" },
100 + state: issue.state === "closed" ? CLOSED : OPEN,
101 createdAt: toIsoUtc(issue.created_at),
102 updatedAt: toIsoUtc(issue.updated_at),
103 closedAt: issue.closed_at ? toIsoUtc(issue.closed_at) : null,
packages/source-control-github/src/server/GitHubIssueTracker.test.ts
+23 -7
@@ -306,14 +306,18 @@ describe("GitHubIssueTracker", () => {
306 yield* Effect.flip(api.update({ ...target, title: "Dropped", labels: ["bug", "p1"] })),
307 ).toMatchObject({ operation: "update", reason: "failed" });
308 yield* api.update({ ...target, title: "Dropped", labels: ["bug"], assignees: [] });
309 - yield* api.setState({ ...target, state: "closed", closeReason: "not-planned" });
309 + expect(yield* Effect.flip(api.setState({ ...target, state: "closed" }))).toMatchObject({
310 + operation: "setState",
311 + reason: "failed",
312 + });
313 + yield* api.setState({ ...target, state: "Not planned" });
314 // GitHub ignores a new reason on a closed issue, so it is refused instead of sent.
315 expect(
312 - yield* api
313 - .setState({ ...target, state: "closed", closeReason: "completed" })
314 - .pipe(Effect.result),
316 + yield* api.setState({ ...target, state: "Completed" }).pipe(Effect.result),
317 ).toMatchObject({ _tag: "Failure", failure: { operation: "setState", reason: "failed" } });
316 - yield* api.setState({ ...target, state: "open" });
318 + yield* api.setState({ ...target, state: "Open" });
319 + yield* api.setState({ ...target, state: "Duplicate" });
320 + yield* api.setState({ ...target, state: "Open" });
321 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: true });
322 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: false });
323
@@ -322,7 +326,7 @@ describe("GitHubIssueTracker", () => {
326 yield* api.update({ ...pullRequest, title: "Do not edit" }).pipe(Effect.result),
327 ).toMatchObject({ _tag: "Failure", failure: { operation: "update", reason: "not-found" } });
328 expect(
325 - yield* api.setState({ ...pullRequest, state: "closed" }).pipe(Effect.result),
329 + yield* api.setState({ ...pullRequest, state: "Completed" }).pipe(Effect.result),
330 ).toMatchObject({
331 _tag: "Failure",
332 failure: { operation: "setState", reason: "not-found" },
@@ -369,6 +373,12 @@ describe("GitHubIssueTracker", () => {
373 { state: "closed", state_reason: "not_planned" },
374 ],
375 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
376 + [
377 + "PATCH",
378 + "https://api.github.com/repos/acme/web/issues/42",
379 + { state: "closed", state_reason: "duplicate" },
380 + ],
381 + ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
382 "AddReaction",
383 "RemoveReaction",
384 ]);
@@ -547,7 +557,13 @@ Redact secrets before uploading.`);
557 displayKey: "#42",
558 title: "Composer loses focus",
559 body: "Typing in the composer drops focus after a paste.",
550 - state: { category: "closed", name: "closed", closeReason: "duplicate" },
560 + state: { category: "closed", name: "Duplicate", closeReason: "duplicate" },
561 + states: [
562 + { category: "open", name: "Open" },
563 + { category: "closed", name: "Completed", closeReason: "completed" },
564 + { category: "closed", name: "Not planned", closeReason: "not-planned" },
565 + { category: "closed", name: "Duplicate", closeReason: "duplicate" },
566 + ],
567 author: {
568 login: "octocat",
569 name: "Octo Cat",
packages/source-control-github/src/server/GitHubIssueTracker.ts
+10 -15
@@ -20,6 +20,7 @@ import { IssuesGraphQLGroup } from "./issues.graphql.ts";
20 import { AddReaction, RemoveReaction } from "./pullRequestMutations.graphql.ts";
21 import { gitHubReactionContent } from "./gitHubPullRequestJson.ts";
22 import {
23 + ISSUE_STATES,
24 decodeCreatedIssueJson,
25 decodeIssueMetadataJson,
26 toIssueCandidates,
@@ -41,11 +42,6 @@ const CAPABILITIES: IssueCapabilities = {
42 linkedPullRequests: true,
43 events: true,
44 search: true,
44 - states: [
45 - { category: "open", name: "open" },
46 - { category: "closed", name: "closed" },
47 - ],
48 - closeReasons: ["completed", "not-planned"],
45 };
46
47 const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/;
@@ -92,11 +88,6 @@ function searchQuery(input: {
88 ].join(" ");
89 }
90
95 -const CLOSE_REASON: Record<string, "completed" | "not_planned"> = {
96 - completed: "completed",
97 - "not-planned": "not_planned",
98 -};
99 -
91 function reasonFor(
92 error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError,
93 ): IssueTrackerError["reason"] {
@@ -390,10 +381,11 @@ export const make = Effect.gen(function* () {
381
382 setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
383 const { path, state, stateReason } = yield* verifiedIssue(input, "setState");
393 - const reason =
394 - input.state === "closed" && input.closeReason !== undefined
395 - ? CLOSE_REASON[input.closeReason]
396 - : undefined;
384 + const wanted = ISSUE_STATES.find((candidate) => candidate.name === input.state);
385 + if (wanted === undefined) {
386 + return yield* invalid("setState", `A GitHub issue has no "${input.state}" state.`);
387 + }
388 + const reason = wanted.closeReason?.replace("-", "_");
389 // GitHub ignores `state_reason` unless the state changes, and would answer with success.
390 if (reason !== undefined && state === "CLOSED" && stateReason?.toLowerCase() !== reason) {
391 return yield* invalid(
@@ -407,7 +399,10 @@ export const make = Effect.gen(function* () {
399 operation: "setState",
400 method: "PATCH",
401 path,
410 - body: { state: input.state, ...(reason === undefined ? {} : { state_reason: reason }) },
402 + body: {
403 + state: wanted.category,
404 + ...(reason === undefined ? {} : { state_reason: reason }),
405 + },
406 })
407 .pipe(Effect.mapError(fail("setState")));
408 }),
packages/source-control-github/src/server/gitHubIssueJson.ts
+23 -12
@@ -59,24 +59,33 @@ function toLabels(raw: ReadonlyArray<Label | null> | null | undefined): Readonly
59 });
60 }
61
62 +const OPEN: IssueState = { category: "open", name: "Open" };
63 +const COMPLETED: IssueState = {
64 + category: "closed",
65 + name: "Completed",
66 + closeReason: "completed",
67 +};
68 +const NOT_PLANNED: IssueState = {
69 + category: "closed",
70 + name: "Not planned",
71 + closeReason: "not-planned",
72 +};
73 +
74 +const DUPLICATE: IssueState = { category: "closed", name: "Duplicate", closeReason: "duplicate" };
75 +
76 +/** What an issue can be moved to: open, or closed for one of the reasons GitHub records. */
77 +export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, COMPLETED, NOT_PLANNED, DUPLICATE];
78 +
79 /** GitHub uses uppercase close reasons; an open issue has `""` or `REOPENED`. */
80 function toIssueState(
81 state: string | null | undefined,
82 stateReason: string | null | undefined,
83 ): IssueState {
67 - if (state?.trim().toUpperCase() !== "CLOSED") return { category: "open", name: "open" };
84 + if (state?.trim().toUpperCase() !== "CLOSED") return OPEN;
85 const reason = stateReason?.trim().toUpperCase();
69 - return {
70 - category: "closed",
71 - name: "closed",
72 - ...(reason === "COMPLETED"
73 - ? { closeReason: "completed" }
74 - : reason === "NOT_PLANNED"
75 - ? { closeReason: "not-planned" }
76 - : reason === "DUPLICATE"
77 - ? { closeReason: "duplicate" }
78 - : {}),
79 - };
86 + if (reason === "COMPLETED") return COMPLETED;
87 + if (reason === "NOT_PLANNED") return NOT_PLANNED;
88 + return reason === "DUPLICATE" ? DUPLICATE : { category: "closed", name: "Closed" };
89 }
90
91 function toSummary(raw: Omit<Issues.NodesIssue, "__typename">): TrackerIssueSummary {
@@ -226,6 +235,7 @@ interface GitHubIssueDetail extends TrackerIssueSummary {
235 readonly body: string;
236 readonly viewer: string | null;
237 readonly viewerPermissions: IssueViewerPermissions;
238 + readonly states: ReadonlyArray<IssueState>;
239 readonly reactions: ReturnType<typeof toReactions>;
240 readonly comments: ReadonlyArray<IssueComment>;
241 readonly commentsCursor: string | null;
@@ -272,6 +282,7 @@ export function toIssueDetail({
282 viewerPermission: repository?.viewerPermission,
283 issue,
284 }),
285 + states: ISSUE_STATES,
286 reactions: toReactions(issue.reactionGroups, viewer),
287 comments: toComments(issue.comments, viewer),
288 commentsCursor: previousCursorOf(issue.comments?.pageInfo),
packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts
+25 -1
@@ -158,7 +158,11 @@ describe("GitLabIssueTracker", () => {
158 expect(issue).toMatchObject({
159 key: "42",
160 displayKey: "#42",
161 - state: { category: "closed", name: "closed" },
161 + state: { category: "closed", name: "Closed" },
162 + states: [
163 + { category: "open", name: "Open" },
164 + { category: "closed", name: "Closed" },
165 + ],
166 author: { login: "octocat", name: "Octo Cat" },
167 assignees: [{ login: "theo" }],
168 labels: [{ name: "bug", color: null }],
@@ -287,6 +291,26 @@ describe("GitLabIssueTracker", () => {
291 }),
292 );
293
294 + it.effect("moves an issue to a state by its name and refuses any other name", () =>
295 + Effect.gen(function* () {
296 + const writes: unknown[] = [];
297 + const api = yield* tracker((args, input) => {
298 + writes.push([args[1], JSON.parse(input.stdin ?? "null")]);
299 + return "{}";
300 + });
301 + const target = { cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "42" };
302 + yield* api.setState!({ ...target, state: "Closed" });
303 + yield* api.setState!({ ...target, state: "Open" });
304 + // The category is not a state name: nothing is sent for it.
305 + const error = yield* Effect.flip(api.setState!({ ...target, state: "closed" }));
306 + expect(error).toMatchObject({ operation: "setState", reason: "failed" });
307 + expect(writes).toEqual([
308 + ["projects/acme%2Fweb/issues/42", { state_event: "close" }],
309 + ["projects/acme%2Fweb/issues/42", { state_event: "reopen" }],
310 + ]);
311 + }),
312 + );
313 +
314 it.effect("refuses a key that names no GitLab issue without a request", () =>
315 Effect.gen(function* () {
316 let requests = 0;
packages/source-control-gitlab/src/server/GitLabIssueTracker.ts
+11 -10
@@ -31,6 +31,7 @@ import {
31 decodeTemplateEntriesJson,
32 decodeTemplateJson,
33 ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
34 + ISSUE_STATES,
35 PAGE_SIZE,
36 type GitLabTemplateEntry,
37 } from "./gitLabIssueJson.ts";
@@ -54,12 +55,6 @@ const CAPABILITIES: IssueCapabilities = {
55 linkedPullRequests: true,
56 events: true,
57 search: true,
57 - states: [
58 - { category: "open", name: "open" },
59 - { category: "closed", name: "closed" },
60 - ],
61 - // GitLab records nothing about why an issue was closed.
62 - closeReasons: [],
58 };
59
60 /**
@@ -480,6 +475,7 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
475 ...issue,
476 viewer: viewerLogin,
477 viewerPermissions: VIEWER_PERMISSIONS,
478 + states: ISSUE_STATES,
479 reactions: awardPage.reactions,
480 comments: notes.comments.map((comment) => ({
481 ...comment,
@@ -601,8 +597,12 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
597 ),
598 ),
599
604 - setState: (input) =>
605 - issuePath(input, "setState").pipe(
600 + setState: (input) => {
601 + const wanted = ISSUE_STATES.find((state) => state.name === input.state);
602 + if (wanted === undefined) {
603 + return Effect.fail(refused("setState", `A GitLab issue has no "${input.state}" state.`));
604 + }
605 + return issuePath(input, "setState").pipe(
606 Effect.flatMap(({ path }) =>
607 write({
608 cwd: input.cwd,
@@ -610,10 +610,11 @@ export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> =
610 operation: "setState",
611 path,
612 method: "PUT",
613 - body: { state_event: input.state === "closed" ? "close" : "reopen" },
613 + body: { state_event: wanted.category === "closed" ? "close" : "reopen" },
614 }),
615 ),
616 - ),
616 + );
617 + },
618
619 setReaction: Effect.fn("GitLabIssueTracker.setReaction")(function* (input) {
620 const { path } = yield* issuePath(input, "setReaction");
packages/source-control-gitlab/src/server/gitLabIssueJson.ts
+9 -5
@@ -17,6 +17,7 @@ import type {
17 IssueLabel,
18 IssueLabelCandidate,
19 IssueLinkedPullRequest,
20 + IssueState,
21 IssueTemplate,
22 PullRequestState,
23 } from "@t3tools/contracts";
@@ -128,6 +129,12 @@ function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<
129 });
130 }
131
132 +const OPEN: IssueState = { category: "open", name: "Open" };
133 +const CLOSED: IssueState = { category: "closed", name: "Closed" };
134 +
135 +/** GitLab has exactly the two states and records no reason for a close. */
136 +export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
137 +
138 function toSummary(raw: typeof RawIssueSchema.Type): TrackerIssueSummary {
139 return {
140 key: String(raw.iid),
@@ -135,11 +142,8 @@ function toSummary(raw: typeof RawIssueSchema.Type): TrackerIssueSummary {
142 title: raw.title,
143 url: raw.web_url,
144 author: toActor(raw.author),
138 - // GitLab has exactly the two states, calls the open one `opened`, and records no reason.
139 - state:
140 - raw.state?.trim().toLowerCase() === "closed"
141 - ? { category: "closed", name: "closed" }
142 - : { category: "open", name: "open" },
145 + // GitLab calls the open one `opened`.
146 + state: raw.state?.trim().toLowerCase() === "closed" ? CLOSED : OPEN,
147 createdAt: raw.created_at,
148 updatedAt: raw.updated_at,
149 closedAt: trimmed(raw.closed_at),