Skip to content

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

feat: pin a CoS task to one federated instance from the web UI (#4520)

[._.]/ Adam Eivy94601d376040
diff --git a/client/src/components/cos/InstancePicker.jsx b/client/src/components/cos/InstancePicker.jsx
new file mode 100644
index 0000000000..66e9aa6129
--- /dev/null
+++ b/client/src/components/cos/InstancePicker.jsx
@@ -0,0 +1,34 @@
+import { Server } from 'lucide-react';
+
+// Which federated instance runs this task (#4520). `''` is "Any instance" — the
+// default, and the opportunistic first-claim-wins behavior CoS has always had.
+// Picking a specific instance pins the task there: every other peer passes over
+// it even when it is idle.
+//
+// Presentational on purpose — the instance list is fetched once by the owning
+// view (`useAssignableInstances`) and passed in, so a list of task rows doesn't
+// issue one request per row.
+export default function InstancePicker({ id, value, onChange, instances, label = 'Run on' }) {
+ return (
+ <label htmlFor={id} className="flex items-center gap-2 py-1">
+ <span className="flex items-center gap-1.5 text-sm text-gray-400 whitespace-nowrap">
+ <Server size={14} className="text-port-accent-2" aria-hidden="true" />
+ {label}
+ </span>
+ <select
+ id={id}
+ value={value || ''}
+ onChange={(e) => onChange(e.target.value)}
+ title="Pin this task to one federated instance. Any instance keeps the default behavior: whichever peer picks it up first runs it."
+ className="min-w-44 rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-white focus:border-port-accent focus:outline-hidden"
+ >
+ <option value="">Any instance</option>
+ {instances.map((instance) => (
+ <option key={instance.instanceId} value={instance.instanceId}>
+ {instance.isSelf ? `${instance.name} (this instance)` : instance.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ );
+}
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index 30e6f05dcf..f0ac80f2e1 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -12,8 +12,10 @@ import { DEFAULT_PR_COMPLETION, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, PR_
import { clickableProps } from '../../lib/a11yKeyboard';
import { slashdoLabel } from '../../lib/slashdoCatalog';
import ReviewerPicker from './ReviewerPicker';
+import InstancePicker from './InstancePicker';
import EffortSelect from './EffortSelect';
import useReviewerModelOptions from '../../hooks/useReviewerModelOptions';
+import useAssignableInstances from '../../hooks/useAssignableInstances';
import { reviewerModelsFromDefaults, reviewerEffortsFromDefaults } from '../../lib/reviewerModels';
export default function TaskAddForm({ providers, apps, onTaskAdded, compact = false, defaultExpanded = false, defaultApp = '' }) {
@@ -38,6 +40,10 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
const [reviewStopMode, setReviewStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);
const [reviewerApplies, setReviewerApplies] = useState(false);
const [reviewerCliInstalled, setReviewerCliInstalled] = useState({});
+ // Which federated instance runs this task (#4520). '' = any instance, the
+ // opportunistic default. Hidden entirely on a single-instance install.
+ const [targetInstanceId, setTargetInstanceId] = useState('');
+ const { instances: assignableInstances, isFederated } = useAssignableInstances();
const [createJiraTicket, setCreateJiraTicket] = useState(false);
const [screenshots, setScreenshots] = useState([]);
const [attachments, setAttachments] = useState([]);
@@ -337,6 +343,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
temperature: newTask.temperature === '' ? undefined : Number(newTask.temperature),
thinking: newTask.thinking === '' ? undefined : newTask.thinking === 'true',
app: newTask.app || undefined,
+ targetInstanceId: targetInstanceId || undefined,
slashdoCommand: slashdoCommand || undefined,
createJiraTicket,
useWorktree,
@@ -534,6 +541,14 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
showRepoPath
/>
)}
+ {isFederated && (
+ <InstancePicker
+ id="task-target-instance"
+ value={targetInstanceId}
+ onChange={setTargetInstanceId}
+ instances={assignableInstances}
+ />
+ )}
<div className="grid grid-cols-1 sm:flex sm:items-center gap-x-4 gap-y-1 sm:flex-wrap">
<label className="flex items-center gap-2 cursor-pointer select-none py-1">
<input
diff --git a/client/src/components/cos/TaskAddForm.test.jsx b/client/src/components/cos/TaskAddForm.test.jsx
index 6cfc8a9d84..0d4005c774 100644
--- a/client/src/components/cos/TaskAddForm.test.jsx
+++ b/client/src/components/cos/TaskAddForm.test.jsx
@@ -13,6 +13,10 @@ const api = vi.hoisted(() => ({
addCosTask: vi.fn()
}));
+// useAssignableInstances reads the instance registry straight off apiSystem, so
+// the picker (#4520) has to be driven from there rather than the `api` barrel.
+const apiSystem = vi.hoisted(() => ({ getAssignableInstances: vi.fn() }));
+vi.mock('../../services/apiSystem', () => apiSystem);
vi.mock('../../services/api', () => api);
describe('TaskAddForm responsive layout', () => {
@@ -23,6 +27,7 @@ describe('TaskAddForm responsive layout', () => {
api.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });
api.getProviders.mockResolvedValue({ providers: [] });
api.applyCosTaskTemplate.mockResolvedValue({ success: true });
+ apiSystem.getAssignableInstances.mockResolvedValue({ instances: [] });
});
it('keeps PR completion controls full-width on mobile', async () => {
@@ -212,3 +217,49 @@ describe('TaskAddForm quick templates — deliverable posture', () => {
expect('worktreeChangesExpected' in api.addCosTask.mock.calls.at(-1)[0]).toBe(false);
});
});
+
+// #4520: on a federated install the form offers "which machine runs this?".
+describe('TaskAddForm federated instance picker (#4520)', () => {
+ const PEER = 'peer-instance-id';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getCosPopularTemplates.mockResolvedValue({ templates: [] });
+ api.getCodeReviewDefaults.mockResolvedValue(null);
+ api.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });
+ api.getProviders.mockResolvedValue({ providers: [] });
+ api.addCosTask.mockResolvedValue({ success: true });
+ });
+
+ it('is hidden on a single-instance install — there is nothing to choose', async () => {
+ apiSystem.getAssignableInstances.mockResolvedValue({
+ instances: [{ instanceId: 'self-instance-id', name: 'workstation', isSelf: true }],
+ });
+ render(<TaskAddForm providers={[]} apps={[]} onTaskAdded={vi.fn()} />);
+ await waitFor(() => expect(apiSystem.getAssignableInstances).toHaveBeenCalled());
+ expect(screen.queryByLabelText('Run on')).toBeNull();
+ });
+
+ it('sends the picked instance with the task, and omits it for "Any instance"', async () => {
+ const user = userEvent.setup();
+ apiSystem.getAssignableInstances.mockResolvedValue({
+ instances: [
+ { instanceId: 'self-instance-id', name: 'workstation', isSelf: true },
+ { instanceId: PEER, name: 'render-box', isSelf: false },
+ ],
+ });
+ render(<TaskAddForm providers={[]} apps={[]} onTaskAdded={vi.fn()} />);
+ await waitFor(() => expect(screen.getByLabelText('Run on')).toBeInTheDocument());
+
+ await user.type(screen.getByPlaceholderText('Task description *'), 'Render the shot');
+ await user.click(screen.getByRole('button', { name: /^Add$/ }));
+ await waitFor(() => expect(api.addCosTask).toHaveBeenCalled());
+ expect(api.addCosTask.mock.calls[0][0].targetInstanceId).toBeUndefined();
+
+ await user.selectOptions(screen.getByLabelText('Run on'), PEER);
+ await user.type(screen.getByPlaceholderText('Task description *'), 'Render the other shot');
+ await user.click(screen.getByRole('button', { name: /^Add$/ }));
+ await waitFor(() => expect(api.addCosTask).toHaveBeenCalledTimes(2));
+ expect(api.addCosTask.mock.calls[1][0].targetInstanceId).toBe(PEER);
+ });
+});
diff --git a/client/src/components/cos/tabs/SortableTaskItem.jsx b/client/src/components/cos/tabs/SortableTaskItem.jsx
index 192791ea49..84b259c425 100644
--- a/client/src/components/cos/tabs/SortableTaskItem.jsx
+++ b/client/src/components/cos/tabs/SortableTaskItem.jsx
@@ -3,7 +3,7 @@ import { useSortable } from '@dnd-kit/sortable';
import { dndTransformToCss } from '../../../lib/dndTransform';
import TaskItem from './TaskItem';
-export default function SortableTaskItem({ task, selected = false, onRefresh, providers, durations, apps }) {
+export default function SortableTaskItem({ task, selected = false, onRefresh, providers, durations, apps, instances }) {
const [isEditing, setIsEditing] = useState(false);
const {
attributes,
@@ -30,6 +30,7 @@ export default function SortableTaskItem({ task, selected = false, onRefresh, pr
providers={providers}
durations={durations}
apps={apps}
+ instances={instances}
dragHandleProps={isEditing ? undefined : { ...attributes, ...listeners }}
onEditingChange={setIsEditing}
/>
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 0c81e4861d..d50d9ec854 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -17,7 +17,8 @@ import {
TrendingUp,
Play,
Scale,
- Unlock
+ Unlock,
+ Server
} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
@@ -28,6 +29,7 @@ import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import Modal from '../../ui/Modal';
import CollapsibleText from '../../ui/CollapsibleText';
import { extractCosTaskType } from '../../../lib/cosTaskType';
+import InstancePicker from '../InstancePicker';
const statusIcons = {
pending: <Clock size={16} aria-hidden="true" className="text-yellow-500" />,
@@ -56,7 +58,9 @@ const getTaskEditData = (task) => ({
prompt: task.metadata?.prompt || '',
context: task.metadata?.context || '',
model: task.metadata?.model || '',
- provider: task.metadata?.provider || ''
+ provider: task.metadata?.provider || '',
+ // '' = "Any instance" (#4520) — no pin, the opportunistic default.
+ targetInstanceId: task.metadata?.targetInstanceId || ''
});
export const taskRowId = (taskId, source) => `cos-task-${source}-${encodeURIComponent(taskId)}`;
@@ -68,7 +72,7 @@ function getSuccessRateStyle(rate) {
return { bg: 'bg-port-error/15', text: 'text-port-error', label: 'low' };
}
-export default function TaskItem({ task, isSystem, selected = false, onRefresh, providers, durations, dragHandleProps, apps, onEditingChange }) {
+export default function TaskItem({ task, isSystem, selected = false, onRefresh, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {
// System tasks are persisted in COS-TASKS.md. Every task
// mutation must name that source; otherwise the API's user-queue default
// searches TASKS.md and reports the system task as missing.
@@ -91,6 +95,20 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,
// task actually carries one, and is omitted from the PATCH otherwise rather
// than writing an empty `prompt` key onto every task the user edits.
const hasPromptField = typeof task.metadata?.prompt === 'string';
+ // Instance pinning (#4520) is only meaningful once this install federates with
+ // at least one identified peer. Below that, the picker is hidden AND the field
+ // is withheld from the PATCH, so editing a task here can never silently clear
+ // a pin another machine set.
+ // `null` means the registry has not been read yet — distinct from a read that
+ // found nothing — so a row never flashes "unknown instance" before the list lands.
+ const knownInstances = instances || [];
+ const canPinInstance = knownInstances.length > 1;
+ const targetInstanceId = task.metadata?.targetInstanceId || '';
+ // A pin naming an instance that has left the registry still renders — silently
+ // dropping the badge would hide exactly the task nothing will ever run.
+ const targetInstanceName = targetInstanceId && instances
+ ? (knownInstances.find(i => i.instanceId === targetInstanceId)?.name || 'unknown instance')
+ : '';
const taskPrompt = task.metadata?.prompt || '';
const taskContext = task.metadata?.context || '';
const taskModel = task.metadata?.model || '';
@@ -208,8 +226,15 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,
};
const handleSave = async () => {
- const { prompt, ...rest } = editData;
- const payload = hasPromptField ? { ...rest, prompt, type: taskSource } : { ...rest, type: taskSource };
+ const { prompt, targetInstanceId: draftInstanceId, ...rest } = editData;
+ const payload = {
+ ...rest,
+ type: taskSource,
+ ...(hasPromptField ? { prompt } : {}),
+ // '' is the picker's "Any instance" → null, the explicit unpin the update
+ // schema preserves (absent would leave the pin untouched).
+ ...(canPinInstance ? { targetInstanceId: draftInstanceId || null } : {})
+ };
const result = await api.updateCosTask(task.id, payload, { silent: true }).catch(err => {
toast.error(err.message);
return null;
@@ -228,7 +253,8 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,
(hasPromptField && editData.prompt !== (task.metadata?.prompt || '')) ||
editData.context !== (task.metadata?.context || '') ||
editData.model !== (task.metadata?.model || '') ||
- editData.provider !== (task.metadata?.provider || '');
+ editData.provider !== (task.metadata?.provider || '') ||
+ editData.targetInstanceId !== targetInstanceId;
const handleCancelEdit = () => {
if (hasUnsavedEdits) {
@@ -330,6 +356,15 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,
{apps.find(a => a.id === task.metadata.app).name}
</span>
)}
+ {targetInstanceName && (
+ <span
+ className="flex items-center gap-1 px-1.5 py-0.5 text-xs bg-port-accent-2/20 text-port-accent-2 rounded shrink-0"
+ title={`Pinned to instance ${targetInstanceId} — only that instance runs this task`}
+ >
+ <Server size={10} aria-hidden="true" />
+ {targetInstanceName}
+ </span>
+ )}
{/* Duration estimate for pending tasks */}
{durationEstimate && (
<span
@@ -426,6 +461,14 @@ export default function TaskItem({ task, isSystem, selected = false, onRefresh,
</select>
)}
</div>
+ {canPinInstance && (
+ <InstancePicker
+ id={`task-target-instance-${idScope}-${task.id}`}
+ value={editData.targetInstanceId}
+ onChange={(next) => setEditData(d => ({ ...d, targetInstanceId: next }))}
+ instances={knownInstances}
+ />
+ )}
{isConfirmingDiscard(task.id) ? (
<ConfirmButtonPair
prompt="Discard unsaved changes?"
diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsx
index 10f5f55a55..8113abeb08 100644
--- a/client/src/components/cos/tabs/TaskItem.test.jsx
+++ b/client/src/components/cos/tabs/TaskItem.test.jsx
@@ -579,3 +579,78 @@ describe('TaskItem investigation approval hint (#3714)', () => {
expect(approve).toHaveAttribute('title', expect.stringContaining('Require approval'));
});
});
+
+// #4520: a task can be pinned to one federated instance. The row shows where it
+// will run; the editor changes it — but only on an install that actually has
+// more than one instance to choose between.
+describe('TaskItem federated instance pin (#4520)', () => {
+ const SELF = 'self-instance-id';
+ const PEER = 'peer-instance-id';
+ const instances = [
+ { instanceId: SELF, name: 'workstation', isSelf: true },
+ { instanceId: PEER, name: 'render-box', isSelf: false },
+ ];
+ const pinned = { ...task, metadata: { ...task.metadata, targetInstanceId: PEER } };
+
+ it('badges the pinned instance by name', () => {
+ render(<TaskItem task={pinned} providers={providers} instances={instances} onRefresh={vi.fn()} />);
+ expect(screen.getByText('render-box')).toBeTruthy();
+ });
+
+ it('badges a pin whose instance has left the registry, rather than hiding it', () => {
+ // The task nothing will ever run is exactly the one that must stay visible.
+ const orphaned = { ...task, metadata: { ...task.metadata, targetInstanceId: 'ghost-instance-id' } };
+ render(<TaskItem task={orphaned} providers={providers} instances={instances} onRefresh={vi.fn()} />);
+ expect(screen.getByText('unknown instance')).toBeTruthy();
+ });
+
+ it('shows no badge for an unpinned task', () => {
+ render(<TaskItem task={task} providers={providers} instances={instances} onRefresh={vi.fn()} />);
+ expect(screen.queryByText('render-box')).toBeNull();
+ });
+
+ it('saves a re-pin from the editor', async () => {
+ render(<TaskItem task={task} providers={providers} instances={instances} onRefresh={vi.fn()} />);
+ fireEvent.click(screen.getByLabelText("Edit task"));
+ fireEvent.change(screen.getByLabelText('Run on'), { target: { value: PEER } });
+ fireEvent.click(screen.getByText('Save'));
+ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalled());
+ expect(api.updateCosTask.mock.calls[0][1].targetInstanceId).toBe(PEER);
+ });
+
+ it('sends null when the editor selects "Any instance" — the explicit unpin', async () => {
+ render(<TaskItem task={pinned} providers={providers} instances={instances} onRefresh={vi.fn()} />);
+ fireEvent.click(screen.getByLabelText("Edit task"));
+ fireEvent.change(screen.getByLabelText('Run on'), { target: { value: '' } });
+ fireEvent.click(screen.getByText('Save'));
+ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalled());
+ expect(api.updateCosTask.mock.calls[0][1].targetInstanceId).toBeNull();
+ });
+
+ it('hides the picker AND withholds the field on a single-instance install', async () => {
+ // Otherwise an edit made here would silently unpin a task another machine
+ // pinned — the field would ride along as `null` on every save.
+ render(<TaskItem task={pinned} providers={providers} instances={[{ instanceId: SELF, name: 'workstation', isSelf: true }]} onRefresh={vi.fn()} />);
+ fireEvent.click(screen.getByLabelText("Edit task"));
+ expect(screen.queryByLabelText('Run on')).toBeNull();
+ fireEvent.click(screen.getByText('Save'));
+ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalled());
+ expect('targetInstanceId' in api.updateCosTask.mock.calls[0][1]).toBe(false);
+ });
+});
+
+// A row must not claim a pin points at an "unknown instance" merely because the
+// registry read hasn't landed yet — `null` is not-fetched, `[]` is fetched-empty.
+describe('TaskItem instance registry — not-fetched vs fetched-empty (#4520)', () => {
+ const pinned = { ...task, metadata: { ...task.metadata, targetInstanceId: 'peer-instance-id' } };
+
+ it('renders no pin badge while the registry is still loading', () => {
+ render(<TaskItem task={pinned} providers={providers} onRefresh={vi.fn()} />);
+ expect(screen.queryByText('unknown instance')).toBeNull();
+ });
+
+ it('renders the orphaned-pin badge once the registry is known to be empty', () => {
+ render(<TaskItem task={pinned} providers={providers} instances={[]} onRefresh={vi.fn()} />);
+ expect(screen.getByText('unknown instance')).toBeTruthy();
+ });
+});
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index e9f75ec21c..abe681ce6e 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -21,6 +21,7 @@ import TaskItem, { taskRowId } from './TaskItem';
import SortableTaskItem from './SortableTaskItem';
import TaskAddForm from '../TaskAddForm';
import { MicroGlyph, SchematicLabel } from '../../micrographics';
+import useAssignableInstances from '../../../hooks/useAssignableInstances';
// Maps a task-section status → micrographic glyph spec. Animation only on
// states where motion communicates real work happening (running tasks).
@@ -43,6 +44,9 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
const [durations, setDurations] = useState(null);
const [showCompletedUserTasks, setShowCompletedUserTasks] = useState(false);
const [showCompletedSystemTasks, setShowCompletedSystemTasks] = useState(false);
+ // Fetched once for the whole list (#4520) — every row renders its instance pin
+ // from this, so a long backlog never issues one request per task.
+ const { instances: assignableInstances } = useAssignableInstances();
// Fetch task duration estimates
useEffect(() => {
@@ -231,7 +235,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
>
<div className="space-y-1.5">
{pendingUserTasksLocal.map(task => (
- <SortableTaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <SortableTaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</SortableContext>
@@ -251,7 +255,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
</div>
<div className="p-2 space-y-1.5">
{activeUserTasksLocal.map(task => (
- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
@@ -268,7 +272,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
</div>
<div className="p-2 space-y-1.5">
{blockedUserTasksLocal.map(task => (
- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
@@ -291,7 +295,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
{showCompletedUserTasks && (
<div className="p-2 space-y-1.5">
{completedUserTasksLocal.map(task => (
- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
)}
@@ -324,7 +328,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
</div>
<div className="p-2 space-y-1.5">
{pendingSystemTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
@@ -341,7 +345,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
</div>
<div className="p-2 space-y-1.5">
{activeSystemTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
@@ -358,7 +362,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
</div>
<div className="p-2 space-y-1.5">
{blockedSystemTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
@@ -381,7 +385,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
{showCompletedSystemTasks && (
<div className="p-2 space-y-1.5">
{completedSystemTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} />
+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
)}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 4cc77b1f55..fcdbc6a128 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -127,6 +127,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. `fitToDuration(sec)` solves the speed for a target run time from the measured scroll travel (returns the applied px/s, or `null` when there is nothing to scroll). Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration }`. | SongBook play view; any teleprompter-style surface. |
| `useAudioSessionClaim` | `useAudioSessionClaim(type)` → `{ claim, release }` — one arbitrated `acquireAudioSession(type)` slot with a React lifecycle: `claim()` drops this instance's previous claim before taking a fresh one, `release()` is idempotent, and unmount releases whatever is still held. | A surface owning its OWN `AudioContext` (MorseTrainer, the Security monitor) or `getUserMedia` stream (`useSingToScore`/`useSingToVerify`) needs the iOS session. An output-only player on the shared transport passes `audioSession: 'playback'` to `createLookaheadTransport` instead — don't hand-roll either. |
| `useAsyncCaptureGuard` | Shared pending-request and generation guard for microphone permission prompts; returns `{ tryStart, settleStart, isCurrent, cancel }` and delegates resource teardown plus caller-owned idle reset. | Any capture hook that must reject concurrent `getUserMedia` starts and dispose a stream resolved after cancellation. |
+| `useAssignableInstances` | `useAssignableInstances()` → `{ instances, loading, isFederated }` — this install's assignable federated instances (self + identified peers) for pinning a CoS task to one machine. Silent fetch; `isFederated` is false on a single-instance install so callers can hide their picker. | Any surface offering "which machine should run this?" — the CoS task add form and the task editor. |
| `useWakeLock` | Holds a screen wake lock (`navigator.wakeLock`) while `active` is true; releases on unmount/inactive, re-acquires on visibilitychange; no-op where unsupported. | Hands-free surfaces that must keep the screen on (SongBook autoscroll). |
## Storage & persistence
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index a228eec6ef..dc27a2c3bb 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -11,6 +11,7 @@
export { default as useAnchorReveal } from './useAnchorReveal.js';
export { default as useAudioSessionClaim } from './useAudioSessionClaim.js';
export { default as useAsyncCaptureGuard } from './useAsyncCaptureGuard.js';
+export { default as useAssignableInstances } from './useAssignableInstances.js';
export { default as useAutoscroll } from './useAutoscroll.js';
export { default as useCityAudio } from './useCityAudio.js';
export { default as useClonedGltf } from './useClonedGltf.jsx';
diff --git a/client/src/hooks/useAssignableInstances.js b/client/src/hooks/useAssignableInstances.js
new file mode 100644
index 0000000000..8fab02a38e
--- /dev/null
+++ b/client/src/hooks/useAssignableInstances.js
@@ -0,0 +1,32 @@
+import { useState, useEffect } from 'react';
+import { getAssignableInstances } from '../services/apiSystem';
+
+// The federated instances a CoS task may be pinned to (#4520) — this machine
+// plus every peer that has advertised a federation identity.
+//
+// Silent by design: a non-federated install has exactly one entry (itself) and
+// the surfaces that consume this hide their picker entirely, so a failed or
+// empty read must not toast. `instances` starts as `null` — "not fetched yet",
+// distinct from `[]` ("fetched, nothing assignable") — so a caller can tell a
+// still-loading render from a genuinely empty registry.
+export default function useAssignableInstances() {
+ const [instances, setInstances] = useState(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ getAssignableInstances({ silent: true })
+ .then((data) => {
+ if (cancelled) return;
+ setInstances(Array.isArray(data?.instances) ? data.instances : []);
+ })
+ .catch(() => { if (!cancelled) setInstances([]); });
+ return () => { cancelled = true; };
+ }, []);
+
+ // A single instance means "not federated" — nothing to choose between, so
+ // callers gate their picker on this rather than re-deriving the rule. `null`
+ // is passed through deliberately: a consumer must be able to tell "registry
+ // not read yet" from "read, and there is nothing here".
+ const isFederated = Array.isArray(instances) && instances.length > 1;
+ return { instances, loading: instances === null, isFederated };
+}
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index daab6ad076..d3e1962431 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -235,6 +235,8 @@ export const navigateBrowser = (url, options = {}) => request('/browser/navigate
// Instances (Federation)
export const getInstances = (options) => request('/instances', options);
export const getSelfInstance = (options) => request('/instances/self', options);
+// Federated instances a CoS task may be pinned to (#4520): id/name/isSelf only.
+export const getAssignableInstances = (options) => request('/instances/assignable', options);
export const updateSelfInstance = (data) => request('/instances/self', { method: 'PUT', body: JSON.stringify(data) });
export const addPeer = (data) => request('/instances/peers', { method: 'POST', body: JSON.stringify(data) });
export const updatePeer = (id, data) => request(`/instances/peers/${id}`, { method: 'PUT', body: JSON.stringify(data) });
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 99b6a52c9c..1040c83f33 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -968,6 +968,15 @@ const cosTaskDiagnosticsSchema = z.object({
// permanent through the API.
const effortInputSchema = z.preprocess(emptyToUndefined, z.enum(EFFORT_LEVELS).optional());
const effortUpdateSchema = z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable().optional());
+// Federated instance this task is PINNED to (#4520) — only that instance's CoS
+// evaluator claims and runs it. On create, '' from the picker's "Any instance"
+// option → undefined (no pin persisted). On update, ''/null must survive as null
+// so the route can clear an existing pin (absent-vs-cleared, CLAUDE.md).
+// Bounded-but-format-free on purpose: the id vocabulary is whatever the peers in
+// this install's registry advertise, and the route is what checks membership.
+const INSTANCE_ID_MAX_LENGTH = 128;
+const targetInstanceIdInputSchema = z.preprocess(emptyToUndefined, z.string().trim().min(1).max(INSTANCE_ID_MAX_LENGTH).optional());
+const targetInstanceIdUpdateSchema = z.preprocess(emptyToNull, z.string().trim().min(1).max(INSTANCE_ID_MAX_LENGTH).nullable().optional());
const taskTemperatureInputSchema = z.number().min(0).max(2).optional();
const taskTemperatureUpdateSchema = z.number().min(0).max(2).nullable().optional();
@@ -1013,6 +1022,7 @@ export const createCosTaskSchema = z.object({
temperature: taskTemperatureInputSchema,
thinking: z.boolean().optional(),
app: z.string().optional(),
+ targetInstanceId: targetInstanceIdInputSchema,
type: z.string().optional().default('user'),
approvalRequired: z.boolean().optional(),
screenshots: z.array(z.string()).optional(),
@@ -1125,6 +1135,7 @@ export const updateCosTaskSchema = z.object({
temperature: taskTemperatureUpdateSchema,
thinking: z.boolean().nullable().optional(),
app: z.string().optional(),
+ targetInstanceId: targetInstanceIdUpdateSchema,
blockedReason: z.string().optional(),
type: z.string().optional().default('user'),
});
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 7cb3cfee13..ade8440072 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -575,7 +575,16 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v5 fall back to `metadata.context`, so the reverse direction degrades
// gracefully — the gate exists for the forward one. Per-category gate → only
// cos-tasks sync pauses until the peer upgrades.
- cosTasks: 5,
+ // v6 = `metadata.targetInstanceId`, the per-task pin to ONE federated instance
+ // (#4520). Same EXECUTION-semantics break as v3/v4/v5 — the pin rides the
+ // permissive `metadata` map, so a ≤v5 receiver validates and stores the task
+ // fine and then RUNS IT ANYWAY: its spawn guards only know the opportunistic
+ // claim/lease, so the laptop happily claims the task the user pinned to the
+ // GPU box, executes it with the wrong hardware/tooling, and LWW-pushes that
+ // run's state back onto the v6 peer — which by then had correctly passed over
+ // the task. Per-category gate → only cos-tasks sync pauses until the peer
+ // upgrades.
+ cosTasks: 6,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index f7619760e0..36e6224db7 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -26,6 +26,7 @@ import {
buildReviewersCsv,
buildReviewWithArgs,
createCosTaskSchema,
+ updateCosTaskSchema,
featureProviderConfigSchema,
codeReviewSettingsSchema,
locationSettingsSchema,
@@ -1462,6 +1463,30 @@ describe('validation.js', () => {
});
});
+ // #4520: pinning a CoS task to one federated instance. Create treats '' as
+ // "any instance" (no pin persisted); update must preserve ''/null as an
+ // explicit CLEAR, or a pin set once could never be removed through the API.
+ describe('targetInstanceId (#4520)', () => {
+ it('create: keeps a real id and drops the empty picker value', () => {
+ expect(createCosTaskSchema.safeParse({ description: 'x', targetInstanceId: 'instance-bbbb' }).data.targetInstanceId).toBe('instance-bbbb');
+ expect(createCosTaskSchema.safeParse({ description: 'x', targetInstanceId: '' }).data.targetInstanceId).toBeUndefined();
+ expect('targetInstanceId' in createCosTaskSchema.safeParse({ description: 'x' }).data).toBe(false);
+ });
+
+ it('create: rejects an over-long id rather than persisting it', () => {
+ expect(createCosTaskSchema.safeParse({ description: 'x', targetInstanceId: 'a'.repeat(129) }).success).toBe(false);
+ });
+
+ it('update: blank and null both survive as null (the explicit unpin)', () => {
+ expect(updateCosTaskSchema.safeParse({ targetInstanceId: '' }).data.targetInstanceId).toBeNull();
+ expect(updateCosTaskSchema.safeParse({ targetInstanceId: null }).data.targetInstanceId).toBeNull();
+ });
+
+ it('update: an absent field stays absent, so an unrelated edit never unpins', () => {
+ expect('targetInstanceId' in updateCosTaskSchema.safeParse({ description: 'x' }).data).toBe(false);
+ });
+ });
+
describe('createCosTaskSchema reviewers fields', () => {
it('accepts an explicit PR completion policy and rejects unknown values', () => {
expect(createCosTaskSchema.safeParse({ description: 'inspect', prCompletion: 'leave-open' }).success).toBe(true);
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index b4cdcb5561..f8204ec3f6 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -9,6 +9,7 @@ import * as taskWatcher from '../services/taskWatcher.js';
import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
import { buildClaimWorkTask, buildJiraTicketTask } from '../services/cosTaskGenerator.js';
import { getAppById } from '../services/apps.js';
+import { getAssignableInstances } from '../services/instances.js';
import { workTrackerLabel } from '../lib/workTracker.js';
import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } from '../lib/slashdoCatalog.js';
import { NON_PM2_TYPES } from '../services/streamingDetect.js';
@@ -36,6 +37,17 @@ const jiraTicketTaskSchema = z.object({
ticketKey: z.string().trim().regex(/^[A-Za-z][A-Za-z0-9]*-\d+$/, 'Invalid JIRA ticket key'),
});
+// Reject a task pinned to an instance this install does not know (#4520). The
+// picker only offers registry members, so this catches the two ways a bad pin
+// still arrives: a hand-crafted request, and a peer removed between the form
+// render and the submit. A pin no instance matches is worse than none — every
+// peer would pass over the task and it would sit pending forever.
+async function assertAssignableInstance(instanceId) {
+ const assignable = await getAssignableInstances();
+ if (assignable.some(i => i.instanceId === instanceId)) return;
+ throw new ServerError('Unknown instance — pick one of this install\'s federated instances', { status: 400, code: 'UNKNOWN_INSTANCE' });
+}
+
const router = Router();
// GET /api/cos/tasks - Get all tasks (user + internal), grouped by source.
@@ -292,6 +304,7 @@ router.post('/tasks', asyncHandler(async (req, res) => {
const parsed = createCosTaskSchema.safeParse(req.body);
if (!parsed.success) failValidation(parsed);
const { type, ...taskData } = parsed.data;
+ if (taskData.targetInstanceId) await assertAssignableInstance(taskData.targetInstanceId);
const result = await cos.addTask(taskData, type);
if (result?.duplicate) {
@@ -321,9 +334,19 @@ router.put('/tasks/:id', asyncHandler(async (req, res) => {
if (fields.thinking !== undefined) updates.thinking = fields.thinking;
if (fields.app !== undefined) updates.app = fields.app;
+ // Re-pin (or unpin) the federated instance this task runs on (#4520). `null`
+ // is the explicit clear the schema preserves — it lands as `undefined` in the
+ // metadata patch, which the store's undefined-stripping turns into a real key
+ // removal, restoring opportunistic first-claim-wins. Absent leaves the pin
+ // untouched (absent-vs-cleared, CLAUDE.md).
+ if (fields.targetInstanceId !== undefined) {
+ if (fields.targetInstanceId !== null) await assertAssignableInstance(fields.targetInstanceId);
+ updates.metadata = { ...updates.metadata, targetInstanceId: fields.targetInstanceId ?? undefined };
+ }
+
// Set blocker metadata when marking as blocked
if (fields.status === 'blocked' && blockedReason) {
- updates.metadata = { blocker: blockedReason };
+ updates.metadata = { ...updates.metadata, blocker: blockedReason };
}
const result = await cos.updateTask(id, updates, type);
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
new file mode 100644
index 0000000000..ae8522df2f
--- /dev/null
+++ b/server/routes/cosTaskRoutes.test.js
@@ -0,0 +1,130 @@
+/**
+ * Route-level tests for the CoS task create/update endpoints, focused on the
+ * federated instance pin (#4520): the pin must survive to the store on create,
+ * be re-settable and CLEARABLE on update, and be refused when it names an
+ * instance this install doesn't know — a pin nothing matches would leave the
+ * task pending on every peer forever.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/cos.js', () => ({
+ addTask: vi.fn(),
+ updateTask: vi.fn(),
+ getAllTasks: vi.fn(),
+ getUserTasks: vi.fn(),
+ getCosTasks: vi.fn(),
+ getTaskById: vi.fn(),
+ deleteTask: vi.fn(),
+ reorderTasks: vi.fn(),
+ approveTask: vi.fn(),
+ challengeTask: vi.fn(),
+ resolveTaskChallenge: vi.fn(),
+ resolveTaskChallengeWithRecheck: vi.fn(),
+ evaluateTasks: vi.fn(),
+ reviveBlockedTask: vi.fn(),
+}));
+vi.mock('../services/taskWatcher.js', () => ({ refreshTasks: vi.fn() }));
+vi.mock('../services/taskEnhancer.js', () => ({ enhanceTaskPrompt: vi.fn() }));
+vi.mock('../services/cosTaskGenerator.js', () => ({
+ buildClaimWorkTask: vi.fn(),
+ buildJiraTicketTask: vi.fn(),
+}));
+vi.mock('../services/apps.js', () => ({ getAppById: vi.fn() }));
+vi.mock('../services/streamingDetect.js', () => ({ NON_PM2_TYPES: new Set() }));
+vi.mock('../services/instances.js', () => ({ getAssignableInstances: vi.fn() }));
+
+import * as cos from '../services/cos.js';
+import { getAssignableInstances } from '../services/instances.js';
+import cosTaskRoutes from './cosTaskRoutes.js';
+
+const SELF = 'self-instance-id';
+const PEER = 'peer-instance-id';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/cos', cosTaskRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getAssignableInstances.mockResolvedValue([
+ { instanceId: SELF, name: 'workstation', isSelf: true },
+ { instanceId: PEER, name: 'render-box', isSelf: false },
+ ]);
+ cos.addTask.mockImplementation(async (taskData) => ({ id: 'task-1', ...taskData }));
+ cos.updateTask.mockResolvedValue({ id: 'task-1' });
+});
+
+describe('POST /api/cos/tasks — targetInstanceId (#4520)', () => {
+ it('passes a registry-known pin through to addTask', async () => {
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: 'render the shot', targetInstanceId: PEER });
+ expect(res.status).toBe(200);
+ expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({ targetInstanceId: PEER }), 'user');
+ });
+
+ it('rejects a pin naming an instance this install does not know', async () => {
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: 'render the shot', targetInstanceId: 'ghost-instance-id' });
+ expect(res.status).toBe(400);
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('creates an unpinned task without consulting the registry', async () => {
+ const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'anywhere' });
+ expect(res.status).toBe(200);
+ expect(getAssignableInstances).not.toHaveBeenCalled();
+ expect(cos.addTask.mock.calls[0][0].targetInstanceId).toBeUndefined();
+ });
+});
+
+describe('PUT /api/cos/tasks/:id — targetInstanceId (#4520)', () => {
+ const metadataOf = () => cos.updateTask.mock.calls[0][1].metadata;
+
+ it('re-pins a task to a known instance', async () => {
+ const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ targetInstanceId: PEER });
+ expect(res.status).toBe(200);
+ expect(metadataOf()).toEqual({ targetInstanceId: PEER });
+ });
+
+ it('clears the pin on an explicit null — the metadata key is dropped by the store', async () => {
+ const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ targetInstanceId: null });
+ expect(res.status).toBe(200);
+ expect(metadataOf()).toHaveProperty('targetInstanceId', undefined);
+ });
+
+ it('treats the picker\'s empty value as the same explicit clear', async () => {
+ const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ targetInstanceId: '' });
+ expect(res.status).toBe(200);
+ expect(metadataOf()).toHaveProperty('targetInstanceId', undefined);
+ });
+
+ it('leaves the pin untouched when the field is absent from the patch', async () => {
+ const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ description: 'new title' });
+ expect(res.status).toBe(200);
+ expect(cos.updateTask.mock.calls[0][1].metadata).toBeUndefined();
+ });
+
+ it('rejects a re-pin to an unknown instance without writing anything', async () => {
+ const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ targetInstanceId: 'ghost-instance-id' });
+ expect(res.status).toBe(400);
+ expect(cos.updateTask).not.toHaveBeenCalled();
+ });
+
+ it('keeps the blocked reason alongside a pin change rather than overwriting it', async () => {
+ const res = await request(buildApp())
+ .put('/api/cos/tasks/task-1')
+ .send({ status: 'blocked', blockedReason: 'waiting on hardware', targetInstanceId: PEER });
+ expect(res.status).toBe(200);
+ expect(metadataOf()).toEqual({ targetInstanceId: PEER, blocker: 'waiting on hardware' });
+ });
+});
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 8d00a93281..e061d6116f 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -133,6 +133,14 @@ router.get('/', asyncHandler(async (req, res) => {
res.json({ self, peers: peers.map(instances.sanitizePeerForClient), syncStatus });
}));
+// GET /api/instances/assignable — id/name pairs a CoS task may be pinned to
+// (#4520). Deliberately narrower than GET / above: no addresses, no sync state,
+// no peer that has yet to advertise a federation identity — just what the task
+// form's instance picker renders.
+router.get('/assignable', asyncHandler(async (req, res) => {
+ res.json({ instances: await instances.getAssignableInstances() });
+}));
+
// GET /api/instances/sync-status — local sync sequences + checksums (used by peers during probe)
// A probing peer may pass `?forPeer=<its instanceId>` to also receive OUR cursor
// into its data (`cursorForYou`) — how far we've pulled from it. That cursor is
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index 84c085bb75..f0ecf1027b 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -12,6 +12,7 @@ vi.mock('../services/syncOrchestrator.js', () => ({
vi.mock('../services/instances.js', () => ({
updatePeer: vi.fn(),
sanitizePeerForClient: vi.fn((peer) => peer),
+ getAssignableInstances: vi.fn(),
}));
vi.mock('../services/sharing/peerSync.js', () => ({
getFullSyncCoverageForPeer: vi.fn(),
@@ -35,6 +36,31 @@ const buildApp = () => {
return app;
};
+// #4520: the CoS task form's instance picker reads this. It is deliberately
+// narrower than GET /api/instances — no addresses, no sync state, no peer that
+// has yet to advertise a federation identity.
+describe('GET /api/instances/assignable', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns the assignable id/name pairs the picker renders', async () => {
+ const assignable = [
+ { instanceId: 'self-id', name: 'workstation', isSelf: true },
+ { instanceId: 'peer-id', name: 'render-box', isSelf: false }
+ ];
+ instances.getAssignableInstances.mockResolvedValue(assignable);
+ const res = await request(buildApp()).get('/api/instances/assignable');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ instances: assignable });
+ });
+
+ it('is not shadowed by the peer routes — a real handler answers it', async () => {
+ instances.getAssignableInstances.mockResolvedValue([]);
+ const res = await request(buildApp()).get('/api/instances/assignable');
+ expect(res.status).toBe(200);
+ expect(instances.getAssignableInstances).toHaveBeenCalled();
+ });
+});
+
describe('GET /api/instances/sync-status — forPeer scoping', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index f208530d08..5fb3ce7273 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -62,7 +62,7 @@ import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSetti
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import { releaseAppReviewMarker } from './appActivity.js';
import { ensureInstanceId } from './instances.js';
-import { isClaimableBy, buildClaim, buildRelease, getClaimOwner } from './cosTaskClaim.js';
+import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';
import { resolveForgeTokenEnv } from './git.js';
import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
@@ -163,6 +163,15 @@ async function runAgentSpawn(task) {
emitLog('error', `Failed to resolve instance identity for task ${task.id}: ${err?.message || err}`, { taskId: task.id });
return null;
}
+ // Targeted assignment guard (issue #4520). A task pinned to a specific
+ // federated instance runs ONLY there — every other peer passes over it, even
+ // when it is unclaimed and this instance is idle. Checked before the lease so
+ // the log names the standing decision rather than a transient claim. Unpinned
+ // tasks (the default) reach the opportunistic lease check unchanged.
+ if (isTargetedElsewhere(task.metadata, instanceId)) {
+ console.log(`📍 Task ${task.id} is assigned to instance ${getTargetInstance(task.metadata)} — skipping spawn on ${instanceId}`);
+ return null;
+ }
if (!isClaimableBy(task.metadata, instanceId)) {
console.log(`🔒 Task ${task.id} is claimed by instance ${getClaimOwner(task.metadata)} (live lease) — skipping spawn on ${instanceId}`);
return null;
@@ -263,6 +272,14 @@ async function runAgentSpawn(task) {
await cleanupOnError('retry held pending cleanup');
return null;
}
+ // Re-check the pin against the freshest record (#4520): the dequeued snapshot
+ // may predate a reassignment that synced in from a peer, and a task
+ // reassigned mid-dispatch must not be started here.
+ if (isTargetedElsewhere(freshTask.metadata, instanceId)) {
+ console.log(`📍 Task ${task.id} is assigned to instance ${getTargetInstance(freshTask.metadata)} — yielding on ${instanceId}`);
+ await cleanupOnError('assigned to another instance');
+ return null;
+ }
// The task is persisted — honor a peer's claim that synced in since dispatch,
// then take the lease up front.
if (!isClaimableBy(freshTask.metadata, instanceId)) {
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 3c9155648f..ff903c164e 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -624,6 +624,27 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'
expect(guardIdx, 'the claim guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
});
+ // #4520: a task pinned to a specific federated instance runs ONLY there. The
+ // pin is a standing decision, so it gates the spawn ahead of the opportunistic
+ // lease check — and is re-checked against the fresh record, because a
+ // reassignment can sync in between the dequeue and the claim.
+ it('refuses to spawn a task pinned to another instance, before the lease check', () => {
+ const targetIdx = RUN_SPAWN_BODY.indexOf('isTargetedElsewhere(task.metadata, instanceId)');
+ const leaseIdx = RUN_SPAWN_BODY.indexOf('isClaimableBy(task.metadata, instanceId)');
+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');
+ expect(targetIdx, 'must gate the spawn on isTargetedElsewhere').toBeGreaterThan(-1);
+ expect(targetIdx, 'the pin guard must run BEFORE the lease guard').toBeLessThan(leaseIdx);
+ expect(targetIdx, 'the pin guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
+ });
+
+ it('re-checks the pin against the freshest task, before claiming it', () => {
+ const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');
+ const recheckIdx = RUN_SPAWN_BODY.indexOf('isTargetedElsewhere(freshTask.metadata, instanceId)');
+ const acquireIdx = RUN_SPAWN_BODY.indexOf('metadata: buildClaim(instanceId)');
+ expect(recheckIdx, 'must re-check the pin against the fresh metadata').toBeGreaterThan(rereadIdx);
+ expect(recheckIdx, 'the fresh pin re-check must precede taking the claim').toBeLessThan(acquireIdx);
+ });
+
it('stamps the federation claim into the in_progress task update', () => {
expect(AGENT_LIFECYCLE_SRC).toMatch(/\.\.\.buildClaim\(instanceId\)/);
});
diff --git a/server/services/cos.js b/server/services/cos.js
index 77ed2e75c8..e2263e1519 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -77,7 +77,7 @@ export { runHealthCheck, getHealthStatus };
import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';
export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };
import { ensureInstanceId } from './instances.js';
-import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
+import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner, getSkipReason } from './cosTaskClaim.js';
import { retryTasksResolvedByInvestigation } from './investigationRetry.js';
import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';
@@ -967,12 +967,14 @@ async function spawnDequeuePriority1UserTasks(ctx) {
for (const task of pendingUserTasks) {
if (capacity.spawned >= capacity.availableSlots) break;
- // A federated peer holds a live lease on this task (#1650) — it's being
- // worked on the other machine. Skip it during candidate selection so it
- // doesn't consume this cycle's spawn slot (the spawn guard would return
- // null anyway) and starve later unclaimed tasks.
- if (isHeldByOther(task.metadata, instanceId)) {
- emitLog('debug', `Skipping user task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ // Not runnable here: the task is pinned to another instance (#4520), or a
+ // federated peer holds a live lease on it (#1650) and is working it on the
+ // other machine. Skip it during candidate selection so it doesn't consume
+ // this cycle's spawn slot (the spawn guard would return null anyway) and
+ // starve later runnable tasks.
+ const skipReason = getSkipReason(task.metadata, instanceId);
+ if (skipReason) {
+ emitLog('debug', `Skipping user task ${task.id} — ${skipReason}`, { taskId: task.id });
continue;
}
if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
@@ -1050,7 +1052,7 @@ async function spawnDequeuePriority2AutoApproved(ctx) {
isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
cooldownExempt: isCooldownExemptTask,
extraSkip: isDisabledAnalysisType,
- heldByOther: (task) => isHeldByOther(task.metadata, instanceId)
+ notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null
});
for (const task of wouldSpawn) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
@@ -1059,11 +1061,12 @@ async function spawnDequeuePriority2AutoApproved(ctx) {
} else {
for (const task of autoApproved) {
if (capacity.spawned >= autonomousSpawnCeiling) break;
- // A federated peer holds a live lease on this task (#1650) — skip it
- // during candidate selection so it doesn't consume an autonomous slot
- // the spawn guard would just reject.
- if (isHeldByOther(task.metadata, instanceId)) {
- emitLog('debug', `Skipping system task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ // Pinned to another instance (#4520), or a federated peer holds a live
+ // lease on it (#1650) — skip it during candidate selection so it doesn't
+ // consume an autonomous slot the spawn guard would just reject.
+ const skipReason = getSkipReason(task.metadata, instanceId);
+ if (skipReason) {
+ emitLog('debug', `Skipping system task ${task.id} — ${skipReason}`, { taskId: task.id });
continue;
}
if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
diff --git a/server/services/cosTaskClaim.js b/server/services/cosTaskClaim.js
index 1650018d36..c5d55bfc59 100644
--- a/server/services/cosTaskClaim.js
+++ b/server/services/cosTaskClaim.js
@@ -128,3 +128,57 @@ export function buildRenewal(metadata, instanceId, { now = Date.now(), leaseMs =
export function buildRelease() {
return Object.fromEntries(CLAIM_METADATA_KEYS.map((k) => [k, undefined]));
}
+
+// ── Targeted assignment (issue #4520) ────────────────────────────────────────
+//
+// The claim/lease above is OPPORTUNISTIC: whichever peer evaluates a shared task
+// first takes it. `metadata.targetInstanceId` is the opt-in override — the user
+// pins a task to ONE federated instance ("run this generation task on the GPU
+// box, not the laptop") and every other peer passes over it on sight. Absent
+// (the default) restores the opportunistic behavior exactly.
+//
+// This is a cheap read-only guard alongside the lease check, NOT a second
+// locking primitive: it decides *eligibility*, the lease still decides *who is
+// currently running it*. A task pinned to an instance that has left the
+// federation stops being spawnable anywhere — deliberate, and recoverable by
+// clearing the assignment from the task editor.
+export const TARGET_INSTANCE_KEY = 'targetInstanceId';
+
+/**
+ * The instance this task is pinned to, or null when it is unpinned (runnable by
+ * any peer). Trims so a whitespace-only value reads as unpinned rather than as
+ * a target no instance can ever match.
+ */
+export function getTargetInstance(metadata) {
+ const target = metadata?.[TARGET_INSTANCE_KEY];
+ if (typeof target !== 'string') return null;
+ const trimmed = target.trim();
+ return trimmed === '' ? null : trimmed;
+}
+
+/**
+ * Is this task pinned to a DIFFERENT instance than `instanceId`? An unpinned
+ * task is never "elsewhere", so a non-federated install answers false for every
+ * task and behaves exactly as it did before the field existed.
+ */
+export function isTargetedElsewhere(metadata, instanceId) {
+ const target = getTargetInstance(metadata);
+ return target !== null && target !== instanceId;
+}
+
+/**
+ * Why should THIS instance pass over the task during candidate selection, as a
+ * log-ready phrase — or null when the task is a candidate here.
+ *
+ * Both spawn engines (`dequeueNextTask` in cos.js, `evaluateTasks` in
+ * cosTaskGenerator.js) ask this same two-part question at four call sites, so it
+ * lives here rather than being re-expressed at each one. Order matters only for
+ * the message: the pin is a standing decision, the lease is transient, so the
+ * pin is reported first when both apply.
+ */
+export function getSkipReason(metadata, instanceId, now = Date.now()) {
+ const target = getTargetInstance(metadata);
+ if (target !== null && target !== instanceId) return `assigned to instance ${target}`;
+ if (isHeldByOther(metadata, instanceId, now)) return `live lease held by peer instance ${getClaimOwner(metadata)}`;
+ return null;
+}
diff --git a/server/services/cosTaskClaim.test.js b/server/services/cosTaskClaim.test.js
index 2efffef82a..ddcbc47c36 100644
--- a/server/services/cosTaskClaim.test.js
+++ b/server/services/cosTaskClaim.test.js
@@ -8,7 +8,11 @@ import {
isHeldByOther,
buildClaim,
buildRenewal,
- buildRelease
+ buildRelease,
+ TARGET_INSTANCE_KEY,
+ getTargetInstance,
+ isTargetedElsewhere,
+ getSkipReason
} from './cosTaskClaim.js';
const A = 'instance-aaaa';
@@ -163,3 +167,67 @@ describe('two-instance claim simulation (#1563 acceptance criterion 5)', () => {
expect(isClaimableBy(task.metadata, B, T0)).toBe(true);
});
});
+
+describe('targeted assignment (#4520)', () => {
+ describe('getTargetInstance', () => {
+ it('returns the pinned instance, or null when unpinned', () => {
+ expect(getTargetInstance({ [TARGET_INSTANCE_KEY]: A })).toBe(A);
+ expect(getTargetInstance({})).toBeNull();
+ expect(getTargetInstance(null)).toBeNull();
+ });
+ it('treats a blank / whitespace-only / non-string pin as unpinned', () => {
+ // A pin no instance can match would strand the task unrunnable everywhere,
+ // so an empty value must read as "any instance", not as a target.
+ expect(getTargetInstance({ [TARGET_INSTANCE_KEY]: '' })).toBeNull();
+ expect(getTargetInstance({ [TARGET_INSTANCE_KEY]: ' ' })).toBeNull();
+ expect(getTargetInstance({ [TARGET_INSTANCE_KEY]: 42 })).toBeNull();
+ });
+ it('trims a padded pin so it still matches its instance id', () => {
+ expect(getTargetInstance({ [TARGET_INSTANCE_KEY]: ` ${A} ` })).toBe(A);
+ });
+ });
+
+ describe('isTargetedElsewhere', () => {
+ it('false for an unpinned task — the pre-#4520 default is unchanged', () => {
+ expect(isTargetedElsewhere({}, A)).toBe(false);
+ expect(isTargetedElsewhere({ claimedBy: B }, A)).toBe(false);
+ });
+ it('false on the instance the task is pinned to', () => {
+ expect(isTargetedElsewhere({ [TARGET_INSTANCE_KEY]: A }, A)).toBe(false);
+ });
+ it('true on every other instance', () => {
+ expect(isTargetedElsewhere({ [TARGET_INSTANCE_KEY]: B }, A)).toBe(true);
+ });
+ });
+
+ describe('getSkipReason', () => {
+ it('null for an unclaimed, unpinned task', () => {
+ expect(getSkipReason({}, A, T0)).toBeNull();
+ });
+ it('null for a task pinned here, even while this instance holds the lease', () => {
+ const metadata = { ...buildClaim(A, { now: T0 }), [TARGET_INSTANCE_KEY]: A };
+ expect(getSkipReason(metadata, A, T0)).toBeNull();
+ });
+ it('names the pin when the task belongs to another instance', () => {
+ expect(getSkipReason({ [TARGET_INSTANCE_KEY]: B }, A, T0)).toContain(B);
+ });
+ it('skips a task pinned elsewhere even when it is idle and unclaimed', () => {
+ // Acceptance criterion 1: peer A must pass over peer B's task while both
+ // are idle — the pin, not the lease, is what holds it back.
+ expect(getSkipReason({ [TARGET_INSTANCE_KEY]: B }, A, T0)).not.toBeNull();
+ });
+ it('names the lease when an unpinned task is held by a peer', () => {
+ const reason = getSkipReason(buildClaim(B, { now: T0 }), A, T0);
+ expect(reason).toContain(B);
+ expect(reason).toContain('lease');
+ });
+ it('reports the pin ahead of the lease when both apply', () => {
+ const metadata = { ...buildClaim(B, { now: T0 }), [TARGET_INSTANCE_KEY]: B };
+ expect(getSkipReason(metadata, A, T0)).not.toContain('lease');
+ });
+ it('null once a peer lease expires on an unpinned task', () => {
+ const metadata = buildClaim(B, { now: T0 });
+ expect(getSkipReason(metadata, A, T0 + LEASE_DURATION_MS + 1)).toBeNull();
+ });
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a74177302a..4970cb7234 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -39,7 +39,7 @@ import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safet
import { generateProactiveTasks as generateMissionTasks } from './missions.js';
import { isRecoveryTask } from './recoveryTasks.js';
import { getCodeReviewDefaults } from './codeReview.js';
-import { isHeldByOther, getClaimOwner } from './cosTaskClaim.js';
+import { getSkipReason } from './cosTaskClaim.js';
import { ensureInstanceId } from './instances.js';
import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { resolveTrackerFilingBlock } from '../lib/workTracker.js';
@@ -150,7 +150,7 @@ export function isCooldownExemptTask(task) {
* @param {(appId: string) => Promise<boolean>} ctx.isOnCooldown - async cooldown probe
* @param {(task: object) => boolean} [ctx.cooldownExempt] - true ⇒ skip the cooldown gate for this task
* @param {(task: object) => boolean} [ctx.extraSkip] - true ⇒ task ineligible (engine-specific gate)
- * @param {(task: object) => boolean} [ctx.heldByOther] - true ⇒ a federated peer holds a live lease on this task (#1650); the execute path skips it before spawning, so the dry-run plan must too
+ * @param {(task: object) => boolean} [ctx.notRunnableHere] - true ⇒ this instance would pass over the task anyway: it is pinned to another instance (#4520) or a federated peer holds a live lease on it (#1650). The execute path skips it before spawning, so the dry-run plan must too
* @returns {Promise<object[]>} the tasks execute mode would spawn, in order
*/
export async function selectDryRunAutoApproved(autoApproved, ctx) {
@@ -162,7 +162,7 @@ export async function selectDryRunAutoApproved(autoApproved, ctx) {
isOnCooldown,
cooldownExempt = () => false,
extraSkip = () => false,
- heldByOther = () => false
+ notRunnableHere = () => false
} = ctx;
const counts = { ...spawnProjectCounts };
@@ -171,7 +171,7 @@ export async function selectDryRunAutoApproved(autoApproved, ctx) {
for (const task of autoApproved) {
if (spawned >= availableSlots) break;
- if (heldByOther(task)) continue;
+ if (notRunnableHere(task)) continue;
if (exceedsMaxSpawns(task)) continue;
if (extraSkip(task)) continue;
const appId = task.metadata?.app;
@@ -1097,12 +1097,14 @@ async function spawnPriority1UserTasks(ctx) {
const { pendingUserTasks, availableSlots, perProjectLimit, tasksToSpawn, canSpawnTask, trackSpawn, instanceId } = ctx;
for (const task of pendingUserTasks) {
if (tasksToSpawn.length >= availableSlots) break;
- // A federated peer holds a live lease on this task (#1650) — it's being
- // worked on the other machine. Skip it during candidate selection so it
- // doesn't consume this cycle's spawn slot (the spawn guard would return
- // null anyway) and starve later unclaimed tasks.
- if (isHeldByOther(task.metadata, instanceId)) {
- emitLog('debug', `Skipping user task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ // Not runnable here: the task is pinned to another instance (#4520), or a
+ // federated peer holds a live lease on it (#1650) and is working it on the
+ // other machine. Skip it during candidate selection so it doesn't consume
+ // this cycle's spawn slot (the spawn guard would return null anyway) and
+ // starve later runnable tasks.
+ const skipReason = getSkipReason(task.metadata, instanceId);
+ if (skipReason) {
+ emitLog('debug', `Skipping user task ${task.id} — ${skipReason}`, { taskId: task.id });
continue;
}
if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
@@ -1134,8 +1136,9 @@ async function spawnPriority2AutoApproved(ctx) {
if (tasksToSpawn.length < autonomousSlotCeiling && cosTaskData.exists && cosAutonomyMode !== 'execute') {
if (cosAutonomyMode === 'dry-run') {
// Log only the tasks execute mode would ACTUALLY spawn — applying the same
- // peer-lease / max-spawns / cooldown / per-project gates against virtual
- // capacity — rather than every auto-approved task regardless of eligibility.
+ // instance-pin / peer-lease / max-spawns / cooldown / per-project gates
+ // against virtual capacity — rather than every auto-approved task
+ // regardless of eligibility.
const wouldSpawn = await selectDryRunAutoApproved(cosTaskData.autoApproved || [], {
availableSlots: autonomousSlotCeiling,
alreadySpawned: tasksToSpawn.length,
@@ -1143,7 +1146,7 @@ async function spawnPriority2AutoApproved(ctx) {
spawnProjectCounts,
isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
cooldownExempt: isCooldownExemptTask,
- heldByOther: (task) => isHeldByOther(task.metadata, instanceId)
+ notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null
});
for (const task of wouldSpawn) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
@@ -1154,11 +1157,12 @@ async function spawnPriority2AutoApproved(ctx) {
for (const task of autoApproved) {
if (tasksToSpawn.length >= autonomousSlotCeiling) break;
- // A federated peer holds a live lease on this task (#1650) — skip it
- // during candidate selection so it doesn't consume an autonomous slot
- // the spawn guard would just reject.
- if (isHeldByOther(task.metadata, instanceId)) {
- emitLog('debug', `Skipping system task ${task.id} — live lease held by peer instance ${getClaimOwner(task.metadata)}`, { taskId: task.id });
+ // Pinned to another instance (#4520), or a federated peer holds a live
+ // lease on it (#1650) — skip it during candidate selection so it doesn't
+ // consume an autonomous slot the spawn guard would just reject.
+ const skipReason = getSkipReason(task.metadata, instanceId);
+ if (skipReason) {
+ emitLog('debug', `Skipping system task ${task.id} — ${skipReason}`, { taskId: task.id });
continue;
}
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index d1c702e7df..b1b66420ce 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -259,19 +259,19 @@ describe('both on-demand engines apply consent before addTask', () => {
});
});
-// #1650: once a peer's claim/lease is visible via task-record federation, a
-// task whose live lease belongs to ANOTHER instance must be skipped during
-// candidate selection — BEFORE the engine emits `task:ready` + trackSpawn.
-// Otherwise that peer-claimed task (often the highest-priority pick) consumes
-// this instance's spawn slot every cycle (the spawn guard then returns null,
-// spawning nothing) and starves later unclaimed tasks. Both spawn engines
-// (dequeueNextTask in cos.js, evaluateTasks here) must apply it, in both their
-// execute loops AND their dry-run plan.
-describe('peer-claim skip during candidate selection (#1650)', () => {
- it('both engines import isHeldByOther from the shared claim module', () => {
+// #1650/#4520: a task this instance must not run — a live lease held by ANOTHER
+// instance, or a pin naming another instance — must be skipped during candidate
+// selection, BEFORE the engine emits `task:ready` + trackSpawn. Otherwise that
+// task (often the highest-priority pick) consumes this instance's spawn slot
+// every cycle (the spawn guard then returns null, spawning nothing) and starves
+// later runnable tasks. Both spawn engines (dequeueNextTask in cos.js,
+// evaluateTasks here) must apply it, in both their execute loops AND their
+// dry-run plan. `getSkipReason` answers both halves in one call.
+describe('not-runnable-here skip during candidate selection (#1650, #4520)', () => {
+ it('both engines import getSkipReason from the shared claim module', () => {
expect(COS_SRC).toContain("from './cosTaskClaim.js'");
- expect(COS_SRC).toMatch(/import\s*\{[^}]*isHeldByOther[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);
- expect(GEN_SRC).toMatch(/import\s*\{[^}]*isHeldByOther[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);
+ expect(COS_SRC).toMatch(/import\s*\{[^}]*getSkipReason[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);
+ expect(GEN_SRC).toMatch(/import\s*\{[^}]*getSkipReason[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);
});
it('both engines resolve this instance id once per cycle via ensureInstanceId', () => {
@@ -279,18 +279,20 @@ describe('peer-claim skip during candidate selection (#1650)', () => {
expect(GEN_SRC).toContain('const instanceId = await ensureInstanceId();');
});
- it('both engines skip peer-held tasks in their EXECUTE candidate loops', () => {
- // Each engine must have the live-lease skip in BOTH the user-task and the
- // auto-approved tiers — at least two execute-path skip sites per engine.
- const cosSkips = COS_SRC.match(/if\s*\(isHeldByOther\(task\.metadata,\s*instanceId\)\)/g) || [];
- const genSkips = GEN_SRC.match(/if\s*\(isHeldByOther\(task\.metadata,\s*instanceId\)\)/g) || [];
+ it('both engines skip not-runnable-here tasks in their EXECUTE candidate loops', () => {
+ // Each engine must have the skip in BOTH the user-task and the auto-approved
+ // tiers — at least two execute-path skip sites per engine.
+ const cosSkips = COS_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\);\n\s*if \(skipReason\)/g) || [];
+ const genSkips = GEN_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\);\n\s*if \(skipReason\)/g) || [];
expect(cosSkips.length).toBeGreaterThanOrEqual(2);
expect(genSkips.length).toBeGreaterThanOrEqual(2);
});
- it('both engines pass heldByOther into their dry-run plan so it matches execute', () => {
- expect(COS_SRC).toContain('heldByOther: (task) => isHeldByOther(task.metadata, instanceId)');
- expect(GEN_SRC).toContain('heldByOther: (task) => isHeldByOther(task.metadata, instanceId)');
+ it('both engines pass notRunnableHere into their dry-run plan so it matches execute', () => {
+ // Covers BOTH reasons this instance passes over a task at spawn time: a
+ // peer's live lease (#1650) and a pin to another instance (#4520).
+ expect(COS_SRC).toContain('notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null');
+ expect(GEN_SRC).toContain('notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null');
});
});
@@ -902,7 +904,7 @@ describe('selectDryRunAutoApproved', () => {
const tasks = [task('1', { claimedBy: 'peer' }), task('2'), task('3', { claimedBy: 'peer' })];
const out = await selectDryRunAutoApproved(tasks, {
...baseCtx,
- heldByOther: (t) => t.metadata?.claimedBy === 'peer'
+ notRunnableHere: (t) => t.metadata?.claimedBy === 'peer'
});
expect(out.map(t => t.id)).toEqual(['2']);
});
@@ -914,7 +916,7 @@ describe('selectDryRunAutoApproved', () => {
const out = await selectDryRunAutoApproved(tasks, {
...baseCtx,
perProjectLimit: 1,
- heldByOther: (t) => t.metadata?.claimedBy === 'peer'
+ notRunnableHere: (t) => t.metadata?.claimedBy === 'peer'
});
expect(out.map(t => t.id)).toEqual(['2']);
});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 2a852bbd6e..307cb62394 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -28,7 +28,7 @@ import { PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../
import { splitTaskPromptFields } from '../lib/cosTaskPrompt.js';
import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
-import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
+import { CLAIM_METADATA_KEYS, TARGET_INSTANCE_KEY, getTargetInstance } from './cosTaskClaim.js';
import { mergeTaskLists } from './cosTaskMerge.js';
import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
@@ -333,6 +333,14 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (taskData.temperature !== undefined) metadata.temperature = taskData.temperature;
if (taskData.thinking !== undefined) metadata.thinking = taskData.thinking;
if (taskData.app) metadata.app = taskData.app;
+ // Pin this task to ONE federated instance (#4520): only that instance's CoS
+ // evaluator claims and runs it, every other peer passes over it. Absent —
+ // the default — leaves the opportunistic first-claim-wins behavior intact.
+ // Normalized through the same reader the spawn guards use, so a blank or
+ // whitespace-only value stores as unpinned rather than as a target no
+ // instance can ever match.
+ const targetInstance = getTargetInstance(taskData);
+ if (targetInstance) metadata[TARGET_INSTANCE_KEY] = targetInstance;
// Tags a task dispatched by the voice code-agent tool so the proactive
// speech layer can announce its completion (see voice/proactiveTriggers.js).
if (taskData.voiceDispatch === true) metadata.voiceDispatch = true;
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index b5b5294706..aa60f5299f 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -323,6 +323,31 @@ describe('cosTaskStore.addTask', () => {
expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'added' && e.payload.type === 'user')).toBe(true);
});
+ describe('targeted instance pin (#4520)', () => {
+ it('persists targetInstanceId and round-trips it through markdown', async () => {
+ const created = await addTask({ description: 'gpu work', id: 'task-pin', targetInstanceId: 'instance-bbbb' }, 'user');
+ expect(created.metadata.targetInstanceId).toBe('instance-bbbb');
+ expect((await getTaskById('task-pin')).metadata.targetInstanceId).toBe('instance-bbbb');
+ });
+
+ it('omits the key entirely when unpinned, so the default stays opportunistic', async () => {
+ const created = await addTask({ description: 'anywhere', id: 'task-nopin' }, 'user');
+ expect('targetInstanceId' in created.metadata).toBe(false);
+ });
+
+ it('treats a blank pin as unpinned rather than a target nothing can match', async () => {
+ const created = await addTask({ description: 'blank', id: 'task-blankpin', targetInstanceId: ' ' }, 'user');
+ expect('targetInstanceId' in created.metadata).toBe(false);
+ });
+
+ it('clears the pin when an update passes it as undefined', async () => {
+ await addTask({ description: 'repin', id: 'task-repin', targetInstanceId: 'instance-bbbb' }, 'user');
+ const cleared = await updateTask('task-repin', { metadata: { targetInstanceId: undefined } }, 'user');
+ expect('targetInstanceId' in cleared.metadata).toBe(false);
+ expect((await getTaskById('task-repin')).metadata.targetInstanceId).toBeUndefined();
+ });
+ });
+
describe('prompt / context split (#4153)', () => {
const AGENT_BODY = 'Improve Example App\n\n## Phase 1\nRead PLAN.md.';
diff --git a/server/services/instances.js b/server/services/instances.js
index 34c954fb6f..5277adf702 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -224,6 +224,28 @@ export async function ensureInstanceId() {
return instanceId;
}
+/**
+ * The instances this install can direct a CoS task at (#4520): this machine
+ * plus every peer whose federation identity is known. A peer that has never
+ * completed a probe/connect still carries `instanceId: null` — it has no
+ * addressable identity yet, so offering it would let a user pin a task to a
+ * target no instance can ever match, stranding it unrunnable on every peer.
+ * Returns only the id/name/isSelf triple the picker needs; no addresses, no
+ * credentials.
+ */
+export async function getAssignableInstances() {
+ const data = await loadData();
+ const assignable = [];
+ if (data.self?.instanceId) {
+ assignable.push({ instanceId: data.self.instanceId, name: data.self.name || 'This instance', isSelf: true });
+ }
+ for (const peer of data.peers || []) {
+ if (!peer.instanceId) continue;
+ assignable.push({ instanceId: peer.instanceId, name: peer.name || peer.address || peer.instanceId, isSelf: false });
+ }
+ return assignable;
+}
+
export async function updateSelf(name, { defaultPeerFullSync } = {}) {
return withData(async (data) => {
if (!data.self) return null;
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index f826b6a598..94c464ec59 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -65,6 +65,7 @@ import {
getInstanceId,
updateSelf,
getPeers,
+ getAssignableInstances,
addPeer,
removePeer,
updatePeer,
@@ -205,6 +206,43 @@ describe('instances.js', () => {
});
});
+ // --- Assignable instances (#4520) ---
+
+ describe('getAssignableInstances', () => {
+ it('lists self plus every peer that has advertised a federation identity', async () => {
+ readJSONFile.mockResolvedValue({
+ self: { instanceId: 'self-id', name: 'workstation' },
+ peers: [
+ { id: 'p1', instanceId: 'peer-id', name: 'render-box', address: '192.0.2.10' },
+ // Never probed: no federation identity yet, so pinning to it would
+ // strand the task unrunnable on every peer.
+ { id: 'p2', instanceId: null, name: 'not-yet-connected', address: '192.0.2.11' }
+ ]
+ });
+ expect(await getAssignableInstances()).toEqual([
+ { instanceId: 'self-id', name: 'workstation', isSelf: true },
+ { instanceId: 'peer-id', name: 'render-box', isSelf: false }
+ ]);
+ });
+
+ it('is empty before this install has an identity of its own', async () => {
+ readJSONFile.mockResolvedValue({ self: null, peers: [] });
+ expect(await getAssignableInstances()).toEqual([]);
+ });
+
+ it('falls back to a peer address, then its id, when the peer is unnamed', async () => {
+ readJSONFile.mockResolvedValue({
+ self: { instanceId: 'self-id', name: 'workstation' },
+ peers: [
+ { id: 'p1', instanceId: 'peer-a', name: '', address: '192.0.2.10' },
+ { id: 'p2', instanceId: 'peer-b', name: '', address: '' }
+ ]
+ });
+ const assignable = await getAssignableInstances();
+ expect(assignable.map(i => i.name)).toEqual(['workstation', '192.0.2.10', 'peer-b']);
+ });
+ });
+
// --- Peer CRUD ---
describe('getPeers', () => {
diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.js
index 695e75007e..f2ce56824a 100644
--- a/server/services/sharing/cosTasksSync.test.js
+++ b/server/services/sharing/cosTasksSync.test.js
@@ -69,7 +69,7 @@ describe('buildCosTasksPayload', () => {
vi.mocked(getUserTasks).mockResolvedValue({ tasks: [task('task-a', 'pending')] });
vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress', { metadata: { claimedBy: 'i1' } })] });
const p = await buildCosTasksPayload();
- expect(p.schemaVersion).toBe(5); // v5: metadata.prompt / metadata.context split (#4153)
+ expect(p.schemaVersion).toBe(6); // v6: metadata.targetInstanceId — per-task instance pin (#4520)
expect(p.listHash).toMatch(/^[a-f0-9]{64}$/);
expect(p.tasks).toHaveLength(2);
const user = p.tasks.find((t) => t.id === 'task-a');
@@ -104,7 +104,7 @@ describe('buildCosTasksPayload', () => {
it('returns an empty payload when there are no tasks', async () => {
const p = await buildCosTasksPayload();
expect(p.tasks).toEqual([]);
- expect(p.schemaVersion).toBe(5); // v5: metadata.prompt / metadata.context split (#4153)
+ expect(p.schemaVersion).toBe(6); // v6: metadata.targetInstanceId — per-task instance pin (#4520)
});
});