Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add a per-app Issues tab and move JIRA config + kanban onto their own tab
[._.]/ Adam Eivy4b5837f72ba2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 83b9f719f5..d7e31d68ec 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,10 @@- Video Gen now offers Apple-local Wan 2.2 TI2V-5B plus validated 4-step A14B Lightning text- and image-to-video profiles through a pinned MLX-Gen runtime. Runtime tools/packages, immutable base snapshots, and exact Lightning adapters install only after an explicit UI action; existing installs receive an in-app repair/upgrade path, saved Hugging Face credentials are applied automatically, gated-source errors link back to the settings/access UI, and render/queue actions stay blocked until every required file is cached. The catalog identifies the A14B profiles as roughly 40 GiB downloads intended for 64+ GB Apple Silicon rather than understating their footprint. Wan-specific 4n+1 frame choices, FPS options, mode compatibility, process-tree cancellation, and locked Lightning sampler settings keep the UI aligned with the actual model contract.+- **Every managed app now has an Issues tab.** It queries the forge the app's work actually lives on (GitHub via `gh`, GitLab via `glab` — enterprise and nested-subgroup remotes included) and lists every open issue with its labels in the forge's own colors, assignees, author, milestone, and an expandable description, plus a filter box over all of it. Each row has a **Claim** button that queues the same `/do:next` CoS agent the Agent Operations panel does, pinned to that issue — so the run honors the app's configured Work Tracker, worktree, and PR settings. The list is gated on the app's *resolved* Work Tracker rather than its git remote alone, which is what keeps that promise: `workTracker` is user-settable and wins over the origin host, so an app with a GitHub remote but its tracker pinned to JIRA would otherwise have listed GitHub issues behind a Claim button that queued a JIRA-ticket run against a key that doesn't exist. Such an app now says so and points at the setting. An unreachable CLI says so and names the remedy; it is never reported as "no open issues".++- **JIRA config and the sprint Kanban board moved onto the app's own JIRA tab.** They were split across two surfaces that neither of them fit: the config was a cramped tab inside the 720px Edit App drawer, and the board was buried below the fold of the Overview tab. They now sit together at `/apps/:id/jira` with the full page width, and the config saves only its own slice, so a save there and a save from the Edit App drawer can no longer overwrite each other.+- Series Pipeline **Autonomous mode** now says which AI it will spend on. The Options popover names the provider and model the run resolves to, links to where per-stage pins and reasoning effort are configured, and offers a per-run provider/model override (never persisted — a one-off run can't silently re-point the whole series). The live progress line names the provider of an in-flight run too, including one the scheduler started.- **Reference images now work on Codex, Grok and Agy, not just local FLUX.** Picking a reference image told you it was "Flux only", and it was: the server rejected reference uploads for every backend but local FLUX.2, and Agy refused an input image of any kind. All three cloud CLIs in fact expose a reference-image parameter — their tool schemas were probed directly rather than taken on the CLI's word — so each now receives them: Codex attaches every input image to `image_gen`'s `referenced_image_paths`, Grok routes them to `image_edit`'s `image` array (a reference-only render goes there too, since its `image_gen` has no image parameter at all), and Agy passes them as `generate_image`'s `ImagePaths`. The init image leads the list everywhere and still carries the strength → fidelity-phrase mapping. The Image Gen form offers as many reference slots as the selected backend actually accepts — Agy's tool takes at most 3 images total, so an init image there leaves room for 2 — and hides the per-reference strength slider on the cloud CLIs, which expose no numeric weight. Sprite forks, seeded reference renders and pipeline redraws no longer divert away from an Agy pin, and Agy alone still requires a prompt even with an input image, because its tool does.diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex 08764004f9..73bf5f4670 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -17,6 +17,8 @@ import AutomationTab from './tabs/AutomationTab';import DocumentsTab from './tabs/DocumentsTab';import GitTab from './tabs/GitTab';import GsdTab from './tabs/GsdTab';+import IssuesTab from './tabs/IssuesTab';+import JiraTab from './tabs/JiraTab';import ProcessesTab from './tabs/ProcessesTab';import ReferencesTab from './tabs/ReferencesTab';import DatadogTab from './tabs/DatadogTab';@@ -250,6 +252,10 @@ export default function AppDetailView() {return <GitTab appId={appId} appName={app.name} repoPath={app.repoPath} />;case 'gsd':return <GsdTab appId={appId} repoPath={app.repoPath} />;+ case 'issues':+ return <IssuesTab appId={appId} appName={app.name} />;+ case 'jira':+ return <JiraTab app={app} onRefresh={fetchApp} />;case 'processes':return <ProcessesTab appId={app.id} pm2ProcessNames={app.pm2ProcessNames} />;case 'references':diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex d3aca614c9..ff977cbc64 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -14,13 +14,17 @@ import { PROVIDER_TYPES } from '../../utils/providers';import { DEFAULT_PR_COMPLETION, PR_COMPLETION_OPTIONS, prCompletionOption } from '../cos/constants';import { WORK_TRACKER_OPTIONS, WORK_TRACKER_LABELS } from './constants';+// JIRA is deliberately absent: its config moved to the app detail page's JIRA+// tab (/apps/:id/jira), where it sits next to the sprint board it drives and has+// the width the instance/project/board pickers need. This drawer therefore never+// sends a `jira` key — the PUT shallow-merges server-side, so the stored config+// is preserved untouched.const TABS = [{ id: 'general', label: 'General' },{ id: 'ports', label: 'Ports & TLS' },{ id: 'commands', label: 'Commands' },{ id: 'workflow', label: 'Workflow' },{ id: 'intelligence', label: 'Intelligence' },- { id: 'jira', label: 'JIRA' },{ id: 'datadog', label: 'DataDog' }];const TAB_IDS = TABS.map(t => t.id);@@ -33,10 +37,6 @@ const PORT_FIELDS = [['tlsPort', 'TLS Port']];-// A JIRA issue key like CONTECH-1553 — used to tell "user typed a key to validate"-// from "user is searching an epic by name" in the epic field.-const EPIC_KEY_RE = /^[A-Za-z][A-Za-z0-9]*-\d+$/;-export default function EditAppDrawer({ app, onClose, onSave }) {const [activeTab, setActiveTab] = useDrawerTab('appTab', 'general', TAB_IDS);const [formData, setFormData] = useState({@@ -59,15 +59,6 @@ export default function EditAppDrawer({ app, onClose, onSave }) {defaultOpenPR: app.defaultOpenPR || false,defaultPrCompletion: app.defaultPrCompletion || DEFAULT_PR_COMPLETION,defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,- jiraEnabled: app.jira?.enabled || false,- jiraInstanceId: app.jira?.instanceId || '',- jiraProjectKey: app.jira?.projectKey || '',- jiraBoardId: app.jira?.boardId || '',- jiraIssueType: app.jira?.issueType || 'Task',- jiraLabels: (app.jira?.labels || []).join(', '),- jiraAssignee: app.jira?.assignee || '',- jiraEpicKey: app.jira?.epicKey || '',- jiraCreatePR: app.jira?.createPR !== false,datadogEnabled: app.datadog?.enabled || false,datadogInstanceId: app.datadog?.instanceId || '',datadogServiceName: app.datadog?.serviceName || '',@@ -120,28 +111,12 @@ export default function EditAppDrawer({ app, onClose, onSave }) {}};const [workTrackerInfo, setWorkTrackerInfo] = useState(null);- const [jiraInstances, setJiraInstances] = useState([]);const [datadogInstances, setDatadogInstances] = useState([]);- const [jiraProjects, setJiraProjects] = useState([]);- const [loadingProjects, setLoadingProjects] = useState(false);- const [projectSearch, setProjectSearch] = useState('');- const [projectDropdownOpen, setProjectDropdownOpen] = useState(false);- const [jiraBoards, setJiraBoards] = useState([]);- const [loadingBoards, setLoadingBoards] = useState(false);- const [boardSprints, setBoardSprints] = useState([]);- const [epicResults, setEpicResults] = useState([]);- const [epicDropdownOpen, setEpicDropdownOpen] = useState(false);- const [epicValidation, setEpicValidation] = useState({ state: 'idle' });useEffect(() => {- const toInstances = (data) => data?.instances ? Object.values(data.instances) : [];- Promise.all([- api.getJiraInstances().then(toInstances).catch(() => []),- api.getDatadogInstances().then(toInstances).catch(() => [])- ]).then(([jira, datadog]) => {- setJiraInstances(jira);- setDatadogInstances(datadog);- });+ api.getDatadogInstances()+ .then(data => setDatadogInstances(data?.instances ? Object.values(data.instances) : []))+ .catch(() => setDatadogInstances([]));}, []);useEffect(() => {@@ -202,119 +177,6 @@ export default function EditAppDrawer({ app, onClose, onSave }) {const updateLiConfig = (patch) => setLiConfig(prev => ({ ...(prev || {}), ...patch }));- useEffect(() => {- if (!formData.jiraInstanceId) {- setJiraProjects([]);- return;- }- setLoadingProjects(true);- api.getJiraProjects(formData.jiraInstanceId).then(projects => {- setJiraProjects(projects || []);- }).catch(() => setJiraProjects([])).finally(() => setLoadingProjects(false));- }, [formData.jiraInstanceId]);-- useEffect(() => {- if (!formData.jiraInstanceId || formData.jiraAssignee) return;- const inst = jiraInstances.find(i => i.id === formData.jiraInstanceId);- if (inst?.email) {- setFormData(prev => ({ ...prev, jiraAssignee: inst.email }));- }- }, [formData.jiraInstanceId, jiraInstances, formData.jiraAssignee]);-- // Detect the project's agile boards so the boardId is picked from live data- // instead of hand-typed (which is how a boardId goes stale across a migration).- useEffect(() => {- if (!formData.jiraInstanceId || !formData.jiraProjectKey) {- setJiraBoards([]);- return;- }- let cancelled = false;- setLoadingBoards(true);- api.getJiraBoards(formData.jiraInstanceId, formData.jiraProjectKey, { silent: true })- .then(boards => { if (!cancelled) setJiraBoards(boards || []); })- .catch(() => { if (!cancelled) setJiraBoards([]); })- .finally(() => { if (!cancelled) setLoadingBoards(false); });- return () => { cancelled = true; };- }, [formData.jiraInstanceId, formData.jiraProjectKey]);-- // Show the selected board's active sprint as confirmation it's the right board.- useEffect(() => {- if (!formData.jiraInstanceId || !formData.jiraBoardId) {- setBoardSprints([]);- return;- }- let cancelled = false;- api.getJiraBoardSprints(formData.jiraInstanceId, formData.jiraBoardId, { silent: true })- .then(sprints => { if (!cancelled) setBoardSprints(sprints || []); })- .catch(() => { if (!cancelled) setBoardSprints([]); });- return () => { cancelled = true; };- }, [formData.jiraInstanceId, formData.jiraBoardId]);-- // Validate the configured epic key still resolves as an Epic on this instance.- useEffect(() => {- const key = formData.jiraEpicKey.trim();- if (!formData.jiraInstanceId || !EPIC_KEY_RE.test(key)) {- setEpicValidation({ state: 'idle' });- return;- }- let cancelled = false;- setEpicValidation({ state: 'checking' });- const t = setTimeout(() => {- api.getJiraIssue(formData.jiraInstanceId, key, { silent: true })- .then(issue => {- if (cancelled) return;- const isEpic = (issue.issueType || '').toLowerCase() === 'epic';- setEpicValidation({ state: isEpic ? 'ok' : 'wrongtype', issue });- })- .catch(() => { if (!cancelled) setEpicValidation({ state: 'stale' }); });- }, 400);- return () => { cancelled = true; clearTimeout(t); };- }, [formData.jiraInstanceId, formData.jiraEpicKey]);-- // When the epic field holds free text (not a key), search epics by name to pick one.- useEffect(() => {- const q = formData.jiraEpicKey.trim();- if (!formData.jiraInstanceId || !formData.jiraProjectKey || q.length < 2 || EPIC_KEY_RE.test(q)) {- setEpicResults([]);- return;- }- let cancelled = false;- const t = setTimeout(() => {- api.searchJiraEpics(formData.jiraInstanceId, formData.jiraProjectKey, q, { silent: true })- .then(results => { if (!cancelled) setEpicResults(results || []); })- .catch(() => { if (!cancelled) setEpicResults([]); });- }, 300);- return () => { cancelled = true; clearTimeout(t); };- }, [formData.jiraInstanceId, formData.jiraProjectKey, formData.jiraEpicKey]);-- // Project-key combobox options: filter by the search box, sort by key, cap at- // 100. Derived once per render so the predicate isn't duplicated between the- // option list and the "no matching projects" empty-state check below.- const filteredJiraProjects = jiraProjects- .filter(proj => {- if (!projectSearch) return true;- const q = projectSearch.toLowerCase();- return proj.key.toLowerCase().includes(q) || proj.name.toLowerCase().includes(q);- })- .sort((a, b) => a.key.localeCompare(b.key))- .slice(0, 100);-- // A saved boardId that isn't among the project's detected boards is stale- // (e.g. carried over from a Server instance after a Cloud migration).- const boardIsStale = !!formData.jiraBoardId && jiraBoards.length > 0- && !jiraBoards.some(b => String(b.id) === String(formData.jiraBoardId));- const activeSprint = boardSprints[0] || null;-- // Changing the instance or project invalidates the selected board, so clear it- // in one place — every discrete instance/project change goes through these so no- // call site forgets the reset. Deliberately interaction-driven, NOT a projectKey- // effect: an effect would fire on mount with the saved projectKey and wipe the- // saved boardId before the boards fetch resolves, defeating stale-board detection.- const changeInstance = (jiraInstanceId) =>- setFormData(prev => ({ ...prev, jiraInstanceId, jiraProjectKey: '', jiraBoardId: '' }));- const selectProject = (jiraProjectKey) =>- setFormData(prev => ({ ...prev, jiraProjectKey, jiraBoardId: '' }));-const handleSubmit = async (e) => {e.preventDefault();setError(null);@@ -388,17 +250,6 @@ export default function EditAppDrawer({ app, onClose, onSave }) {defaultUseWorktree: formData.defaultUseWorktree || formData.defaultOpenPR,defaultOpenPR: formData.defaultOpenPR,defaultPrCompletion: formData.defaultPrCompletion,- jira: formData.jiraEnabled ? {- enabled: true,- instanceId: formData.jiraInstanceId || undefined,- projectKey: formData.jiraProjectKey || undefined,- boardId: formData.jiraBoardId || undefined,- issueType: formData.jiraIssueType || 'Task',- labels: formData.jiraLabels ? formData.jiraLabels.split(',').map(s => s.trim()).filter(Boolean) : [],- assignee: formData.jiraAssignee || undefined,- epicKey: formData.jiraEpicKey.trim() || undefined,- createPR: formData.jiraCreatePR- } : { enabled: false },datadog: formData.datadogEnabled ? {enabled: true,instanceId: formData.datadogInstanceId || undefined,@@ -445,9 +296,9 @@ export default function EditAppDrawer({ app, onClose, onSave }) {tabs={TABS}activeTab={activeTab}onTabChange={setActiveTab}- // The form is long-lived and an accidental Esc / backdrop click while- // editing nested JIRA pickers would lose state. Preserve the modal's- // no-accidental-dismiss behavior.+ // The form is long-lived and spans several tabs, so an accidental Esc /+ // backdrop click mid-edit would discard work across all of them. Preserve+ // the modal's no-accidental-dismiss behavior.closeOnEsc={false}closeOnBackdrop={false}>@@ -459,9 +310,9 @@ export default function EditAppDrawer({ app, onClose, onSave }) {{/* The Drawer body remounts per active tab (key={currentTab}), so thisentire form/footer subtree is torn down and rebuilt on every tab- switch. All mutable form state (formData, error, saving, the JIRA- project-picker state) therefore MUST live above the Drawer body in- this component — never in an uncontrolled input or subcomponent+ switch. All mutable form state (formData, error, saving, the layered+ intelligence working copy) therefore MUST live above the Drawer body+ in this component — never in an uncontrolled input or subcomponentinside the form, or it would silently reset on tab switch. */}<form onSubmit={handleSubmit} className="space-y-4">{activeTab === 'general' && (@@ -795,260 +646,6 @@ export default function EditAppDrawer({ app, onClose, onSave }) {/>)}- {activeTab === 'jira' && (- <div className="space-y-3">- <label className="flex items-center gap-2 cursor-pointer">- <input- type="checkbox"- checked={formData.jiraEnabled}- onChange={e => setFormData({ ...formData, jiraEnabled: e.target.checked })}- className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"- />- <span className="text-sm text-white">Enable JIRA Integration</span>- </label>-- {formData.jiraEnabled && (- <>- {jiraInstances.length === 0 ? (- <Banner tone="warning" size="md">- No JIRA instances configured. <Link to="/devtools/jira" className="underline hover:text-white">Configure JIRA</Link> first.- </Banner>- ) : (- <>- <div>- <label htmlFor="edit-app-jira-instance" className="block text-sm text-gray-400 mb-1">JIRA Instance</label>- <select- id="edit-app-jira-instance"- value={formData.jiraInstanceId}- onChange={e => changeInstance(e.target.value)}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- >- <option value="">Select instance...</option>- {jiraInstances.map(inst => (- <option key={inst.id} value={inst.id}>{inst.name} ({inst.baseUrl})</option>- ))}- </select>- </div>-- <div className="relative">- <label htmlFor="edit-app-jira-project" className="block text-sm text-gray-400 mb-1">Project Key</label>- {loadingProjects ? (- <div className="text-xs text-gray-500">Loading projects...</div>- ) : jiraProjects.length > 0 ? (- <div>- <input- id="edit-app-jira-project"- type="text"- value={projectDropdownOpen ? projectSearch : (- formData.jiraProjectKey- ? `${formData.jiraProjectKey} - ${jiraProjects.find(p => p.key === formData.jiraProjectKey)?.name || ''}`- : ''- )}- onChange={e => {- setProjectSearch(e.target.value);- if (!projectDropdownOpen) setProjectDropdownOpen(true);- }}- onFocus={() => {- setProjectDropdownOpen(true);- setProjectSearch('');- }}- onBlur={() => setTimeout(() => setProjectDropdownOpen(false), 150)}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="Search projects..."- />- {formData.jiraProjectKey && !projectDropdownOpen && (- <button- type="button"- onClick={() => selectProject('')}- aria-label="Clear JIRA project"- className="absolute right-2 top-8 text-gray-500 hover:text-white text-sm"- >- x- </button>- )}- {projectDropdownOpen && (- <div className="absolute z-50 w-full mt-1 bg-port-bg border border-port-border rounded-lg max-h-48 overflow-auto shadow-lg">- {filteredJiraProjects- .map(proj => (- <button- key={proj.key}- type="button"- onMouseDown={e => {- e.preventDefault();- selectProject(proj.key);- setProjectDropdownOpen(false);- setProjectSearch('');- }}- className={`w-full text-left px-3 py-2 text-sm hover:bg-port-accent/20 ${- formData.jiraProjectKey === proj.key ? 'bg-port-accent/10 text-port-accent' : 'text-white'- }`}- >- <span className="font-mono">{proj.key}</span>- <span className="text-gray-400 ml-2">{proj.name}</span>- </button>- ))- }- {filteredJiraProjects.length === 0 && (- <div className="px-3 py-2 text-sm text-gray-500">No matching projects</div>- )}- </div>- )}- </div>- ) : (- <input- id="edit-app-jira-project"- type="text"- value={formData.jiraProjectKey}- onChange={e => setFormData({ ...formData, jiraProjectKey: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="e.g. CONTECH"- />- )}- </div>-- <div>- <label htmlFor="edit-app-jira-board" className="block text-sm text-gray-400 mb-1">Board</label>- {!formData.jiraProjectKey ? (- <div className="text-xs text-gray-500">Select a project to detect its boards.</div>- ) : loadingBoards ? (- <div className="text-xs text-gray-500">Detecting boards…</div>- ) : jiraBoards.length > 0 ? (- <>- <select- id="edit-app-jira-board"- value={formData.jiraBoardId}- onChange={e => setFormData({ ...formData, jiraBoardId: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- >- <option value="">Select board...</option>- {jiraBoards.map(b => (- <option key={b.id} value={String(b.id)}>{b.id} — {b.name} ({b.type})</option>- ))}- {boardIsStale && (- <option value={formData.jiraBoardId}>{formData.jiraBoardId} — (not in this project)</option>- )}- </select>- {boardIsStale ? (- <p className="text-xs text-port-warning mt-1">⚠ Saved board {formData.jiraBoardId} isn't among this project's boards — pick a current one.</p>- ) : formData.jiraBoardId && (- <p className="text-xs text-gray-500 mt-1">- {activeSprint ? `Active sprint: ${activeSprint.name}` : 'No active sprint on this board.'}- </p>- )}- </>- ) : (- <>- <input- id="edit-app-jira-board"- type="text"- value={formData.jiraBoardId}- onChange={e => setFormData({ ...formData, jiraBoardId: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="e.g. 1294 (from JIRA board URL rapidView param)"- />- <p className="text-xs text-gray-500 mt-1">Couldn't auto-detect boards — enter the id manually (board URL <span className="font-mono">rapidView</span> param).</p>- </>- )}- </div>-- <div className="grid grid-cols-2 gap-3">- <div>- <label htmlFor="edit-app-jira-issue-type" className="block text-sm text-gray-400 mb-1">Issue Type</label>- <input- id="edit-app-jira-issue-type"- type="text"- value={formData.jiraIssueType}- onChange={e => setFormData({ ...formData, jiraIssueType: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="Task"- />- </div>- <div>- <label htmlFor="edit-app-jira-assignee" className="block text-sm text-gray-400 mb-1">Assignee</label>- <input- id="edit-app-jira-assignee"- type="text"- value={formData.jiraAssignee}- onChange={e => setFormData({ ...formData, jiraAssignee: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="Optional"- />- </div>- </div>-- <div>- <label htmlFor="edit-app-jira-labels" className="block text-sm text-gray-400 mb-1">Labels (comma-separated)</label>- <input- id="edit-app-jira-labels"- type="text"- value={formData.jiraLabels}- onChange={e => setFormData({ ...formData, jiraLabels: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="e.g. cos-auto, feature"- />- </div>-- <div className="relative">- <label htmlFor="edit-app-jira-epic" className="block text-sm text-gray-400 mb-1">Epic Key</label>- <input- id="edit-app-jira-epic"- type="text"- value={formData.jiraEpicKey}- onChange={e => setFormData({ ...formData, jiraEpicKey: e.target.value })}- onFocus={() => setEpicDropdownOpen(true)}- onBlur={() => setTimeout(() => setEpicDropdownOpen(false), 150)}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"- placeholder="e.g. CONTECH-100, or type a name to search"- />- {epicDropdownOpen && epicResults.length > 0 && (- <div className="absolute z-50 w-full mt-1 bg-port-bg border border-port-border rounded-lg max-h-48 overflow-auto shadow-lg">- {epicResults.map(ep => (- <button- key={ep.key}- type="button"- onMouseDown={e => {- e.preventDefault();- setFormData({ ...formData, jiraEpicKey: ep.key });- setEpicDropdownOpen(false);- }}- className="w-full text-left px-3 py-2 text-sm hover:bg-port-accent/20 text-white"- >- <span className="font-mono">{ep.key}</span>- <span className="text-gray-400 ml-2">{ep.summary}</span>- </button>- ))}- </div>- )}- {epicValidation.state !== 'idle' && (- <p className={`text-xs mt-1 ${- epicValidation.state === 'ok' ? 'text-port-success'- : epicValidation.state === 'checking' ? 'text-gray-500'- : 'text-port-warning'- }`}>- {epicValidation.state === 'checking' && 'Checking epic…'}- {epicValidation.state === 'ok' && `✓ ${epicValidation.issue.key} · ${epicValidation.issue.summary}`}- {epicValidation.state === 'wrongtype' && `⚠ ${epicValidation.issue.key} is a ${epicValidation.issue.issueType}, not an Epic`}- {epicValidation.state === 'stale' && `⚠ ${formData.jiraEpicKey} doesn't resolve on this instance`}- </p>- )}- </div>-- <label className="flex items-center gap-2 cursor-pointer">- <input- type="checkbox"- checked={formData.jiraCreatePR}- onChange={e => setFormData({ ...formData, jiraCreatePR: e.target.checked })}- className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"- />- <span className="text-sm text-white">Create Pull Request on completion</span>- </label>- </>- )}- </>- )}- </div>- )}-{activeTab === 'datadog' && (<div className="space-y-3"><label className="flex items-center gap-2 cursor-pointer">diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsxindex 2b8cd82974..3a3ae80f34 100644--- a/client/src/components/apps/EditAppDrawer.test.jsx+++ b/client/src/components/apps/EditAppDrawer.test.jsx@@ -5,9 +5,7 @@ import { MemoryRouter } from 'react-router';// Mock the API surface EditAppDrawer touches on mount, plus the work-tracker// resolver and the update path used on save.vi.mock('../../services/api', () => ({- getJiraInstances: vi.fn(),getDatadogInstances: vi.fn(),- getJiraProjects: vi.fn(),getAppWorkTracker: vi.fn(),getAppLayeredIntelligence: vi.fn(),getAppTaskTypes: vi.fn(),@@ -44,9 +42,7 @@ async function openTab(name) {}beforeEach(() => {- api.getJiraInstances.mockResolvedValue({ instances: {} });api.getDatadogInstances.mockResolvedValue({ instances: {} });- api.getJiraProjects.mockResolvedValue([]);api.getAppWorkTracker.mockResolvedValue({configured: 'auto',resolved: 'github',@@ -90,10 +86,16 @@ describe('EditAppDrawer tabbed layout', () => {it('renders all six section tabs', async () => {renderDrawer();- for (const label of ['General', 'Ports & TLS', 'Commands', 'Workflow', 'JIRA', 'DataDog']) {+ for (const label of ['General', 'Ports & TLS', 'Commands', 'Workflow', 'Intelligence', 'DataDog']) {expect(await screen.findByRole('tab', { name: label })).toBeInTheDocument();}});++ it('has no JIRA tab — that config moved to the app detail page JIRA tab', async () => {+ renderDrawer();+ await screen.findByRole('tab', { name: 'General' });+ expect(screen.queryByRole('tab', { name: 'JIRA' })).not.toBeInTheDocument();+ });});describe('EditAppDrawer work tracker selector', () => {@@ -137,6 +139,20 @@ describe('EditAppDrawer work tracker selector', () => {expect(payload.workTracker).toBe('gitlab');});+ it('omits `jira` from the save payload so a drawer save cannot clobber the JIRA tab config', async () => {+ // The server shallow-merges the PUT, so an ABSENT `jira` key preserves the+ // stored config. Sending `{ enabled: false }` (what the removed drawer tab+ // did when its checkbox was unmounted) would silently disable an app's JIRA+ // integration on an unrelated save.+ renderDrawer({ app: { ...APP, jira: { enabled: true, instanceId: 'inst-1', projectKey: 'PROJ' } } });+ await screen.findByLabelText('Name');++ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));++ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());+ expect(api.updateApp.mock.calls[0][1]).not.toHaveProperty('jira');+ });+it('saves the selected default PR completion policy', async () => {renderDrawer({ app: { ...APP, defaultUseWorktree: true, defaultOpenPR: true } });await openTab('Workflow');diff --git a/client/src/components/apps/JiraConfigPanel.jsx b/client/src/components/apps/JiraConfigPanel.jsxnew file mode 100644index 0000000000..bdf3a22b2d--- /dev/null+++ b/client/src/components/apps/JiraConfigPanel.jsx@@ -0,0 +1,470 @@+import { useState, useEffect, useMemo } from 'react';+import { Link } from 'react-router';+import { Save, Loader2 } from 'lucide-react';+import * as api from '../../services/api';+import toast from '../ui/Toast';+import Banner from '../ui/Banner';+import { INPUT_CLASS } from './constants';++// A JIRA issue key like PROJ-1553 — used to tell "user typed a key to validate"+// from "user is searching an epic by name" in the epic field.+const EPIC_KEY_RE = /^[A-Za-z][A-Za-z0-9]*-\d+$/;++/** Flatten the app record's stored `jira` object into flat form fields. */+const toForm = (jira) => ({+ enabled: jira?.enabled || false,+ instanceId: jira?.instanceId || '',+ projectKey: jira?.projectKey || '',+ boardId: jira?.boardId || '',+ issueType: jira?.issueType || 'Task',+ labels: (jira?.labels || []).join(', '),+ assignee: jira?.assignee || '',+ epicKey: jira?.epicKey || '',+ createPR: jira?.createPR !== false+});++/**+ * The app's JIRA integration config — instance/project/board pickers, issue+ * defaults, and the epic combobox.+ *+ * Lives on the app detail page's JIRA tab (alongside the sprint Kanban board)+ * rather than inside the Edit App drawer: JIRA config is only meaningful next to+ * the board it drives, and the pickers are wide enough that a 720px drawer made+ * them cramped. Saves ONLY the `jira` slice through `PUT /api/apps/:id` (a+ * shallow merge server-side), so it can't clobber fields the drawer owns.+ */+export default function JiraConfigPanel({ app, onSaved }) {+ const [form, setForm] = useState(() => toForm(app.jira));+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(null);+ const [instances, setInstances] = useState([]);+ const [projects, setProjects] = useState([]);+ const [loadingProjects, setLoadingProjects] = useState(false);+ const [projectSearch, setProjectSearch] = useState('');+ const [projectDropdownOpen, setProjectDropdownOpen] = useState(false);+ const [boards, setBoards] = useState([]);+ const [loadingBoards, setLoadingBoards] = useState(false);+ const [boardSprints, setBoardSprints] = useState([]);+ const [epicResults, setEpicResults] = useState([]);+ const [epicDropdownOpen, setEpicDropdownOpen] = useState(false);+ const [epicValidation, setEpicValidation] = useState({ state: 'idle' });++ useEffect(() => {+ api.getJiraInstances()+ .then(data => setInstances(data?.instances ? Object.values(data.instances) : []))+ .catch(() => setInstances([]));+ }, []);++ useEffect(() => {+ if (!form.instanceId) {+ setProjects([]);+ return;+ }+ let cancelled = false;+ setLoadingProjects(true);+ api.getJiraProjects(form.instanceId)+ .then(list => { if (!cancelled) setProjects(list || []); })+ .catch(() => { if (!cancelled) setProjects([]); })+ .finally(() => { if (!cancelled) setLoadingProjects(false); });+ return () => { cancelled = true; };+ }, [form.instanceId]);++ // Default the assignee to the instance's own account so the common case needs+ // no typing — only when the field is still empty, never overwriting a choice.+ useEffect(() => {+ if (!form.instanceId || form.assignee) return;+ const inst = instances.find(i => i.id === form.instanceId);+ if (inst?.email) setForm(prev => ({ ...prev, assignee: inst.email }));+ }, [form.instanceId, form.assignee, instances]);++ // Detect the project's agile boards so the boardId is picked from live data+ // instead of hand-typed (which is how a boardId goes stale across a migration).+ useEffect(() => {+ if (!form.instanceId || !form.projectKey) {+ setBoards([]);+ return;+ }+ let cancelled = false;+ setLoadingBoards(true);+ api.getJiraBoards(form.instanceId, form.projectKey, { silent: true })+ .then(list => { if (!cancelled) setBoards(list || []); })+ .catch(() => { if (!cancelled) setBoards([]); })+ .finally(() => { if (!cancelled) setLoadingBoards(false); });+ return () => { cancelled = true; };+ }, [form.instanceId, form.projectKey]);++ // Show the selected board's active sprint as confirmation it's the right board.+ useEffect(() => {+ if (!form.instanceId || !form.boardId) {+ setBoardSprints([]);+ return;+ }+ let cancelled = false;+ api.getJiraBoardSprints(form.instanceId, form.boardId, { silent: true })+ .then(sprints => { if (!cancelled) setBoardSprints(sprints || []); })+ .catch(() => { if (!cancelled) setBoardSprints([]); });+ return () => { cancelled = true; };+ }, [form.instanceId, form.boardId]);++ // Validate the configured epic key still resolves as an Epic on this instance.+ useEffect(() => {+ const key = form.epicKey.trim();+ if (!form.instanceId || !EPIC_KEY_RE.test(key)) {+ setEpicValidation({ state: 'idle' });+ return;+ }+ let cancelled = false;+ setEpicValidation({ state: 'checking' });+ const t = setTimeout(() => {+ api.getJiraIssue(form.instanceId, key, { silent: true })+ .then(issue => {+ if (cancelled) return;+ const isEpic = (issue.issueType || '').toLowerCase() === 'epic';+ setEpicValidation({ state: isEpic ? 'ok' : 'wrongtype', issue });+ })+ .catch(() => { if (!cancelled) setEpicValidation({ state: 'stale' }); });+ }, 400);+ return () => { cancelled = true; clearTimeout(t); };+ }, [form.instanceId, form.epicKey]);++ // When the epic field holds free text (not a key), search epics by name to pick one.+ useEffect(() => {+ const q = form.epicKey.trim();+ if (!form.instanceId || !form.projectKey || q.length < 2 || EPIC_KEY_RE.test(q)) {+ setEpicResults([]);+ return;+ }+ let cancelled = false;+ const t = setTimeout(() => {+ api.searchJiraEpics(form.instanceId, form.projectKey, q, { silent: true })+ .then(results => { if (!cancelled) setEpicResults(results || []); })+ .catch(() => { if (!cancelled) setEpicResults([]); });+ }, 300);+ return () => { cancelled = true; clearTimeout(t); };+ }, [form.instanceId, form.projectKey, form.epicKey]);++ // Project-key combobox options: filter by the search box, sort by key, cap at+ // 100. Derived once so the predicate isn't duplicated between the option list+ // and the "no matching projects" empty-state check below. Memoized on its real+ // inputs: a JIRA instance with hundreds of projects otherwise re-ran an+ // Intl-backed `localeCompare` sort on every keystroke in the Labels, Assignee,+ // Issue Type, and Epic fields, which all share this component's form state.+ const filteredProjects = useMemo(() => projects+ .filter(proj => {+ if (!projectSearch) return true;+ const q = projectSearch.toLowerCase();+ return proj.key.toLowerCase().includes(q) || proj.name.toLowerCase().includes(q);+ })+ .sort((a, b) => a.key.localeCompare(b.key))+ .slice(0, 100), [projects, projectSearch]);++ const selectedProjectName = useMemo(+ () => projects.find(p => p.key === form.projectKey)?.name || '',+ [projects, form.projectKey]+ );++ // A saved boardId that isn't among the project's detected boards is stale+ // (e.g. carried over from a Server instance after a Cloud migration).+ const boardIsStale = !!form.boardId && boards.length > 0+ && !boards.some(b => String(b.id) === String(form.boardId));+ const activeSprint = boardSprints[0] || null;++ // Changing the instance or project invalidates the selected board, so clear it+ // in one place — every discrete instance/project change goes through these so no+ // call site forgets the reset. Deliberately interaction-driven, NOT a projectKey+ // effect: an effect would fire on mount with the saved projectKey and wipe the+ // saved boardId before the boards fetch resolves, defeating stale-board detection.+ const changeInstance = (instanceId) =>+ setForm(prev => ({ ...prev, instanceId, projectKey: '', boardId: '' }));+ const selectProject = (projectKey) =>+ setForm(prev => ({ ...prev, projectKey, boardId: '' }));++ const handleSubmit = async (e) => {+ e.preventDefault();+ setError(null);+ setSaving(true);+ const jira = form.enabled ? {+ enabled: true,+ instanceId: form.instanceId || undefined,+ projectKey: form.projectKey || undefined,+ boardId: form.boardId || undefined,+ issueType: form.issueType || 'Task',+ labels: form.labels ? form.labels.split(',').map(s => s.trim()).filter(Boolean) : [],+ assignee: form.assignee || undefined,+ epicKey: form.epicKey.trim() || undefined,+ createPR: form.createPR+ } : { enabled: false };+ // Custom error UI below, so silence the helper's toast (one layer wins).+ const updated = await api.updateApp(app.id, { jira }, { silent: true }).catch(err => {+ setError(err.message);+ return null;+ });+ setSaving(false);+ if (!updated) return;+ toast.success('JIRA configuration saved');+ onSaved?.(updated);+ };++ return (+ <form onSubmit={handleSubmit} className="space-y-3 max-w-3xl">+ {error && (+ <div className="p-3 bg-port-error/20 border border-port-error rounded-lg text-port-error text-sm">+ {error}+ </div>+ )}++ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={form.enabled}+ onChange={e => setForm({ ...form, enabled: e.target.checked })}+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <span className="text-sm text-white">Enable JIRA Integration</span>+ </label>++ {form.enabled && (+ instances.length === 0 ? (+ <Banner tone="warning" size="md">+ No JIRA instances configured. <Link to="/devtools/jira" className="underline hover:text-white">Configure JIRA</Link> first.+ </Banner>+ ) : (+ <>+ <div>+ <label htmlFor="app-jira-instance" className="block text-sm text-gray-400 mb-1">JIRA Instance</label>+ <select+ id="app-jira-instance"+ value={form.instanceId}+ onChange={e => changeInstance(e.target.value)}+ className={INPUT_CLASS}+ >+ <option value="">Select instance...</option>+ {instances.map(inst => (+ <option key={inst.id} value={inst.id}>{inst.name} ({inst.baseUrl})</option>+ ))}+ </select>+ </div>++ <div className="relative">+ <label htmlFor="app-jira-project" className="block text-sm text-gray-400 mb-1">Project Key</label>+ {loadingProjects ? (+ <div className="text-xs text-gray-500">Loading projects...</div>+ ) : projects.length > 0 ? (+ <div>+ <input+ id="app-jira-project"+ type="text"+ value={projectDropdownOpen ? projectSearch : (+ form.projectKey ? `${form.projectKey} - ${selectedProjectName}` : ''+ )}+ onChange={e => {+ setProjectSearch(e.target.value);+ if (!projectDropdownOpen) setProjectDropdownOpen(true);+ }}+ onFocus={() => {+ setProjectDropdownOpen(true);+ setProjectSearch('');+ }}+ onBlur={() => setTimeout(() => setProjectDropdownOpen(false), 150)}+ className={INPUT_CLASS}+ placeholder="Search projects..."+ />+ {form.projectKey && !projectDropdownOpen && (+ <button+ type="button"+ onClick={() => selectProject('')}+ aria-label="Clear JIRA project"+ className="absolute right-2 top-8 text-gray-500 hover:text-white text-sm"+ >+ x+ </button>+ )}+ {projectDropdownOpen && (+ <div className="absolute z-50 w-full mt-1 bg-port-bg border border-port-border rounded-lg max-h-48 overflow-auto shadow-lg">+ {filteredProjects.map(proj => (+ <button+ key={proj.key}+ type="button"+ onMouseDown={e => {+ e.preventDefault();+ selectProject(proj.key);+ setProjectDropdownOpen(false);+ setProjectSearch('');+ }}+ className={`w-full text-left px-3 py-2 text-sm hover:bg-port-accent/20 ${+ form.projectKey === proj.key ? 'bg-port-accent/10 text-port-accent' : 'text-white'+ }`}+ >+ <span className="font-mono">{proj.key}</span>+ <span className="text-gray-400 ml-2">{proj.name}</span>+ </button>+ ))}+ {filteredProjects.length === 0 && (+ <div className="px-3 py-2 text-sm text-gray-500">No matching projects</div>+ )}+ </div>+ )}+ </div>+ ) : (+ <input+ id="app-jira-project"+ type="text"+ value={form.projectKey}+ onChange={e => setForm({ ...form, projectKey: e.target.value })}+ className={INPUT_CLASS}+ placeholder="e.g. PROJ"+ />+ )}+ </div>++ <div>+ <label htmlFor="app-jira-board" className="block text-sm text-gray-400 mb-1">Board</label>+ {!form.projectKey ? (+ <div className="text-xs text-gray-500">Select a project to detect its boards.</div>+ ) : loadingBoards ? (+ <div className="text-xs text-gray-500">Detecting boards…</div>+ ) : boards.length > 0 ? (+ <>+ <select+ id="app-jira-board"+ value={form.boardId}+ onChange={e => setForm({ ...form, boardId: e.target.value })}+ className={INPUT_CLASS}+ >+ <option value="">Select board...</option>+ {boards.map(b => (+ <option key={b.id} value={String(b.id)}>{b.id} — {b.name} ({b.type})</option>+ ))}+ {boardIsStale && (+ <option value={form.boardId}>{form.boardId} — (not in this project)</option>+ )}+ </select>+ {boardIsStale ? (+ <p className="text-xs text-port-warning mt-1">⚠ Saved board {form.boardId} isn't among this project's boards — pick a current one.</p>+ ) : form.boardId && (+ <p className="text-xs text-gray-500 mt-1">+ {activeSprint ? `Active sprint: ${activeSprint.name}` : 'No active sprint on this board.'}+ </p>+ )}+ </>+ ) : (+ <>+ <input+ id="app-jira-board"+ type="text"+ value={form.boardId}+ onChange={e => setForm({ ...form, boardId: e.target.value })}+ className={INPUT_CLASS}+ placeholder="e.g. 1294 (from JIRA board URL rapidView param)"+ />+ <p className="text-xs text-gray-500 mt-1">Couldn't auto-detect boards — enter the id manually (board URL <span className="font-mono">rapidView</span> param).</p>+ </>+ )}+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor="app-jira-issue-type" className="block text-sm text-gray-400 mb-1">Issue Type</label>+ <input+ id="app-jira-issue-type"+ type="text"+ value={form.issueType}+ onChange={e => setForm({ ...form, issueType: e.target.value })}+ className={INPUT_CLASS}+ placeholder="Task"+ />+ </div>+ <div>+ <label htmlFor="app-jira-assignee" className="block text-sm text-gray-400 mb-1">Assignee</label>+ <input+ id="app-jira-assignee"+ type="text"+ value={form.assignee}+ onChange={e => setForm({ ...form, assignee: e.target.value })}+ className={INPUT_CLASS}+ placeholder="Optional"+ />+ </div>+ </div>++ <div>+ <label htmlFor="app-jira-labels" className="block text-sm text-gray-400 mb-1">Labels (comma-separated)</label>+ <input+ id="app-jira-labels"+ type="text"+ value={form.labels}+ onChange={e => setForm({ ...form, labels: e.target.value })}+ className={INPUT_CLASS}+ placeholder="e.g. cos-auto, feature"+ />+ </div>++ <div className="relative">+ <label htmlFor="app-jira-epic" className="block text-sm text-gray-400 mb-1">Epic Key</label>+ <input+ id="app-jira-epic"+ type="text"+ value={form.epicKey}+ onChange={e => setForm({ ...form, epicKey: e.target.value })}+ onFocus={() => setEpicDropdownOpen(true)}+ onBlur={() => setTimeout(() => setEpicDropdownOpen(false), 150)}+ className={INPUT_CLASS}+ placeholder="e.g. PROJ-100, or type a name to search"+ />+ {epicDropdownOpen && epicResults.length > 0 && (+ <div className="absolute z-50 w-full mt-1 bg-port-bg border border-port-border rounded-lg max-h-48 overflow-auto shadow-lg">+ {epicResults.map(ep => (+ <button+ key={ep.key}+ type="button"+ onMouseDown={e => {+ e.preventDefault();+ setForm({ ...form, epicKey: ep.key });+ setEpicDropdownOpen(false);+ }}+ className="w-full text-left px-3 py-2 text-sm hover:bg-port-accent/20 text-white"+ >+ <span className="font-mono">{ep.key}</span>+ <span className="text-gray-400 ml-2">{ep.summary}</span>+ </button>+ ))}+ </div>+ )}+ {epicValidation.state !== 'idle' && (+ <p className={`text-xs mt-1 ${+ epicValidation.state === 'ok' ? 'text-port-success'+ : epicValidation.state === 'checking' ? 'text-gray-500'+ : 'text-port-warning'+ }`}>+ {epicValidation.state === 'checking' && 'Checking epic…'}+ {epicValidation.state === 'ok' && `✓ ${epicValidation.issue.key} · ${epicValidation.issue.summary}`}+ {epicValidation.state === 'wrongtype' && `⚠ ${epicValidation.issue.key} is a ${epicValidation.issue.issueType}, not an Epic`}+ {epicValidation.state === 'stale' && `⚠ ${form.epicKey} doesn't resolve on this instance`}+ </p>+ )}+ </div>++ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={form.createPR}+ onChange={e => setForm({ ...form, createPR: e.target.checked })}+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <span className="text-sm text-white">Create Pull Request on completion</span>+ </label>+ </>+ )+ )}++ <button+ type="submit"+ disabled={saving}+ className="px-4 py-2 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 border border-port-border rounded-lg text-sm flex items-center gap-2 disabled:opacity-50 transition-colors"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {saving ? 'Saving…' : 'Save JIRA Settings'}+ </button>+ </form>+ );+}diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex 6ad788db01..d4f471172d 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -5,6 +5,7 @@ import LayeredIntelligenceOutcomes from './LayeredIntelligenceOutcomes';import { filterSelectableModels } from '../../utils/providers';import { timeAgo } from '../../utils/formatters';import { formatLiReason, liReasonTone } from '../../utils/layeredIntelligenceReasons';+import { INPUT_CLASS } from './constants';// The self-improvement loop's per-app config surface. Field set mirrors the// server schema (server/lib/validation.js `layeredIntelligenceConfigSchema`)@@ -35,8 +36,6 @@ export const LI_SCOPES = [{ id: 'portos-self', label: 'PortOS self', portosOnly: true, hint: 'Improve PortOS itself (PortOS only)' }];-const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden';-// Common cadences for the interval select. Values are milliseconds; the schema// floor is 60_000 (1 minute). A stored non-preset value renders as "Custom".export const LI_INTERVAL_PRESETS = [diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex 7d0e53a298..283e184b6c 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -1,5 +1,10 @@export const NON_PM2_TYPES = new Set(['ios-native', 'macos-native', 'xcode', 'swift']);+// The app-config text input / select styling. Shared so a restyle of these forms+// is one edit rather than one per config surface. Must stay a COMPLETE literal+// class string — Tailwind only sees classes it can read in source.+export const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden';+// Mirrors DESKTOP_TYPES in server/services/streamingDetect.js — app types that run// a GUI/desktop process with no HTTP port (a game binary). Kept in sync by hand// (a parity test asserts the two Sets match); the server stays the source of truth@@ -58,6 +63,9 @@ export const WORK_TRACKER_LABELS = Object.fromEntries(export const workItemNoun = (tracker) =>tracker === 'jira' ? 'ticket' : (tracker === 'github' || tracker === 'gitlab') ? 'issue' : 'item';+// Overview first, then alphabetical. Every id is a real route segment+// (`/apps/:appId/:tab`) so each tab is linkable, bookmarkable, and reachable+// from ⌘K — see the routing rules in client/src/CLAUDE.md.export const APP_DETAIL_TABS = [{ id: 'overview', label: 'Overview' },{ id: 'automation', label: 'Automation' },@@ -65,6 +73,8 @@ export const APP_DETAIL_TABS = [{ id: 'documents', label: 'Documents' },{ id: 'git', label: 'Git' },{ id: 'gsd', label: 'GSD' },+ { id: 'issues', label: 'Issues' },+ { id: 'jira', label: 'JIRA' },{ id: 'processes', label: 'Processes' },{ id: 'references', label: 'References' },{ id: 'tasks', label: 'Tasks' },diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsxnew file mode 100644index 0000000000..a33e11fcc7--- /dev/null+++ b/client/src/components/apps/tabs/IssuesTab.jsx@@ -0,0 +1,305 @@+import { useState, useEffect, useCallback, useMemo, useId } from 'react';+import { Link } from 'react-router';+import {+ AlertTriangle, ChevronDown, ChevronRight, CircleDot, ExternalLink,+ Loader2, RefreshCw, Rocket, Search, User+} from 'lucide-react';+import BrailleSpinner from '../../BrailleSpinner';+import Banner from '../../ui/Banner';+import Pill from '../../ui/Pill';+import toast from '../../ui/Toast';+import * as api from '../../../services/api';+import { timeAgo } from '../../../utils/formatters';++const FORGE_LABEL = { github: 'GitHub', gitlab: 'GitLab' };++// Why the forge returned nothing, in the user's terms. Sentinel-aware: a+// definitive "no open issues" and a failed probe are different sentences, so an+// unreachable CLI can never read as an empty tracker.+const EMPTY_REASONS = {+ 'no-repo-path': 'This app has no repo path configured.',+ 'unsupported-forge': 'This app\'s git origin isn\'t GitHub or GitLab, so there are no forge issues to list.',+ 'tracker-not-a-forge': 'This app\'s Work Tracker isn\'t a forge issue tracker, so a claim here wouldn\'t touch forge issues. Change it under Edit App → Workflow.',+ 'tracker-forge-mismatch': 'This app\'s Work Tracker is pinned to a different forge than its git origin, so neither list would match what a claim runs against. Reconcile them under Edit App → Workflow.',+ 'no-open-issues': 'No open issues on this tracker.'+};++/**+ * Label chips carry the forge's own color, which is arbitrary per-repo data —+ * so it can't be a Tailwind class (those must be literal strings in source).+ * Render it as a tinted chip via inline style: the color for text and border,+ * a low-alpha wash of it for the background, which stays legible on the dark+ * surface for the full hue range. A label with no color falls back to `muted`.+ */+function LabelChip({ label }) {+ return (+ <Pill+ size="xs"+ tone={label.color ? 'bare' : 'muted'}+ title={label.description || undefined}+ style={label.color ? {+ color: label.color,+ borderColor: `${label.color}66`,+ backgroundColor: `${label.color}1a`+ } : undefined}+ >+ {label.name}+ </Pill>+ );+}++/**+ * Open issues from the app's forge (GitHub or GitLab, resolved from the git+ * `origin` remote), each with its labels, assignees, expandable description, and+ * a one-click "Claim with CoS agent" button.+ *+ * Claiming queues the SAME `/do:next` task the Agent Operations panel does,+ * pinned to this issue via `target` — so the run honors the app's configured+ * Work Tracker, worktree, and PR settings instead of a parallel code path.+ */+export default function IssuesTab({ appId, appName }) {+ const searchId = useId();+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState('');+ const [query, setQuery] = useState('');+ const [expanded, setExpanded] = useState(() => new Set());+ // Per-issue claim lifecycle: 'queuing' while the POST is in flight, 'queued'+ // once the CoS task exists. Keyed by issue number so one claim can't disable+ // every other row's button.+ const [claims, setClaims] = useState({});++ const load = useCallback(async () => {+ setLoading(true);+ setError('');+ const result = await api.getAppIssues(appId).catch(err => {+ setError(err?.message || 'Failed to load issues');+ return null;+ });+ setLoading(false);+ if (result) setData(result);+ }, [appId]);++ useEffect(() => { load(); }, [load]);++ // Lowercase each issue's searchable text ONCE per fetch, not once per+ // keystroke: bodies are capped at 8000 chars and the list at 200 issues, so+ // re-deriving inside the filter churned up to 1.6 MB of throwaway strings on+ // every character typed. Digits are case-invariant, so the issue number folds+ // into the same haystack.+ const haystacks = useMemo(() => (data?.issues || []).map(issue => ({+ issue,+ hay: [+ String(issue.number),+ issue.title,+ issue.body || '',+ issue.labels.map(l => l.name).join(' '),+ issue.assignees.join(' ')+ ].join('\n').toLowerCase()+ })), [data]);++ const issues = useMemo(() => {+ const q = query.trim().toLowerCase();+ const rows = q ? haystacks.filter(h => h.hay.includes(q)) : haystacks;+ return rows.map(h => h.issue);+ }, [haystacks, query]);++ const total = data?.issues?.length ?? 0;++ const toggleExpanded = (number) => setExpanded(prev => {+ const next = new Set(prev);+ if (next.has(number)) next.delete(number); else next.add(number);+ return next;+ });++ const handleClaim = async (issue) => {+ setClaims(prev => ({ ...prev, [issue.number]: 'queuing' }));+ const result = await api.createSlashdoTask('next', appId, { target: String(issue.number) }, { silent: true })+ .catch(err => {+ toast.error(err?.message || `Failed to queue a claim for #${issue.number}`);+ return null;+ });+ if (!result) {+ setClaims(prev => {+ const next = { ...prev };+ delete next[issue.number];+ return next;+ });+ return;+ }+ setClaims(prev => ({ ...prev, [issue.number]: 'queued' }));+ toast.success(`Queued a CoS agent to claim #${issue.number}`);+ };++ if (loading && !data) return <BrailleSpinner text="Loading issues" />;++ const forgeLabel = FORGE_LABEL[data?.forge] || 'Issues';+ // A transient failure keeps the "couldn't ask" framing — never the lie that+ // the tracker is empty.+ const unavailable = data?.transient === true;++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center gap-3">+ <h3 className="text-lg font-semibold text-white">+ {forgeLabel} Issues+ {data?.fullName && <span className="ml-2 text-xs font-mono text-gray-500">{data.fullName}</span>}+ </h3>+ {total > 0 && (+ <span className="text-xs text-gray-500">+ {issues.length === total ? `${total} open` : `${issues.length} of ${total} open`}+ </span>+ )}+ <div className="relative ml-auto">+ <label htmlFor={searchId} className="sr-only">Filter issues</label>+ <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" />+ <input+ id={searchId}+ type="search"+ value={query}+ onChange={e => setQuery(e.target.value)}+ placeholder="Filter by title, label, assignee…"+ className="w-full sm:w-72 pl-8 pr-3 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"+ />+ </div>+ <button+ onClick={load}+ disabled={loading}+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"+ >+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} /> Refresh+ </button>+ </div>++ {error && (+ <Banner tone="error" size="md" icon={AlertTriangle}>+ Couldn't load issues — {error}+ </Banner>+ )}++ {!error && unavailable && (+ <Banner tone="warning" size="md" icon={AlertTriangle}>+ Couldn't reach {forgeLabel} ({data.reason})+ {data.remedy ? ` — ${data.remedy}.` : ' — retry once the CLI is authenticated.'}+ </Banner>+ )}++ {!error && !unavailable && total === 0 && (+ <div className="px-3 py-2 text-sm text-gray-500 bg-port-card border border-port-border rounded-lg">+ {EMPTY_REASONS[data?.reason] ?? EMPTY_REASONS['no-open-issues']}+ </div>+ )}++ {/* A failed REFRESH deliberately shows the error banner above AND the last+ good list below — blanking issues the user was reading is worse than+ showing them alongside a "couldn't refresh" notice. */}+ {issues.length === 0 && total > 0 && (+ <div className="px-3 py-2 text-sm text-gray-500 bg-port-card border border-port-border rounded-lg">+ No open issues match “{query}”.+ </div>+ )}++ {issues.length > 0 && (+ <div className="border border-port-border rounded-lg divide-y divide-port-border overflow-hidden">+ {issues.map(issue => {+ const isOpen = expanded.has(issue.number);+ const claimState = claims[issue.number];+ return (+ <div key={issue.number} className="bg-port-card">+ <div className="flex flex-col sm:flex-row sm:items-start gap-3 p-3">+ <button+ onClick={() => toggleExpanded(issue.number)}+ aria-expanded={isOpen}+ aria-label={`${isOpen ? 'Collapse' : 'Expand'} description for issue ${issue.number}`}+ className="hidden sm:flex text-gray-500 hover:text-white transition-colors mt-0.5 shrink-0"+ >+ {isOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ </button>++ <div className="flex-1 min-w-0">+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <CircleDot size={14} className="text-port-success shrink-0 self-center" />+ <span className="text-xs font-mono text-gray-500">#{issue.number}</span>+ <button+ onClick={() => toggleExpanded(issue.number)}+ aria-expanded={isOpen}+ className="text-sm text-white text-left hover:text-port-accent transition-colors break-words"+ >+ {issue.title || '(no title)'}+ </button>+ {issue.url && (+ <a+ href={issue.url}+ target="_blank"+ rel="noreferrer"+ aria-label={`Open issue ${issue.number} on ${forgeLabel}`}+ className="text-gray-500 hover:text-port-accent transition-colors self-center"+ >+ <ExternalLink size={12} />+ </a>+ )}+ </div>++ {issue.labels.length > 0 && (+ <div className="flex flex-wrap gap-1 mt-1.5">+ {issue.labels.map(l => <LabelChip key={l.name} label={l} />)}+ </div>+ )}++ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1.5 text-xs text-gray-500">+ {issue.author && <span>opened by {issue.author}</span>}+ {issue.updatedAt && <span>updated {timeAgo(issue.updatedAt)}</span>}+ {issue.milestone && <span className="text-cyan-400">{issue.milestone}</span>}+ {issue.assignees.length > 0 ? (+ <span className="flex items-center gap-1 text-gray-300">+ <User size={12} /> {issue.assignees.join(', ')}+ </span>+ ) : (+ <span className="italic">unassigned</span>+ )}+ </div>+ </div>++ <div className="shrink-0">+ {claimState === 'queued' ? (+ <Link+ to="/cos/agents"+ className="px-3 py-1.5 bg-port-success/20 text-port-success hover:bg-port-success/30 border border-port-border rounded-lg text-xs flex items-center gap-1.5 transition-colors"+ >+ <Rocket size={14} /> Queued — view+ </Link>+ ) : (+ <button+ onClick={() => handleClaim(issue)}+ disabled={claimState === 'queuing'}+ title={`Queue a CoS agent to claim issue #${issue.number} for ${appName}`}+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent enabled:hover:bg-port-accent/30 border border-port-border rounded-lg text-xs flex items-center gap-1.5 disabled:opacity-50 transition-colors"+ >+ {claimState === 'queuing'+ ? <Loader2 size={14} className="animate-spin" />+ : <Rocket size={14} />}+ {claimState === 'queuing' ? 'Queuing…' : 'Claim'}+ </button>+ )}+ </div>+ </div>++ {isOpen && (+ <div className="px-3 pb-3 sm:pl-10">+ {issue.body?.trim() ? (+ <pre className="text-xs text-gray-300 whitespace-pre-wrap break-words font-sans bg-port-bg border border-port-border rounded-lg p-3 max-h-96 overflow-auto">+ {issue.body}+ </pre>+ ) : (+ <p className="text-xs text-gray-500 italic">No description.</p>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/apps/tabs/IssuesTab.test.jsx b/client/src/components/apps/tabs/IssuesTab.test.jsxnew file mode 100644index 0000000000..a771bb8bd2--- /dev/null+++ b/client/src/components/apps/tabs/IssuesTab.test.jsx@@ -0,0 +1,145 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../../../services/api', () => ({+ getAppIssues: vi.fn(),+ createSlashdoTask: vi.fn(),+}));++import * as api from '../../../services/api';+import IssuesTab from './IssuesTab';++const ISSUE = {+ number: 42,+ title: 'Crash on save',+ body: 'Repro: open the editor and hit save.',+ url: 'https://github.com/acme/widget/issues/42',+ state: 'open',+ labels: [{ name: 'bug', color: '#d73a4a', description: 'Something is broken' }],+ assignees: ['alice'],+ author: 'carol',+ milestone: null,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-02T00:00:00Z',+};++const okPayload = (issues) => ({+ forge: 'github',+ fullName: 'acme/widget',+ issues,+ reason: issues.length ? 'ok' : 'no-open-issues',+ transient: false,+ remedy: null,+});++const renderTab = () => render(+ <MemoryRouter>+ <IssuesTab appId="app-1" appName="Widget" />+ </MemoryRouter>+);++beforeEach(() => {+ api.getAppIssues.mockResolvedValue(okPayload([ISSUE]));+ api.createSlashdoTask.mockResolvedValue({ id: 'task-1' });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('IssuesTab', () => {+ it('auto-queries open issues on mount and renders title, labels, and assignees', async () => {+ renderTab();++ expect(await screen.findByText('Crash on save')).toBeInTheDocument();+ expect(api.getAppIssues).toHaveBeenCalledWith('app-1');+ expect(screen.getByText('#42')).toBeInTheDocument();+ expect(screen.getByText('bug')).toBeInTheDocument();+ expect(screen.getByText(/alice/)).toBeInTheDocument();+ expect(screen.getByText('acme/widget')).toBeInTheDocument();+ });++ it('keeps the description collapsed until the user expands it', async () => {+ renderTab();++ const title = await screen.findByText('Crash on save');+ expect(screen.queryByText(/Repro: open the editor/)).not.toBeInTheDocument();++ fireEvent.click(title);+ expect(await screen.findByText(/Repro: open the editor/)).toBeInTheDocument();++ fireEvent.click(title);+ await waitFor(() => expect(screen.queryByText(/Repro: open the editor/)).not.toBeInTheDocument());+ });++ it('claims an issue by queuing the /do:next task pinned to that issue number', async () => {+ renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));++ await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledWith(+ 'next', 'app-1', { target: '42' }, { silent: true }+ ));+ expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();+ });++ it('re-enables the Claim button when queuing fails, instead of stranding it', async () => {+ api.createSlashdoTask.mockRejectedValue(new Error('CoS is not running'));+ renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));++ await waitFor(() => expect(screen.getByRole('button', { name: /Claim/ })).toBeEnabled());+ expect(screen.queryByRole('link', { name: /Queued/ })).not.toBeInTheDocument();+ });++ it('filters the list by title, label, or assignee', async () => {+ api.getAppIssues.mockResolvedValue(okPayload([+ ISSUE,+ { ...ISSUE, number: 43, title: 'Add CSV export', labels: [], assignees: [] },+ ]));+ renderTab();++ await screen.findByText('Crash on save');+ fireEvent.change(screen.getByLabelText('Filter issues'), { target: { value: 'csv' } });++ expect(screen.getByText('Add CSV export')).toBeInTheDocument();+ expect(screen.queryByText('Crash on save')).not.toBeInTheDocument();+ });++ it('says "couldn\'t reach" for a transient failure — never "no open issues"', async () => {+ api.getAppIssues.mockResolvedValue({+ forge: 'github', fullName: 'acme/widget', issues: [],+ reason: 'gh-unauthenticated', transient: true, remedy: 'run gh auth login',+ });+ renderTab();++ expect(await screen.findByText(/Couldn't reach GitHub/)).toBeInTheDocument();+ expect(screen.getByText(/run gh auth login/)).toBeInTheDocument();+ expect(screen.queryByText(/No open issues on this tracker/)).not.toBeInTheDocument();+ });++ it('explains a non-forge origin instead of showing an empty list', async () => {+ api.getAppIssues.mockResolvedValue({+ forge: null, fullName: null, issues: [], reason: 'unsupported-forge', transient: false, remedy: null,+ });+ renderTab();++ expect(await screen.findByText(/isn't GitHub or GitLab/)).toBeInTheDocument();+ });++ it('points at the Work Tracker setting when the tracker owns no forge issues', async () => {+ // The server refuses to list issues a Claim here would not actually touch.+ api.getAppIssues.mockResolvedValue({+ forge: null, tracker: 'jira', fullName: null, issues: [],+ reason: 'tracker-not-a-forge', transient: false, remedy: null,+ });+ renderTab();++ expect(await screen.findByText(/Work Tracker isn't a forge issue tracker/)).toBeInTheDocument();+ // No issues ⇒ no Claim button that would queue a mis-routed run.+ expect(screen.queryByRole('button', { name: /Claim/ })).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/apps/tabs/JiraTab.jsx b/client/src/components/apps/tabs/JiraTab.jsxnew file mode 100644index 0000000000..b15ab5b640--- /dev/null+++ b/client/src/components/apps/tabs/JiraTab.jsx@@ -0,0 +1,96 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import { AlertTriangle, RefreshCw } from 'lucide-react';+import BrailleSpinner from '../../BrailleSpinner';+import KanbanBoard from '../../KanbanBoard';+import JiraConfigPanel from '../JiraConfigPanel';+import * as api from '../../../services/api';++/**+ * Everything JIRA for one app: the integration config and the sprint Kanban+ * board it drives. Both used to live elsewhere (the config inside the Edit App+ * drawer, the board buried in the Overview tab) — they belong together, and the+ * board needs the full page width the drawer never had.+ */+export default function JiraTab({ app, onRefresh }) {+ const [tickets, setTickets] = useState(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState(null);+ const requestRef = useRef(0);++ const configured = !!(app?.jira?.enabled && app.jira.instanceId && app.jira.projectKey);++ // Same sentinel contract as the /apps list (#3437): a failed fetch records a+ // message instead of collapsing into `[]`, which read as "you have no sprint+ // tickets" and offered no way to retry.+ const loadSprintTickets = useCallback(() => {+ if (!configured) return;+ // Generation guard: a Retry (or a JIRA-config change) while an earlier+ // request is still open must not let the older response land last.+ const generation = requestRef.current + 1;+ requestRef.current = generation;+ const isCurrent = () => requestRef.current === generation;++ setLoading(true);+ setError(null);+ api.getMySprintTickets(app.jira.instanceId, app.jira.projectKey, { silent: true })+ .then(rows => { if (isCurrent()) setTickets(Array.isArray(rows) ? rows : []); })+ .catch(err => { if (isCurrent()) setError(err?.message || 'Request failed'); })+ .finally(() => { if (isCurrent()) setLoading(false); });+ }, [configured, app?.jira?.instanceId, app?.jira?.projectKey]);++ useEffect(() => { loadSprintTickets(); }, [loadSprintTickets]);++ return (+ <div className="space-y-6">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">JIRA Configuration</div>+ {/* Re-seed the form when the underlying record actually changes.+ AppDetailView refetches `app` on every `apps:changed` socket event+ (a peer sync, a second browser tab, the Edit App drawer saving), and+ the panel seeds its state from `app.jira` in a useState initializer —+ without this key it would keep its first-render snapshot and write+ those stale values back on the next Save, which is the exact clobber+ splitting the config out was meant to end. Keyed on `updatedAt`, not+ the object, so an identical refetch doesn't discard an in-progress edit. */}+ <JiraConfigPanel key={app.updatedAt || app.id} app={app} onSaved={onRefresh} />+ </div>++ {configured && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">My Sprint Tickets</div>+ {loading ? (+ <div className="flex items-center gap-2 px-3 py-2 text-sm text-gray-400">+ <BrailleSpinner text="" />+ <span>Loading tickets...</span>+ </div>+ ) : error ? (+ <div className="flex flex-wrap items-center gap-3 px-3 py-2 bg-port-card border border-port-error/30 rounded-lg max-w-5xl">+ <AlertTriangle size={16} className="text-port-error shrink-0" />+ <span className="text-sm text-gray-300 min-w-0">Couldn't load sprint tickets — {error}</span>+ <button+ onClick={loadSprintTickets}+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1"+ aria-label={`Retry loading sprint tickets for ${app.name}`}+ >+ <RefreshCw size={14} /> Retry+ </button>+ </div>+ ) : tickets?.length > 0 ? (+ <KanbanBoard+ tickets={tickets}+ instanceId={app.jira.instanceId}+ onTicketsChange={setTickets}+ appId={app.id}+ projectKey={app.jira.projectKey}+ boardId={app.jira.boardId}+ />+ ) : (+ <div className="px-3 py-2 text-sm text-gray-500 bg-port-card border border-port-border rounded-lg max-w-5xl">+ No tickets assigned to you in the current sprint+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/apps/tabs/JiraTab.test.jsx b/client/src/components/apps/tabs/JiraTab.test.jsxnew file mode 100644index 0000000000..d0e50068c4--- /dev/null+++ b/client/src/components/apps/tabs/JiraTab.test.jsx@@ -0,0 +1,92 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../../../services/api', () => ({+ getJiraInstances: vi.fn(),+ getJiraProjects: vi.fn(),+ getJiraBoards: vi.fn(),+ getJiraBoardSprints: vi.fn(),+ getJiraIssue: vi.fn(),+ searchJiraEpics: vi.fn(),+ getMySprintTickets: vi.fn(),+ updateApp: vi.fn(),+}));++// The Kanban board is exercised by its own suite; stub it so this test is about+// the tab's composition (config + board) rather than the board's internals.+vi.mock('../../KanbanBoard', () => ({+ default: ({ tickets }) => <div data-testid="kanban">{tickets.length} tickets</div>,+}));++import * as api from '../../../services/api';+import JiraTab from './JiraTab';++const APP = {+ id: 'app-1',+ name: 'Widget',+ jira: { enabled: true, instanceId: 'inst-1', projectKey: 'PROJ', boardId: '12', issueType: 'Task', labels: ['cos-auto'], createPR: true },+};++const renderTab = (app = APP, onRefresh = () => {}) => render(+ <MemoryRouter>+ <JiraTab app={app} onRefresh={onRefresh} />+ </MemoryRouter>+);++beforeEach(() => {+ api.getJiraInstances.mockResolvedValue({ instances: { 'inst-1': { id: 'inst-1', name: 'Acme', baseUrl: 'https://acme.example.com' } } });+ api.getJiraProjects.mockResolvedValue([{ key: 'PROJ', name: 'Project' }]);+ api.getJiraBoards.mockResolvedValue([{ id: 12, name: 'Board', type: 'scrum' }]);+ api.getJiraBoardSprints.mockResolvedValue([{ name: 'Sprint 3' }]);+ api.getMySprintTickets.mockResolvedValue([{ key: 'PROJ-1', summary: 'Do a thing', status: 'To Do', statusCategory: 'To Do' }]);+ api.updateApp.mockResolvedValue({ ...APP });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('JiraTab', () => {+ it('renders the JIRA config form and the sprint board together', async () => {+ renderTab();++ expect(await screen.findByLabelText('JIRA Instance')).toBeInTheDocument();+ expect(await screen.findByTestId('kanban')).toHaveTextContent('1 tickets');+ expect(api.getMySprintTickets).toHaveBeenCalledWith('inst-1', 'PROJ', { silent: true });+ });++ it('saves ONLY the jira slice, so the PUT cannot touch other app fields', async () => {+ const onRefresh = vi.fn();+ renderTab(APP, onRefresh);++ fireEvent.click(await screen.findByRole('button', { name: /Save JIRA Settings/ }));++ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());+ const [id, payload, options] = api.updateApp.mock.calls[0];+ expect(id).toBe('app-1');+ expect(Object.keys(payload)).toEqual(['jira']);+ expect(payload.jira).toMatchObject({ enabled: true, instanceId: 'inst-1', projectKey: 'PROJ', boardId: '12', labels: ['cos-auto'] });+ // Custom error UI lives in the panel, so the helper must not also toast.+ expect(options).toEqual({ silent: true });+ await waitFor(() => expect(onRefresh).toHaveBeenCalled());+ });++ it('collapses to just the config form when JIRA is not configured', async () => {+ renderTab({ id: 'app-2', name: 'No JIRA' });++ expect(await screen.findByText('Enable JIRA Integration')).toBeInTheDocument();+ expect(screen.queryByTestId('kanban')).not.toBeInTheDocument();+ expect(api.getMySprintTickets).not.toHaveBeenCalled();+ });++ it('says "couldn\'t load" with a retry when the sprint fetch fails', async () => {+ api.getMySprintTickets.mockRejectedValue(new Error('JIRA unreachable'));+ renderTab();++ expect(await screen.findByText(/Couldn't load sprint tickets — JIRA unreachable/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Retry loading sprint tickets/ })).toBeInTheDocument();+ expect(screen.queryByText(/No tickets assigned to you/)).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsxindex 430e8e0de9..c485fa320b 100644--- a/client/src/components/apps/tabs/OverviewTab.jsx+++ b/client/src/components/apps/tabs/OverviewTab.jsx@@ -1,10 +1,8 @@-import { useState, useEffect, useMemo, useCallback, useRef } from 'react';+import { useState, useEffect, useMemo } from 'react';import { Link } from 'react-router';-import { FolderOpen, Gamepad2, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Ticket, Download, Tag, AlertTriangle, Rocket, Camera, Image, Sparkles } from 'lucide-react';+import { FolderOpen, Gamepad2, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Download, Tag, AlertTriangle, Rocket, Camera, Image, Sparkles } from 'lucide-react';import toast from '../../ui/Toast';import { NON_PM2_TYPES } from '../constants';-import BrailleSpinner from '../../BrailleSpinner';-import KanbanBoard from '../../KanbanBoard';import ActivityLog from '../ActivityLog';import SlashDoPanel from '../SlashDoPanel';import Banner from '../../ui/Banner';@@ -21,10 +19,6 @@ const SCRIPT_ICONS = {export default function OverviewTab({ app, onRefresh }) {const [refreshingConfig, setRefreshingConfig] = useState(false);const [archiving, setArchiving] = useState(false);- const [jiraTickets, setJiraTickets] = useState(null);- const [loadingTickets, setLoadingTickets] = useState(false);- const [ticketError, setTicketError] = useState(null);- const ticketRequestRef = useRef(0);const [installingScripts, setInstallingScripts] = useState(false);const [detectingIcon, setDetectingIcon] = useState(false);// Reverse lookup (#2991): sprite records that publish assets into this app.@@ -37,27 +31,6 @@ export default function OverviewTab({ app, onRefresh }) {const updating = isOperating && operationType === 'update';const standardizing = isOperating && operationType === 'standardize';- // Same sentinel contract as the /apps list (#3437): a failed fetch records a- // message instead of collapsing into `[]`, which read as "you have no sprint- // tickets" and offered no way to retry.- const loadSprintTickets = useCallback(() => {- if (!app?.jira?.enabled || !app.jira.instanceId || !app.jira.projectKey) return;- // Generation guard: a Retry (or a JIRA-config change) while an earlier- // request is still open must not let the older response land last.- const generation = ticketRequestRef.current + 1;- ticketRequestRef.current = generation;- const isCurrent = () => ticketRequestRef.current === generation;-- setLoadingTickets(true);- setTicketError(null);- api.getMySprintTickets(app.jira.instanceId, app.jira.projectKey, { silent: true })- .then(tickets => { if (isCurrent()) setJiraTickets(Array.isArray(tickets) ? tickets : []); })- .catch(err => { if (isCurrent()) setTicketError(err?.message || 'Request failed'); })- .finally(() => { if (isCurrent()) setLoadingTickets(false); });- }, [app?.jira?.enabled, app?.jira?.instanceId, app?.jira?.projectKey]);-- useEffect(() => { loadSprintTickets(); }, [loadSprintTickets]);-// Load the sprite records bound to this app (empty for an app with none).useEffect(() => {if (!app?.id) return;@@ -130,7 +103,9 @@ export default function OverviewTab({ app, onRefresh }) {return (<div className="space-y-6">- {/* Readable details/config zone — capped width so key/value pairs stay legible */}+ {/* Capped width so key/value pairs stay legible. (JIRA config + the sprint+ Kanban board, which needed the full page width, now live on the app's+ own JIRA tab.) */}<div className="space-y-6 max-w-5xl">{/* Details Grid */}<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">@@ -295,56 +270,6 @@ export default function OverviewTab({ app, onRefresh }) {</div>)}- {/* JIRA Integration */}- {app.jira?.enabled && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">JIRA Integration</div>- <div className="flex flex-wrap items-center gap-3 px-3 py-2 bg-port-card border border-port-border rounded-lg">- <Ticket size={16} className="text-blue-400 shrink-0" />- <span className="text-sm text-white font-mono">{app.jira.projectKey || '-'}</span>- {app.jira.issueType && <span className="text-xs text-gray-400">{app.jira.issueType}</span>}- {app.jira.createPR !== false && <span className="text-xs text-port-success">+ PR</span>}- {app.jira.labels?.length > 0 && (- <span className="text-xs text-cyan-400">{app.jira.labels.join(', ')}</span>- )}- </div>- </div>- )}- </div>{/* end readable details/config zone */}-- {/* My Sprint Tickets — full width so the Kanban lifecycle isn't clipped */}- {app.jira?.enabled && app.jira.instanceId && app.jira.projectKey && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">My Sprint Tickets</div>- {loadingTickets ? (- <div className="flex items-center gap-2 px-3 py-2 text-sm text-gray-400">- <BrailleSpinner text="" />- <span>Loading tickets...</span>- </div>- ) : ticketError ? (- <div className="flex flex-wrap items-center gap-3 px-3 py-2 bg-port-card border border-port-error/30 rounded-lg max-w-5xl">- <AlertTriangle size={16} className="text-port-error shrink-0" />- <span className="text-sm text-gray-300 min-w-0">Couldn't load sprint tickets — {ticketError}</span>- <button- onClick={loadSprintTickets}- className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1"- aria-label={`Retry loading sprint tickets for ${app.name}`}- >- <RefreshCw size={14} /> Retry- </button>- </div>- ) : jiraTickets?.length > 0 ? (- <KanbanBoard tickets={jiraTickets} instanceId={app.jira?.instanceId} onTicketsChange={setJiraTickets} appId={app.id} projectKey={app.jira?.projectKey} boardId={app.jira?.boardId} />- ) : (- <div className="px-3 py-2 text-sm text-gray-500 bg-port-card border border-port-border rounded-lg max-w-5xl">- No tickets assigned to you in the current sprint- </div>- )}- </div>- )}-- {/* Actions zone — back to capped readable width */}- <div className="space-y-6 max-w-5xl">{/* Agent Operations */}<SlashDoPanel appId={app.id} appName={app.name} appType={app.type} />@@ -415,7 +340,7 @@ export default function OverviewTab({ app, onRefresh }) {{/* Activity Log */}<ActivityLog steps={steps} error={error} completed={completed} />- </div>{/* end actions zone */}+ </div></div>);}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 5c4955fd61..d621ceae05 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -36,7 +36,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| File | Purpose ||---|---|-| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart/logs) + local open actions (editor, Claude Code, folder, Xcode). |+| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart/logs) + local open actions (editor, Claude Code, folder, Xcode) + `getAppIssues` (open GitHub/GitLab issues for the Issues tab). || `apiWorkspaceContexts.js` | Per-project working-context save/restore (branch, shells, tasks). || `apiAccounts.js` | Platform accounts. || `apiAgents.js` | Running-agent process management. |diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 98e2b0c964..30d2d30d79 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -21,6 +21,12 @@ export const getAppWorkItems = (id, { issueAuthorFilter } = {}, options) => {const qs = issueAuthorFilter ? `?issueAuthorFilter=${encodeURIComponent(issueAuthorFilter)}` : '';return request(`/apps/${id}/work-items${qs}`, { silent: true, ...options });};+// Every OPEN issue on the forge this app's git origin points at (GitHub via gh,+// GitLab via glab): { forge, fullName, issues: [{ number, title, body, labels,+// assignees, author, url, createdAt, updatedAt }], reason, transient }. Backs the+// app Issues tab. Read-only; the tab owns its own error UI, so default to silent.+export const getAppIssues = (id, options) =>+ request(`/apps/${id}/issues`, { silent: true, ...options });// Effective Layered Intelligence config (self-improvement loop) for an app —// stored partial merged over the shipped defaults. Read-only; saved through// updateApp (the `layeredIntelligence` key routes to the merge helper server-@@ -36,9 +42,13 @@ export const createApp = (data) => request('/apps', {method: 'POST',body: JSON.stringify(data)});-export const updateApp = (id, data) => request(`/apps/${id}`, {+// Partial update — the server shallow-merges, so a body carrying one slice (e.g.+// `{ jira }` from the JIRA tab) leaves every other field untouched. Pass+// `{ silent: true }` when the caller renders its own error UI.+export const updateApp = (id, data, options = {}) => request(`/apps/${id}`, {method: 'PUT',- body: JSON.stringify(data)+ body: JSON.stringify(data),+ ...options});export const deleteApp = (id) => request(`/apps/${id}`, { method: 'DELETE' });diff --git a/server/lib/README.md b/server/lib/README.mdindex 0bb8b8141c..fd33b13c7a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -333,7 +333,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. || `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |-| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |+| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. || `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). || `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |diff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex 213d2ae814..e494291f6d 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -15,7 +15,7 @@// `git`). See server/services/cosTaskGenerator.js for the claim-work router// that consumes trackerToClaimTaskType.-import { readOriginRemoteUrl } from './gitRemote.js';+import { getOriginInfo, readOriginRemoteUrl } from './gitRemote.js';// Every selectable value (UI + Zod enum). `'auto'` is the default; the rest are// concrete sources.@@ -395,3 +395,73 @@ export async function resolveAppWorkTracker(app) {const base = resolveWorkTracker({ configured, host });return { ...base, host, forge: forgeCliForTracker(base.resolved) };}++/**+ * Best-effort `group[/subgroup...]/project` display path from a GitLab origin+ * URL. Cosmetic only — `glab` targets the project from the repo cwd, not this+ * string — so callers degrade to the host classifier's fullName or the raw host+ * rather than treating a null as "not a GitLab repo". Module-private: the only+ * consumer is `resolveRepoForgeTarget` below, and this module's exports are+ * re-exported flat from the `server/lib` barrel.+ * @param {string|null|undefined} originUrl+ * @returns {string|null}+ */+function gitlabProjectPath(originUrl) {+ if (typeof originUrl !== 'string') return null;+ // scheme://[user@]host[:port]/<path> OR [user@]host:<path> — capture <path>,+ // then strip a trailing `.git`.+ const m = originUrl.trim().match(/^[a-zA-Z][\w+.-]*:\/\/(?:[^/@]+@)?[^/]+\/(.+)$/)+ || originUrl.trim().match(/^(?:[^@/]+@)?[^/:]+:(.+)$/);+ return m ? m[1].replace(/\.git$/i, '').replace(/\/$/, '') : null;+}++/**+ * Resolve which forge a repo checkout's `origin` points at, together with+ * everything a `gh`/`glab` caller needs to target it — or null when the origin+ * isn't a forge PortOS can query (no remote, or a host that is neither+ * GitHub- nor GitLab-family).+ *+ * The two branches deliberately differ, mirroring how the CLIs address a repo:+ * - GitHub (incl. Enterprise) resolves through `githubRepoSpec`, whose+ * host-qualified `HOST/OWNER/REPO` selector keeps `gh --repo` deterministic on+ * a fork+upstream checkout and correct on enterprise hosts.+ * - GitLab is classified straight off the HOST via the subgroup-safe+ * `hostFromOriginUrl`, NOT `getOriginInfo().fullName`: the latter's strict+ * `owner/repo` parse returns null for a nested `group/subgroup/project`+ * remote (the common GitLab layout), which would silently read as "not a+ * forge" even though `glab` resolves the project from its cwd regardless.+ * `repoSpec` is therefore null for GitLab — the caller must run `glab` in+ * `repoPath`.+ *+ * Never throws: a missing repo / unreadable origin degrades to null.+ * @param {string} repoPath+ * @returns {Promise<{forge:'github'|'gitlab', fullName:string, repoSpec:string|null, apiHost:string|null}|null>}+ */+export async function resolveRepoForgeTarget(repoPath) {+ if (!repoPath) return null;+ const origin = await getOriginInfo(repoPath).catch(() => null);+ const githubSpec = githubRepoSpec(origin);+ if (githubSpec) {+ return {+ forge: 'github',+ fullName: origin.fullName,+ repoSpec: githubSpec,+ apiHost: githubApiHost(origin.host),+ };+ }+ // Reuse the URL `getOriginInfo` already read rather than spawning a second+ // `git remote get-url`. Its copy is credential-redacted (`://user:tok@` →+ // `://***@`), which both consumers below tolerate — each matches the userinfo+ // segment and discards it before reading the host / path.+ const originUrl = origin?.originUrl || null;+ const host = origin?.host || hostFromOriginUrl(originUrl);+ if (hostToWorkTracker(host) === 'gitlab') {+ return {+ forge: 'gitlab',+ fullName: origin?.fullName || gitlabProjectPath(originUrl) || host,+ repoSpec: null,+ apiHost: null,+ };+ }+ return null;+}diff --git a/server/routes/apps/index.js b/server/routes/apps/index.jsindex 338caf9a30..c62987b20d 100644--- a/server/routes/apps/index.js+++ b/server/routes/apps/index.js@@ -11,6 +11,7 @@* xcode — xcode-scripts/install* icons — icon serving + detection* taskTypes — per-app task-type overrides, work-tracker, layered-intelligence+ * issues — open GitHub/GitLab issues for the Issues tab* launch — open-editor, open-claude, open-folder, open-xcode* documents — planning-doc read/list/commit* agents — recent CoS agent history@@ -30,6 +31,7 @@ import viteTlsRoutes from './viteTls.js';import xcodeRoutes from './xcode.js';import iconRoutes from './icons.js';import taskTypeRoutes from './taskTypes.js';+import issueRoutes from './issues.js';import launchRoutes from './launch.js';import documentRoutes from './documents.js';import agentRoutes from './agents.js';@@ -43,6 +45,7 @@ router.use(viteTlsRoutes);router.use(xcodeRoutes);router.use(iconRoutes);router.use(taskTypeRoutes);+router.use(issueRoutes);router.use(launchRoutes);router.use(documentRoutes);router.use(agentRoutes);diff --git a/server/routes/apps/issues.js b/server/routes/apps/issues.jsnew file mode 100644index 0000000000..c87541f1f7--- /dev/null+++ b/server/routes/apps/issues.js@@ -0,0 +1,29 @@+/**+ * Forge issue listing for a managed app's Issues tab.+ *+ * GET /:id/issues → { appId, appName, forge, fullName, issues, reason, transient, remedy }+ *+ * Read-only: it shells out to `gh`/`glab` to LIST open issues and nothing more —+ * no claim markers, no labels written, no LLM call. Claiming one goes through the+ * existing `POST /api/cos/tasks/slashdo` (`command: 'next'`, `target: <number>`),+ * which is what keeps the button honest about the app's Work Tracker config.+ */++import { Router } from 'express';+import { listAppIssues } from '../../services/appIssues.js';+import { asyncHandler } from '../../lib/errorHandler.js';+import { loadApp } from './shared.js';++const router = Router();++// GET /api/apps/:id/issues - Every OPEN issue on the forge this app's git origin+// points at (github.* → gh, gitlab.* → glab). Unlike /work-items — which answers+// "what could /do:next claim?" and filters accordingly — this is the unfiltered+// tracker view the user reads before claiming.+router.get('/:id/issues', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const result = await listAppIssues(app);+ res.json({ appId: app.id, appName: app.name, ...result });+}));++export default router;diff --git a/server/routes/apps/issues.test.js b/server/routes/apps/issues.test.jsnew file mode 100644index 0000000000..e281fece74--- /dev/null+++ b/server/routes/apps/issues.test.js@@ -0,0 +1,72 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import issueRoutes from './issues.js';++vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+}));+vi.mock('../../services/appIssues.js', () => ({+ listAppIssues: vi.fn(),+}));++import * as appsService from '../../services/apps.js';+import { listAppIssues } from '../../services/appIssues.js';++describe('GET /api/apps/:id/issues', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', issueRoutes);+ vi.clearAllMocks();+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Widget', repoPath: '/repo' });+ });++ it('passes the loaded app to the lister and returns its payload with app identity', async () => {+ listAppIssues.mockResolvedValue({+ forge: 'github',+ fullName: 'acme/widget',+ issues: [{ number: 1, title: 'Bug', labels: [], assignees: [] }],+ reason: 'ok',+ transient: false,+ remedy: null,+ });++ const response = await request(app).get('/api/apps/app-001/issues');++ expect(response.status).toBe(200);+ expect(listAppIssues).toHaveBeenCalledWith({ id: 'app-001', name: 'Widget', repoPath: '/repo' });+ expect(response.body).toMatchObject({+ appId: 'app-001',+ appName: 'Widget',+ forge: 'github',+ fullName: 'acme/widget',+ reason: 'ok',+ transient: false,+ });+ expect(response.body.issues).toHaveLength(1);+ });++ it('surfaces the transient sentinel verbatim rather than flattening it to an empty list', async () => {+ listAppIssues.mockResolvedValue({+ forge: 'github', fullName: 'acme/widget', issues: [],+ reason: 'gh-unauthenticated', transient: true, remedy: 'run gh auth login',+ });++ const response = await request(app).get('/api/apps/app-001/issues');++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({ reason: 'gh-unauthenticated', transient: true, remedy: 'run gh auth login' });+ });++ it('404s for an unknown app without calling the forge', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/app-999/issues');++ expect(response.status).toBe(404);+ expect(listAppIssues).not.toHaveBeenCalled();+ });+});diff --git a/server/services/appIssues.js b/server/services/appIssues.jsnew file mode 100644index 0000000000..9fac645a71--- /dev/null+++ b/server/services/appIssues.js@@ -0,0 +1,193 @@+/**+ * Open-issue listing for a managed app's Issues tab.+ *+ * Distinct from `workItems.js`, which answers "what could `/do:next` CLAIM?" —+ * that list is deliberately narrowed (assigned / blocked / in-flight / epic+ * issues are filtered out) and carries only `{ ref, title }`. The Issues tab+ * shows the tracker as it actually is: EVERY open issue, with the labels,+ * assignees, and body the user reads before deciding to claim one.+ *+ * Forge-agnostic. The origin→forge classification is `resolveRepoForgeTarget`+ * (shared with the issue reconciler) so "which repo do we query" has exactly one+ * definition: github.* → `gh`, gitlab.* → `glab`, anything else → null. JIRA is+ * NOT handled here — JIRA-tracked apps have their own tab with the sprint board.+ *+ * Crucially the tab lists ONLY the tracker a claim would actually run against+ * (see `listAppIssues`), so the Claim button can never queue a run against a+ * tracker other than the one the user is looking at.+ *+ * Sentinel discipline (CLAUDE.md): "couldn't ask the forge" never collapses into+ * "there are no issues". A failed probe returns `issues: []` WITH+ * `transient: true` and a `reason`, so the UI says "couldn't load" instead of+ * the lie "no open issues".+ */++import { execGh, ensureForgeReachable } from './github.js';+import { execGlab } from './gitlab.js';+import { resolveAppWorkTracker, resolveRepoForgeTarget } from '../lib/workTracker.js';+import { safeJSONParse } from '../lib/fileUtils.js';++// Single-user repos never realistically exceed this; `glab` caps a page at 100.+const GH_LIST_LIMIT = 200;+const GL_PER_PAGE = 100;++// Issue bodies are rendered in an expandable panel, not a full markdown reader —+// cap what we ship so a novel-length issue can't bloat the payload.+const BODY_MAX_CHARS = 8000;++const truncateBody = (body) => {+ const text = typeof body === 'string' ? body : '';+ return text.length > BODY_MAX_CHARS ? `${text.slice(0, BODY_MAX_CHARS)}\n\n…(truncated)` : text;+};++/**+ * Normalize a raw `gh issue list --json` row into the common issue shape.+ * GitHub labels carry a hex `color` with no `#`; the UI needs it prefixed.+ */+function normalizeGithubIssue(issue) {+ return {+ number: issue.number,+ title: issue.title || '',+ body: truncateBody(issue.body),+ url: issue.url || '',+ labels: Array.isArray(issue.labels)+ ? issue.labels.filter(Boolean).map((l) => ({+ name: l.name || '',+ color: l.color ? `#${String(l.color).replace(/^#/, '')}` : null,+ description: l.description || '',+ })).filter((l) => l.name)+ : [],+ assignees: Array.isArray(issue.assignees)+ ? issue.assignees.map((a) => a?.login).filter(Boolean)+ : [],+ author: issue.author?.login || null,+ milestone: issue.milestone?.title || null,+ updatedAt: issue.updatedAt || null,+ };+}++/**+ * Normalize a raw `glab issue list -F json` row. GitLab keys the number on+ * `iid` and assignees/author on `username`. Labels are plain strings on current+ * `glab`, but the object form is tolerated too — the `-F json` label shape has+ * varied across glab versions, and a silently-dropped label list is worse than+ * an unused branch.+ */+function normalizeGitlabIssue(issue) {+ return {+ number: issue.iid,+ title: issue.title || '',+ body: truncateBody(issue.description),+ url: issue.web_url || '',+ labels: Array.isArray(issue.labels)+ ? issue.labels+ .map((l) => (typeof l === 'string' ? { name: l, color: null, description: '' }+ : { name: l?.name || '', color: l?.color || null, description: l?.description || '' }))+ .filter((l) => l.name)+ : [],+ assignees: Array.isArray(issue.assignees)+ ? issue.assignees.map((a) => a?.username).filter(Boolean)+ : [],+ author: issue.author?.username || null,+ milestone: issue.milestone?.title || null,+ updatedAt: issue.updated_at || null,+ };+}++/**+ * Shared tail of both fetchers: parse the CLI's JSON and classify the answer.+ * The absent-vs-empty split is the whole point — an unparseable/failed read is+ * `fetch-failed` + transient, while a CLI that answered with zero rows is the+ * definitive `no-open-issues`.+ */+function toIssueResult(raw, normalize) {+ const rows = safeJSONParse(raw, null);+ if (!Array.isArray(rows)) return { issues: [], reason: 'fetch-failed', transient: true };+ return { issues: rows.map(normalize), reason: rows.length ? 'ok' : 'no-open-issues', transient: false };+}++/**+ * Open issues from GitHub. `repoSpec` is the host-qualified `HOST/OWNER/REPO`+ * selector so enterprise repos resolve correctly and a fork+upstream checkout+ * stays deterministic. The reachability probe runs first: without it an+ * unreachable `gh` returns an empty page that reads as "no open issues".+ */+async function fetchGithubIssues(repoSpec, apiHost) {+ const forge = await ensureForgeReachable('app-issues', { hostname: apiHost });+ if (!forge.ok) {+ return { issues: [], reason: `gh-${forge.status}`, transient: true, remedy: forge.remedy || null };+ }+ // execGh REJECTS on failure (execGlab resolves null), so this catch is what+ // makes the two fetchers share the same "raw or null" contract below.+ const raw = await execGh([+ 'issue', 'list', '--repo', repoSpec, '--state', 'open',+ '--limit', String(GH_LIST_LIMIT),+ '--json', 'number,title,body,labels,assignees,author,milestone,url,updatedAt',+ ]).catch((err) => {+ console.error(`❌ app-issues: gh issue list failed for ${repoSpec}: ${err.message}`);+ return null;+ });+ return toIssueResult(raw, normalizeGithubIssue);+}++/**+ * Open issues from GitLab. `glab` resolves the project from the origin remote in+ * its working directory, so every call runs in `repoPath`.+ */+async function fetchGitlabIssues(repoPath) {+ // `glab issue list` defaults to OPEN issues.+ const raw = await execGlab(['issue', 'list', '--per-page', String(GL_PER_PAGE), '-F', 'json'], repoPath);+ return toIssueResult(raw, normalizeGitlabIssue);+}++/**+ * List the open issues on the forge this app's work actually lives on.+ *+ * The listed tracker MUST be the one a claim would run against, so this gates on+ * the app's RESOLVED work tracker (`resolveAppWorkTracker`) — not on the git+ * origin alone. `workTracker` is user-settable, and `resolveWorkTracker`+ * short-circuits on an explicit value before consulting the host: an app with a+ * GitHub origin but `workTracker: 'jira'` claims JIRA tickets, so listing its+ * GitHub issues here would offer a Claim button that queues `claim-issue-jira`+ * against a ticket key that doesn't exist. Same resolver as+ * `buildClaimWorkTask`, so the list and the claim agree by construction.+ *+ * The tracker probe and the forge-target probe are independent git reads, so+ * they overlap.+ *+ * @param {object} app - managed app record (needs `repoPath`, `workTracker`)+ * @returns {Promise<{forge:'github'|'gitlab'|null, tracker:string|null, fullName:string|null, issues:object[], reason:string, transient:boolean, remedy:string|null}>}+ */+export async function listAppIssues(app) {+ const base = { forge: null, tracker: null, fullName: null, issues: [], transient: false, remedy: null };+ if (!app?.repoPath) return { ...base, reason: 'no-repo-path' };++ const [wt, target] = await Promise.all([+ resolveAppWorkTracker(app),+ resolveRepoForgeTarget(app.repoPath),+ ]);+ const tracker = wt.resolved;++ // PLAN.md / JIRA apps have no forge issue list — and, more importantly, no+ // claim this tab could honestly offer.+ if (tracker !== 'github' && tracker !== 'gitlab') return { ...base, tracker, reason: 'tracker-not-a-forge' };+ if (!target) return { ...base, tracker, reason: 'unsupported-forge' };+ // Explicitly tracking one forge from the other's remote: we can't query the+ // configured tracker (no selector for it) and must not silently list the+ // other one, since that is not what a claim would touch.+ if (target.forge !== tracker) return { ...base, tracker, reason: 'tracker-forge-mismatch' };++ const result = tracker === 'github'+ ? await fetchGithubIssues(target.repoSpec, target.apiHost)+ : await fetchGitlabIssues(app.repoPath);++ return {+ forge: target.forge,+ tracker,+ fullName: target.fullName,+ issues: result.issues,+ reason: result.reason,+ transient: result.transient,+ remedy: result.remedy || null,+ };+}diff --git a/server/services/appIssues.test.js b/server/services/appIssues.test.jsnew file mode 100644index 0000000000..134872447b--- /dev/null+++ b/server/services/appIssues.test.js@@ -0,0 +1,230 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));+vi.mock('./github.js', () => ({+ execGh: vi.fn(async () => '[]'),+ ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),+}));+vi.mock('./gitlab.js', () => ({ execGlab: vi.fn(async () => '[]') }));+// gitRemote is the only effectful dependency of the real forge classifier, so+// mock IT and let `resolveRepoForgeTarget` run for real — the github-vs-gitlab+// routing under test is exactly that mapping.+vi.mock('../lib/gitRemote.js', () => ({+ getOriginInfo: vi.fn(async () => ({ isGithub: true, host: 'github.com', fullName: 'acme/widget' })),+ readOriginRemoteUrl: vi.fn(async () => '[email protected]:acme/widget.git'),+}));+vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { root: '/repo' },+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },+}));++import { listAppIssues } from './appIssues.js';+import { execGh } from './github.js';+import { execGlab } from './gitlab.js';+import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';++// `workTracker: 'auto'` resolves to whatever the origin host is — the common case.+const APP = { id: 'app-1', name: 'Widget', repoPath: '/repo', workTracker: 'auto' };++/** Point the origin at GitLab so the gitlab branch is exercised. */+function useGitlabOrigin() {+ getOriginInfo.mockResolvedValue({ isGithub: false, host: 'gitlab.com', fullName: 'group/proj' });+ readOriginRemoteUrl.mockResolvedValue('[email protected]:group/proj.git');+}++beforeEach(() => {+ vi.clearAllMocks();+ ensureForgeReachableMock.mockResolvedValue({ ok: true, status: 'ok', detail: null, remedy: null });+ getOriginInfo.mockResolvedValue({ isGithub: true, host: 'github.com', fullName: 'acme/widget' });+ readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/widget.git');+ execGh.mockResolvedValue('[]');+ execGlab.mockResolvedValue('[]');+});++describe('listAppIssues — GitHub', () => {+ it('normalizes a gh row into the common issue shape, with a #-prefixed label color', async () => {+ execGh.mockResolvedValue(JSON.stringify([{+ number: 42,+ title: 'Crash on save',+ body: 'Steps to reproduce…',+ url: 'https://github.com/acme/widget/issues/42',+ labels: [{ name: 'bug', color: 'd73a4a', description: 'Something is broken' }],+ assignees: [{ login: 'alice' }, { login: 'bob' }],+ author: { login: 'carol' },+ milestone: { title: 'v2' },+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-02T00:00:00Z',+ }]));++ const result = await listAppIssues(APP);++ expect(result.forge).toBe('github');+ expect(result.fullName).toBe('acme/widget');+ expect(result.reason).toBe('ok');+ expect(result.transient).toBe(false);+ expect(result.issues).toEqual([{+ number: 42,+ title: 'Crash on save',+ body: 'Steps to reproduce…',+ url: 'https://github.com/acme/widget/issues/42',+ labels: [{ name: 'bug', color: '#d73a4a', description: 'Something is broken' }],+ assignees: ['alice', 'bob'],+ author: 'carol',+ milestone: 'v2',+ updatedAt: '2026-01-02T00:00:00Z',+ }]);+ });++ it('does not re-read the origin remote inside the forge resolver', async () => {+ await listAppIssues(APP);+ // `getOriginInfo` already carries the URL, so `resolveRepoForgeTarget` must+ // not spawn a second `git remote get-url`. The one call here is the+ // independent work-tracker probe.+ expect(getOriginInfo).toHaveBeenCalledTimes(1);+ expect(readOriginRemoteUrl).toHaveBeenCalledTimes(1);+ });++ it('targets the host-qualified repo selector and asks only for OPEN issues', async () => {+ await listAppIssues(APP);+ const argv = execGh.mock.calls[0][0];+ expect(argv).toContain('--repo');+ expect(argv[argv.indexOf('--repo') + 1]).toBe('github.com/acme/widget');+ expect(argv[argv.indexOf('--state') + 1]).toBe('open');+ });++ it('an ANSWERED empty list is a definitive "no open issues", not a transient', async () => {+ execGh.mockResolvedValue('[]');+ const result = await listAppIssues(APP);+ expect(result.reason).toBe('no-open-issues');+ expect(result.transient).toBe(false);+ });++ it('an unreachable gh is transient — never collapsed into "no open issues"', async () => {+ ensureForgeReachableMock.mockResolvedValue({ ok: false, status: 'unauthenticated', detail: 'x', remedy: 'run gh auth login' });+ const result = await listAppIssues(APP);+ expect(result.transient).toBe(true);+ expect(result.reason).toBe('gh-unauthenticated');+ expect(result.remedy).toBe('run gh auth login');+ expect(result.issues).toEqual([]);+ // The probe short-circuits — no point spending a list call on a dead CLI.+ expect(execGh).not.toHaveBeenCalled();+ });++ it('a failed / unparseable gh list is transient', async () => {+ execGh.mockRejectedValue(new Error('bad file descriptor'));+ const failed = await listAppIssues(APP);+ expect(failed).toMatchObject({ reason: 'fetch-failed', transient: true, issues: [] });++ execGh.mockResolvedValue('not json');+ const unparseable = await listAppIssues(APP);+ expect(unparseable).toMatchObject({ reason: 'fetch-failed', transient: true });+ });++ it('truncates a novel-length body instead of shipping it whole', async () => {+ execGh.mockResolvedValue(JSON.stringify([{ number: 1, title: 't', body: 'x'.repeat(9000), labels: [], assignees: [] }]));+ const result = await listAppIssues(APP);+ expect(result.issues[0].body.length).toBeLessThan(9000);+ expect(result.issues[0].body).toMatch(/truncated/);+ });+});++describe('listAppIssues — GitLab', () => {+ it('normalizes iid / description / string labels / username assignees', async () => {+ useGitlabOrigin();+ execGlab.mockResolvedValue(JSON.stringify([{+ iid: 7,+ title: 'Add export',+ description: 'We need CSV',+ web_url: 'https://gitlab.com/group/proj/-/issues/7',+ state: 'opened',+ labels: ['feature', 'p2'],+ assignees: [{ username: 'dana' }],+ author: { username: 'erin' },+ milestone: { title: 'Sprint 3' },+ created_at: '2026-02-01T00:00:00Z',+ updated_at: '2026-02-02T00:00:00Z',+ }]));++ const result = await listAppIssues(APP);++ expect(result.forge).toBe('gitlab');+ expect(result.issues[0]).toMatchObject({+ number: 7,+ title: 'Add export',+ body: 'We need CSV',+ assignees: ['dana'],+ author: 'erin',+ milestone: 'Sprint 3',+ });+ expect(result.issues[0].labels).toEqual([+ { name: 'feature', color: null, description: '' },+ { name: 'p2', color: null, description: '' },+ ]);+ // glab resolves the project from its cwd, so the repo path is load-bearing.+ expect(execGlab.mock.calls[0][1]).toBe('/repo');+ });++ it('a null glab result (CLI missing / timed out) is transient', async () => {+ useGitlabOrigin();+ execGlab.mockResolvedValue(null);+ const result = await listAppIssues(APP);+ expect(result).toMatchObject({ forge: 'gitlab', reason: 'fetch-failed', transient: true });+ });+});++describe('listAppIssues — non-forge apps', () => {+ it('reports no-repo-path without touching any CLI', async () => {+ const result = await listAppIssues({ id: 'app-2', name: 'No Repo' });+ expect(result).toMatchObject({ forge: null, reason: 'no-repo-path', transient: false, issues: [] });+ expect(execGh).not.toHaveBeenCalled();+ expect(execGlab).not.toHaveBeenCalled();+ });++ it('an unrecognized origin falls back to PLAN.md, which has no forge issue list', async () => {+ getOriginInfo.mockResolvedValue({ isGithub: false, host: 'bitbucket.org', fullName: 'acme/widget' });+ readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/widget.git');+ const result = await listAppIssues(APP);+ expect(result).toMatchObject({ forge: null, tracker: 'plan', reason: 'tracker-not-a-forge', transient: false });+ });++ it('reports unsupported-forge when a forge tracker is pinned but the origin can serve none', async () => {+ getOriginInfo.mockResolvedValue({ isGithub: false, host: 'bitbucket.org', fullName: 'acme/widget' });+ readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/widget.git');+ const result = await listAppIssues({ ...APP, workTracker: 'github' });+ expect(result).toMatchObject({ forge: null, tracker: 'github', reason: 'unsupported-forge', transient: false });+ });+});++// The tab's whole promise is "the Claim button claims the issue you are looking+// at". `buildClaimWorkTask` routes on the app's RESOLVED work tracker, so listing+// anything the resolved tracker doesn't own would offer a claim that runs against+// a different tracker entirely.+describe('listAppIssues — the list must match the tracker a claim would use', () => {+ it('lists nothing for a JIRA-tracked app even when the origin is GitHub', async () => {+ const result = await listAppIssues({ ...APP, workTracker: 'jira' });+ expect(result).toMatchObject({ forge: null, tracker: 'jira', reason: 'tracker-not-a-forge', issues: [] });+ // Otherwise the Claim button would queue claim-issue-jira against ticket "42".+ expect(execGh).not.toHaveBeenCalled();+ });++ it('lists nothing for a PLAN.md-tracked app even when the origin is GitHub', async () => {+ const result = await listAppIssues({ ...APP, workTracker: 'plan' });+ expect(result).toMatchObject({ forge: null, tracker: 'plan', reason: 'tracker-not-a-forge' });+ expect(execGh).not.toHaveBeenCalled();+ });++ it('refuses to list the OTHER forge when the tracker is pinned across remotes', async () => {+ // Pinned to GitLab, but the remote is GitHub: neither answer is honest, so+ // list neither rather than showing issues a claim would never touch.+ const result = await listAppIssues({ ...APP, workTracker: 'gitlab' });+ expect(result).toMatchObject({ forge: null, tracker: 'gitlab', reason: 'tracker-forge-mismatch' });+ expect(execGh).not.toHaveBeenCalled();+ expect(execGlab).not.toHaveBeenCalled();+ });++ it('honors an explicit github pin on a GitHub remote', async () => {+ execGh.mockResolvedValue(JSON.stringify([{ number: 1, title: 't', labels: [], assignees: [] }]));+ const result = await listAppIssues({ ...APP, workTracker: 'github' });+ expect(result).toMatchObject({ forge: 'github', tracker: 'github', reason: 'ok' });+ });+});diff --git a/server/services/issueReconcile.js b/server/services/issueReconcile.jsindex cb4050ea53..db00255040 100644--- a/server/services/issueReconcile.js+++ b/server/services/issueReconcile.js@@ -54,8 +54,7 @@ import { execGit } from '../lib/execGit.js';import { execGh, ensureForgeReachable } from './github.js';import { execGlab } from './gitlab.js';import { fetchMyCurrentSprintTickets } from './jira.js';-import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';-import { hostToWorkTracker, hostFromOriginUrl, githubRepoSpec, githubApiHost } from '../lib/workTracker.js';+import { resolveRepoForgeTarget } from '../lib/workTracker.js';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';// Bound the forge queries (single-user repos never realistically truncate at 200).@@ -384,56 +383,24 @@ async function getGitlabState(repoPath, fullName) {};}-/**- * Best-effort `group[/subgroup...]/project` display path from a GitLab origin- * URL. Only cosmetic (it feeds the prompt header) — `glab` targets the project- * from the repo cwd, not this string — so it degrades to the host classifier's- * fullName or the raw origin URL rather than blocking the scan.- */-function gitlabProjectPath(originUrl) {- if (typeof originUrl !== 'string') return null;- // scheme://[user@]host[:port]/<path> OR [user@]host:<path> — capture <path>,- // then strip a trailing `.git`.- const m = originUrl.trim().match(/^[a-zA-Z][\w+.-]*:\/\/(?:[^/@]+@)?[^/]+\/(.+)$/)- || originUrl.trim().match(/^(?:[^@/]+@)?[^/:]+:(.+)$/);- return m ? m[1].replace(/\.git$/i, '').replace(/\/$/, '') : null;-}-/*** Resolve the app's forge from its git origin host and fetch the corresponding* state. github.* → GitHub, gitlab.* → GitLab; any other remote (or no origin)* returns null so the caller skips without parking.*- * GitHub is resolved via `githubRepoSpec` (github.com AND enterprise github.*),- * mirroring prWatcher — `getOriginInfo().isGithub` is github.com-only and- * silently skipped enterprise repos. That helper also needs a parsed `owner/repo`- * to build the host-qualified `--repo` selector. GitLab is classified- * straight off the origin HOST via the- * subgroup-safe `hostFromOriginUrl`, NOT `getOriginInfo().fullName`: the latter's- * strict `owner/repo` parse returns null for a nested `group/subgroup/project`- * remote (the common GitLab layout), which would silently skip the scan even- * though `glab` resolves the project from the cwd regardless.+ * The origin→forge classification itself (enterprise-aware GitHub `--repo`+ * selector, subgroup-safe GitLab host match) lives in `resolveRepoForgeTarget`+ * so this scan and the app Issues tab can't drift on what counts as a queryable+ * repo; only the state-fetching differs here.* @param {string} repoPath* @returns {Promise<object|null>}*/async function getForgeState(repoPath) {- const origin = await getOriginInfo(repoPath).catch(() => null);- // GitHub (incl. enterprise): githubRepoSpec is the host-qualified- // `HOST/OWNER/REPO` --repo selector (deterministic on fork+upstream checkouts),- // or null when the origin isn't a resolvable GitHub repo.- const githubSpec = githubRepoSpec(origin);- if (githubSpec) return getGithubState(githubSpec, origin.fullName, githubApiHost(origin.host));-- // GitLab: classify off the host (subgroup-safe). `glab` is cwd-based, so a- // display path is best-effort — prefer getOriginInfo's fullName, else derive the- // full project path from the URL, else fall back to the host.- const originUrl = await readOriginRemoteUrl(repoPath).catch(() => null);- const host = origin?.host || hostFromOriginUrl(originUrl);- if (hostToWorkTracker(host) === 'gitlab') {- const displayName = origin?.fullName || gitlabProjectPath(originUrl) || host;- return getGitlabState(repoPath, displayName);- }- return null;+ const target = await resolveRepoForgeTarget(repoPath);+ if (!target) return null;+ if (target.forge === 'github') return getGithubState(target.repoSpec, target.fullName, target.apiHost);+ // `glab` is cwd-based, so `fullName` here is only a display path.+ return getGitlabState(repoPath, target.fullName);}/**diff --git a/server/services/issueReconcile.test.js b/server/services/issueReconcile.test.jsindex 55e5ecc2a4..6040ce06eb 100644--- a/server/services/issueReconcile.test.js+++ b/server/services/issueReconcile.test.js@@ -28,18 +28,11 @@ vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: vi.fn(async () => ({ isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS' })),readOriginRemoteUrl: vi.fn(async () => '[email protected]:atomantic/PortOS.git'),}));-// hostToWorkTracker is the canonical host→forge classifier. Import the REAL pure-// implementation (partial mock) so the GitLab branch is exercised through the-// exact mapping production uses — no drift-prone re-implementation here.-vi.mock('../lib/workTracker.js', async (importActual) => {- const actual = await importActual();- return {- hostToWorkTracker: actual.hostToWorkTracker,- hostFromOriginUrl: actual.hostFromOriginUrl,- githubRepoSpec: actual.githubRepoSpec,- githubApiHost: actual.githubApiHost,- };-});+// workTracker.js is deliberately NOT mocked: `resolveRepoForgeTarget` is the+// canonical origin→forge classifier, and its only effectful dependency is+// gitRemote.js (mocked above). Running the real implementation is what exercises+// the enterprise-GitHub and nested-subgroup-GitLab branches through the exact+// mapping production uses — a re-implementation here would drift.vi.mock('../lib/fileUtils.js', () => ({PATHS: { root: '/repo' },safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },@@ -422,8 +415,13 @@ describe('reconcile (GitLab forge)', () => {// Common GitLab layout `group/subgroup/project` — getOriginInfo's strict// owner/repo parse returns null, but the host still classifies as GitLab and// `glab` is cwd-based, so the scan must NOT be skipped. Host is classified off- // the origin URL via the real hostFromOriginUrl.- getOriginInfo.mockResolvedValue({ isGithub: false, host: null, fullName: null });+ // the origin URL via the real hostFromOriginUrl. `originUrl` is part of+ // getOriginInfo's real return shape on the unparseable-remote path (see+ // gitRemote.js) — the resolver reads it rather than re-shelling to git.+ getOriginInfo.mockResolvedValue({+ isGithub: false, host: null, fullName: null,+ originUrl: '[email protected]:group/subgroup/project.git',+ });readOriginRemoteUrl.mockResolvedValue('[email protected]:group/subgroup/project.git');mockGlab({issues: [{ iid: 42, title: 't', labels: ['in-progress'], assignees: [], web_url: 'u' }],