@omercnet/paseo-pr-radar 3.2.3 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/radar.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { usePaseo } from "@getpaseo/plugin/client";
2
2
  import { z } from "zod";
3
- import { type GitHubInboxItem, HttpsUrlSchema } from "../shared/viewer-scope";
3
+ import type { CwdMode } from "../shared/settings";
4
+ import { type GitHubInboxItem, type GitHubIssueItem, HttpsUrlSchema } from "../shared/viewer-scope";
4
5
 
5
6
  export type PaseoApi = ReturnType<typeof usePaseo>;
6
7
  export type PaseoWorkspace = Awaited<ReturnType<PaseoApi["workspaces"]["list"]>>["entries"][number];
@@ -49,8 +50,11 @@ export interface RadarCheck {
49
50
  }
50
51
 
51
52
  export type ViewerOwnership = "mine" | "external" | "unknown";
53
+ export type CwdTag = "CWD-BASE" | "CWD-WORKTREE" | "CWD-TBD";
52
54
 
53
55
  export interface RadarRow {
56
+ itemKind?: "pr" | "issue";
57
+ issueRole?: GitHubIssueItem["role"];
54
58
  id: string;
55
59
  number: number | null;
56
60
  url: string;
@@ -65,6 +69,9 @@ export interface RadarRow {
65
69
  comments: number;
66
70
  labels: string[];
67
71
  changes: string[];
72
+ linkedIssues: string[];
73
+ cwdTag: CwdTag;
74
+ hasLocalPlace: boolean;
68
75
  mergeable: "UNKNOWN" | "MERGEABLE" | "CONFLICTING";
69
76
  mergeStateStatus: string | null;
70
77
  checksStatus: "success" | "pending" | "none" | "failure";
@@ -88,12 +95,20 @@ export interface RadarWarning {
88
95
  message: string;
89
96
  }
90
97
 
98
+ export interface RadarIssueMatch {
99
+ workspaceIds: string[];
100
+ workspaceNames: string[];
101
+ agents: RadarAgent[];
102
+ cwdTag: CwdTag;
103
+ }
104
+
91
105
  export interface RadarSnapshot {
92
106
  rows: RadarRow[];
93
107
  warnings: RadarWarning[];
94
108
  workspaceCount: number;
95
109
  refreshedAt: string;
96
110
  repositoryRoots: Record<string, string>;
111
+ issueMatches?: Record<string, RadarIssueMatch>;
97
112
  }
98
113
 
99
114
  export interface ViewerScopeData {
@@ -217,15 +232,16 @@ function externalWaitingReason(row: RadarRow): string {
217
232
  return "External pull request";
218
233
  }
219
234
 
235
+ function hasFailedAgent(agents: readonly RadarAgent[]): boolean {
236
+ return agents.some((agent) => agent.status === "error" || agent.attentionReason === "error");
237
+ }
238
+
220
239
  export function classifyRow(row: RadarRow): Pick<RadarRow, "bucket" | "reason"> {
221
240
  const humanBlocker = attentionReason(row.agents);
222
241
  if (humanBlocker) return { bucket: "needs-you", reason: humanBlocker };
223
242
 
224
243
  const activeAgent = hasActiveAgent(row.agents);
225
- if (
226
- !activeAgent &&
227
- row.agents.some((agent) => agent.status === "error" || agent.attentionReason === "error")
228
- ) {
244
+ if (!activeAgent && hasFailedAgent(row.agents)) {
229
245
  return { bucket: "needs-you", reason: "Agent failed" };
230
246
  }
231
247
  if (activeAgent && row.ownership !== "mine") {
@@ -321,6 +337,9 @@ export function agentActionFor(row: RadarRow): RadarAgentAction {
321
337
  }
322
338
 
323
339
  export function buildAgentPrompt(row: RadarRow): string {
340
+ if (row.itemKind === "issue") {
341
+ return `Investigate and address GitHub issue ${row.url} (${row.title}). Inspect the repository, implement a fix or plan, run relevant validation, and report the result.`;
342
+ }
324
343
  if (row.reviewRequestedFromMe) {
325
344
  return `Review ${row.url}. CI is complete and GitHub is requesting your review. Inspect the changes, follow the repository review workflow, submit the review when justified, and report the result.`;
326
345
  }
@@ -355,6 +374,7 @@ export function buildRadarSnapshot(
355
374
  const rows = new Map<string, RadarRow>();
356
375
  const warnings: RadarWarning[] = [];
357
376
  const repositoryRoots: Record<string, string> = {};
377
+ const issueMatches: Record<string, RadarIssueMatch> = {};
358
378
 
359
379
  for (const workspace of workspaces) {
360
380
  const remoteRepository = workspace.gitRuntime?.remoteUrl
@@ -362,6 +382,37 @@ export function buildRadarSnapshot(
362
382
  : null;
363
383
  if (remoteRepository) {
364
384
  repositoryRoots[remoteRepository.toLowerCase()] ??= workspace.projectRootPath;
385
+ const issueBranchMatch =
386
+ workspace.gitRuntime?.currentBranch?.match(/^pr-radar\/issue-(\d+)$/);
387
+ if (issueBranchMatch) {
388
+ const issueKey = `${remoteRepository.toLowerCase()}#issue-${issueBranchMatch[1]}`;
389
+ const wsAgents = agentsByWorkspace.get(workspace.id) ?? [];
390
+ const wsLabels = (workspace as { labels?: readonly string[] }).labels;
391
+ const wsCwdTag: CwdTag = wsLabels?.includes("CWD-BASE")
392
+ ? "CWD-BASE"
393
+ : wsLabels?.includes("CWD-WORKTREE")
394
+ ? "CWD-WORKTREE"
395
+ : "CWD-TBD";
396
+ const current = issueMatches[issueKey] ?? {
397
+ workspaceIds: [],
398
+ workspaceNames: [],
399
+ agents: [],
400
+ cwdTag: "CWD-TBD" as CwdTag,
401
+ };
402
+ if (!current.workspaceIds.includes(workspace.id)) {
403
+ current.workspaceIds.push(workspace.id);
404
+ current.workspaceNames.push(workspace.name);
405
+ }
406
+ const knownIds = new Set(current.agents.map((a) => a.id));
407
+ for (const a of wsAgents) {
408
+ if (!knownIds.has(a.id)) current.agents.push(a);
409
+ }
410
+ sortAgents(current.agents);
411
+ if (current.cwdTag === "CWD-TBD" && wsCwdTag !== "CWD-TBD") {
412
+ current.cwdTag = wsCwdTag;
413
+ }
414
+ issueMatches[issueKey] = current;
415
+ }
365
416
  }
366
417
  const runtime = workspace.githubRuntime;
367
418
  if (runtime?.error?.message) {
@@ -409,6 +460,14 @@ export function buildRadarSnapshot(
409
460
  continue;
410
461
  }
411
462
 
463
+ const workspaceCwdTag: CwdTag = workspace.labels?.includes("CWD-BASE")
464
+ ? "CWD-BASE"
465
+ : workspace.labels?.includes("CWD-WORKTREE")
466
+ ? "CWD-WORKTREE"
467
+ : workspace.workspaceKind === "worktree"
468
+ ? "CWD-WORKTREE"
469
+ : "CWD-BASE";
470
+
412
471
  const row: RadarRow = {
413
472
  id,
414
473
  number: pullRequest.number ?? null,
@@ -424,6 +483,9 @@ export function buildRadarSnapshot(
424
483
  comments: 0,
425
484
  labels: [],
426
485
  changes: [],
486
+ linkedIssues: [],
487
+ cwdTag: workspaceCwdTag,
488
+ hasLocalPlace: true,
427
489
  mergeable: pullRequest.mergeable ?? "UNKNOWN",
428
490
  mergeStateStatus: facts?.mergeStateStatus ?? null,
429
491
  checksStatus: pullRequest.checksStatus ?? "none",
@@ -460,6 +522,7 @@ export function buildRadarSnapshot(
460
522
  workspaceCount: workspaces.length,
461
523
  refreshedAt: now.toISOString(),
462
524
  repositoryRoots,
525
+ issueMatches,
463
526
  };
464
527
  }
465
528
 
@@ -480,6 +543,7 @@ export function mergeInboxRows(
480
543
  existing.comments = item.comments;
481
544
  existing.labels = [...item.labels];
482
545
  existing.changes = [...item.changes];
546
+ existing.linkedIssues = [...item.linkedIssues];
483
547
  existing.isDraft = item.isDraft;
484
548
  existing.baseRefName = item.baseRefName || existing.baseRefName;
485
549
  existing.headRefName = item.headRefName || existing.headRefName;
@@ -490,6 +554,8 @@ export function mergeInboxRows(
490
554
  existing.ownership = item.role === "author" ? "mine" : "external";
491
555
  existing.reviewRequestedFromMe = item.role === "reviewer";
492
556
  existing.localProjectRoot ??= snapshot.repositoryRoots[item.repository.toLowerCase()] ?? null;
557
+ existing.hasLocalPlace =
558
+ existing.workspaceIds.length > 0 || Boolean(existing.localProjectRoot);
493
559
  if (Date.parse(item.updatedAt) > Date.parse(existing.activityAt ?? "")) {
494
560
  existing.activityAt = item.updatedAt;
495
561
  }
@@ -514,6 +580,9 @@ export function mergeInboxRows(
514
580
  comments: item.comments,
515
581
  labels: [...item.labels],
516
582
  changes: [...item.changes],
583
+ linkedIssues: [...item.linkedIssues],
584
+ cwdTag: "CWD-TBD",
585
+ hasLocalPlace: Boolean(snapshot.repositoryRoots[item.repository.toLowerCase()]),
517
586
  mergeable: item.mergeable,
518
587
  mergeStateStatus: item.mergeStateStatus,
519
588
  checksStatus: item.checksStatus,
@@ -703,3 +772,255 @@ export function profileAgentConfig(profile: AgentProfileLike) {
703
772
  : {}),
704
773
  };
705
774
  }
775
+
776
+ /**
777
+ * The provider and model a routing result sets. A routed provider that differs from the current
778
+ * one without a routed model drops the model, which belonged to the old provider (it would
779
+ * otherwise build an id such as `codex/<claude model>`). If the caller refuses a routed provider
780
+ * because the user edited it, a routed model is applied only when it belongs to the current
781
+ * provider.
782
+ */
783
+ export function routedProviderModel(
784
+ current: { provider?: string },
785
+ routed: { provider?: string; model?: string },
786
+ options: { applyProvider?: boolean } = {},
787
+ ): { provider?: string; model?: string } {
788
+ const result: { provider?: string; model?: string } = {};
789
+ const applyProvider = options.applyProvider ?? true;
790
+ const providerApplied = Boolean(routed.provider && applyProvider);
791
+ if (providerApplied) result.provider = routed.provider;
792
+ if (routed.model) {
793
+ const modelMatchesCurrentProvider = !routed.provider || routed.provider === current.provider;
794
+ if (providerApplied || modelMatchesCurrentProvider) result.model = routed.model;
795
+ } else if (providerApplied && routed.provider !== current.provider) result.model = "";
796
+ return result;
797
+ }
798
+
799
+ /** Cloning is never preselected: the user has to pick the clone row to allow it. */
800
+ export function initialLaunchTarget(row: Pick<RadarRow, "localProjectRoot">) {
801
+ return { selectedDir: row.localProjectRoot ?? null, allowClone: false };
802
+ }
803
+
804
+ export interface RoutingLaunchState {
805
+ selectedDir: string | null;
806
+ cwdMode: CwdMode;
807
+ provider: string;
808
+ }
809
+
810
+ export function automaticRoutingLaunchState(
811
+ row: Pick<RadarRow, "localProjectRoot">,
812
+ current: RoutingLaunchState,
813
+ defaults: Pick<RoutingLaunchState, "cwdMode" | "provider">,
814
+ isNewRow: boolean,
815
+ ): RoutingLaunchState {
816
+ if (!isNewRow) return current;
817
+ const target = initialLaunchTarget(row);
818
+ return {
819
+ selectedDir: target.selectedDir,
820
+ cwdMode: defaults.cwdMode,
821
+ provider: defaults.provider,
822
+ };
823
+ }
824
+
825
+ export function autoLaunchRequiresModal(
826
+ settings: {
827
+ autoLaunchMode: "disabled" | "prompt" | "existing_only" | "existing_or_clone";
828
+ defaultCwdMode: CwdTag;
829
+ },
830
+ row: Pick<RadarRow, "hasLocalPlace">,
831
+ ): boolean {
832
+ const shouldAutoLaunch =
833
+ settings.autoLaunchMode === "existing_or_clone" ||
834
+ (settings.autoLaunchMode === "existing_only" && row.hasLocalPlace);
835
+ return !shouldAutoLaunch || settings.defaultCwdMode === "CWD-BASE";
836
+ }
837
+
838
+ const CWD_TAGS: readonly CwdTag[] = ["CWD-BASE", "CWD-WORKTREE", "CWD-TBD"];
839
+
840
+ interface LabelableWorkspace {
841
+ // Workspaces before Paseo 0.16.0-beta.1 have no setLabel.
842
+ setLabel?(label: string, options: { assigned: boolean }): unknown;
843
+ }
844
+
845
+ /** Marks exactly one CWD tag on the workspace; a host without label support is left unlabelled. */
846
+ export async function labelWorkspaceCwd(
847
+ workspace: LabelableWorkspace,
848
+ cwdTag: CwdTag,
849
+ ): Promise<void> {
850
+ if (typeof workspace.setLabel !== "function") return;
851
+ await Promise.all(CWD_TAGS.map((tag) => workspace.setLabel?.(tag, { assigned: tag === cwdTag })));
852
+ }
853
+
854
+ // A routing script is user-supplied code, so what it may set on a launch is limited to these lists.
855
+ // Permission modes that skip approvals (bypassPermissions, dontAsk, full access) stay out, so only
856
+ // a person can pick them. Provider `options` keys outside the list are dropped the same way.
857
+ export const ROUTED_MODE_IDS: readonly string[] = ["default", "plan", "acceptEdits", "read-only"];
858
+ export const ROUTED_OPTION_KEYS: readonly string[] = ["contextMode"];
859
+
860
+ export interface RestrictedRouting {
861
+ modeId?: string;
862
+ options?: Record<string, unknown>;
863
+ ignored: string[];
864
+ }
865
+
866
+ export function restrictRoutedLaunch(routed: {
867
+ modeId?: string;
868
+ options?: Record<string, unknown>;
869
+ }): RestrictedRouting {
870
+ const ignored: string[] = [];
871
+ const result: RestrictedRouting = { ignored };
872
+ const modeId = routed.modeId?.trim();
873
+ if (modeId) {
874
+ if (ROUTED_MODE_IDS.includes(modeId)) result.modeId = modeId;
875
+ else ignored.push(`modeId ${modeId}`);
876
+ }
877
+ const kept: Record<string, unknown> = {};
878
+ for (const [key, value] of Object.entries(routed.options ?? {})) {
879
+ if (ROUTED_OPTION_KEYS.includes(key)) kept[key] = value;
880
+ else ignored.push(`options.${key}`);
881
+ }
882
+ if (Object.keys(kept).length > 0) result.options = kept;
883
+ return result;
884
+ }
885
+
886
+ /**
887
+ * A profile a routing script names is routed input too: its modeId, options and featureValues
888
+ * reach the agent config. It is accepted only when the profile asks for nothing a script may not
889
+ * set itself; otherwise the caller keeps the profile the user chose and reports it as ignored.
890
+ */
891
+ export function vetRoutedProfile(
892
+ profiles: readonly (AgentProfileLike & { name: string })[],
893
+ routedName: string | undefined,
894
+ ): { profileName?: string; ignored: string[] } {
895
+ const wanted = routedName?.trim();
896
+ if (!wanted) return { ignored: [] };
897
+ const profile = profiles.find(
898
+ (candidate) => candidate.name.toLowerCase() === wanted.toLowerCase(),
899
+ );
900
+ const modeOk = !profile?.modeId?.trim() || ROUTED_MODE_IDS.includes(profile.modeId.trim());
901
+ const keysOk = [profile?.options, profile?.featureValues].every((bag) =>
902
+ Object.keys(bag ?? {}).every((key) => ROUTED_OPTION_KEYS.includes(key)),
903
+ );
904
+ if (!profile || !modeOk || !keysOk) return { ignored: [`profile ${wanted}`] };
905
+ return { profileName: profile.name, ignored: [] };
906
+ }
907
+
908
+ export interface AgentLaunchOverrides {
909
+ provider?: string;
910
+ model?: string;
911
+ modeId?: string;
912
+ thinkingOptionId?: string;
913
+ contextMode?: string;
914
+ options?: Record<string, unknown>;
915
+ }
916
+
917
+ export function buildAgentConfig(
918
+ profile: AgentProfileLike | undefined,
919
+ overrides: AgentLaunchOverrides = {},
920
+ ) {
921
+ const baseProvider = overrides.provider?.trim() || profile?.provider || "claude";
922
+ const baseModel = overrides.model?.trim() || (overrides.provider?.trim() ? "" : profile?.model);
923
+ const provider = baseModel ? `${baseProvider}/${baseModel}` : baseProvider;
924
+ const modeId = overrides.modeId?.trim() || profile?.modeId;
925
+ const thinkingOptionId = overrides.thinkingOptionId?.trim() || profile?.thinkingOptionId;
926
+ const mergedOptions: Record<string, unknown> = {
927
+ ...(profile?.options ?? {}),
928
+ ...(overrides.options ?? {}),
929
+ ...(overrides.contextMode?.trim() ? { contextMode: overrides.contextMode.trim() } : {}),
930
+ };
931
+ return {
932
+ provider,
933
+ ...(modeId ? { modeId } : {}),
934
+ ...(thinkingOptionId ? { thinkingOptionId } : {}),
935
+ ...(Object.keys(mergedOptions).length > 0 ? { options: mergedOptions } : {}),
936
+ ...(profile?.featureValues && Object.keys(profile.featureValues).length > 0
937
+ ? { featureValues: profile.featureValues }
938
+ : {}),
939
+ };
940
+ }
941
+
942
+ export function splitDraftRows(rows: readonly RadarRow[]): {
943
+ pullRequests: RadarRow[];
944
+ draftPullRequests: RadarRow[];
945
+ } {
946
+ const pullRequests: RadarRow[] = [];
947
+ const draftPullRequests: RadarRow[] = [];
948
+ for (const row of rows) {
949
+ if (row.isDraft) {
950
+ draftPullRequests.push(row);
951
+ } else {
952
+ pullRequests.push(row);
953
+ }
954
+ }
955
+ return { pullRequests, draftPullRequests };
956
+ }
957
+
958
+ export function buildIssueRows(
959
+ snapshot: RadarSnapshot | undefined,
960
+ issueItems: readonly GitHubIssueItem[],
961
+ ): RadarRow[] {
962
+ const roots = snapshot?.repositoryRoots ?? {};
963
+ const matches = snapshot?.issueMatches ?? {};
964
+ return issueItems.map((item) => {
965
+ const issueKey = `${item.repository.toLowerCase()}#issue-${item.number}`;
966
+ const matched = matches[issueKey];
967
+ const localProjectRoot = roots[item.repository.toLowerCase()] ?? null;
968
+ const agents = matched ? [...matched.agents] : [];
969
+ const workspaceIds = matched ? [...matched.workspaceIds] : [];
970
+ const workspaceNames = matched ? [...matched.workspaceNames] : [];
971
+ const cwdTag = matched?.cwdTag ?? "CWD-TBD";
972
+ const roleLabel =
973
+ item.role === "author"
974
+ ? "Authored issue"
975
+ : item.role === "assignee"
976
+ ? "Assigned to you"
977
+ : "Open in your repository";
978
+ const humanBlocker = attentionReason(agents);
979
+ const activeAgent = hasActiveAgent(agents);
980
+ const bucket: RadarBucket = humanBlocker
981
+ ? "needs-you"
982
+ : activeAgent
983
+ ? "being-handled"
984
+ : hasFailedAgent(agents)
985
+ ? "needs-you"
986
+ : item.role === "assignee"
987
+ ? "needs-you"
988
+ : "waiting";
989
+ return {
990
+ itemKind: "issue",
991
+ issueRole: item.role,
992
+ id: issueKey,
993
+ number: item.number,
994
+ url: item.url,
995
+ title: item.title,
996
+ repository: item.repository,
997
+ baseRefName: "",
998
+ headRefName: item.title,
999
+ isDraft: false,
1000
+ author: item.author,
1001
+ authorKind: item.authorKind,
1002
+ isSecurity: item.isSecurity,
1003
+ comments: item.comments,
1004
+ labels: [...item.labels],
1005
+ changes: [],
1006
+ linkedIssues: [],
1007
+ cwdTag,
1008
+ hasLocalPlace: Boolean(localProjectRoot) || workspaceIds.length > 0,
1009
+ mergeable: "UNKNOWN",
1010
+ mergeStateStatus: null,
1011
+ checksStatus: "none",
1012
+ reviewDecision: null,
1013
+ checks: [],
1014
+ workspaceIds,
1015
+ workspaceNames,
1016
+ localProjectRoot,
1017
+ agents,
1018
+ ownership: item.role === "author" ? "mine" : "external",
1019
+ reviewRequestedFromMe: false,
1020
+ bucket,
1021
+ reason: roleLabel,
1022
+ activityAt: item.updatedAt,
1023
+ refreshedAt: item.updatedAt,
1024
+ };
1025
+ });
1026
+ }
@@ -50,3 +50,23 @@ export function needsYouSummary(
50
50
  const items = rows.filter((row) => row.bucket === "needs-you");
51
51
  return { items, label: loading ? "…" : `${items.length}${warnings.length ? "+" : ""}` };
52
52
  }
53
+
54
+ export const INBOX_CAP_NOTE = "Results reached the 100-item inbox cap.";
55
+
56
+ /**
57
+ * The completeness note under the controls. It shows on both tabs, so a failed issue search or a
58
+ * capped result list is never read as "nothing here"; the update controls stay PR-only.
59
+ */
60
+ export function viewerCoverage(
61
+ tab: "prs" | "issues",
62
+ viewerData: { coverageNote: string; truncated: boolean; updates: number } | null | undefined,
63
+ ) {
64
+ if (!viewerData) return null;
65
+ const text = `${viewerData.coverageNote}${viewerData.truncated ? ` ${INBOX_CAP_NOTE}` : ""}`;
66
+ return { text, showUpdates: tab === "prs" && viewerData.updates > 0 };
67
+ }
68
+
69
+ /** Screen readers get the picked option from its state, not only from the accent colour. */
70
+ export function pickerOptionAccessibility(selected: boolean) {
71
+ return { accessibilityRole: "button" as const, accessibilityState: { selected } };
72
+ }