Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/de/platform/projects/project-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ Um dem Projekt einen eigenen Agenten zu geben, wähle **Neuer Agent**. Ab dann b

## Einen Agenten ändern oder entfernen

Wenn du einen bestehenden Agenten bearbeitest, prüft Tale beim Speichern, ob seine Einstellungen seit dem Öffnen geändert wurden. Hat jemand anderes zuerst gespeichert, wird dein Speichern abgelehnt und deine ungespeicherten Änderungen bleiben im Dialog. Kopiere die Änderungen, die du behalten möchtest, bevor du ihn schließt. Öffne den Agenten dann erneut, um die aktuellen Einstellungen zu laden, und füge deine Änderungen ein, bevor du wieder speicherst.

Bearbeite oder lösche den Agenten über sein Zeilenmenü. Der Standard-Agent hat nur **Agent löschen**. Änderungen gelten für spätere Läufe; ein aktiver Lauf behält seine Startkonfiguration. Die Löschung entfernt Agentenzuweisungen von Aufgaben, erhält aber deren Verlauf. Sie löscht außerdem die [Sandbox-Arbeitsbereiche](/de/platform/admin/sandboxes#explain-why-a-workspace-disappeared) des Agenten samt Dateien, auch die der Mitglieder. Prüfe laufende Arbeit und sichere benötigte Ergebnisse, bevor du den zugehörigen Agenten entfernst.

Scheitert das Erstellen, lies die Begründung: Ein doppelter Name, fehlender Projektzugriff, ein nicht verfügbares Modell und unsichtbare Skills sind unterschiedliche Ursachen. Ein Lauf, der endgültig scheitert, sagt oben in seiner Aufgabe, was schiefging und wer es beheben kann; [Wenn der Agent nicht fertig wird](/de/platform/projects/task-automation#wenn-der-agent-nicht-fertig-wird) zählt die Fälle auf. Neue Anweisungen beheben diese Voraussetzungen nicht.
2 changes: 2 additions & 0 deletions docs/en/platform/projects/project-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ To give the project an agent of its own, select **New agent**. From then on, the

## Update or remove an agent

When you edit an existing agent, saving checks that its settings have not changed since you opened it. If someone else saved first, your save is refused and your unsaved edits stay in the dialog. Copy the changes you want to keep before closing it, then reopen the agent to load the latest settings and merge your changes before saving again.

Use the agent’s row actions to edit or delete it. The standard agent has only **Delete agent**. Changes apply to later runs; an active run keeps its starting configuration. Deleting the agent clears task assignment references while preserving task history. It also deletes the agent's [sandbox workspaces](/platform/admin/sandboxes#explain-why-a-workspace-disappeared) and their files, including each Member's. Review current work and preserve outputs you still need before removing the worker it belongs to.

If creation fails, use the displayed reason to distinguish a duplicate name, missing project access, an unavailable provider/model or a skill visibility issue. A run that fails for good says at the top of its task what went wrong and who can fix it; [When the agent can't finish](/platform/projects/task-automation#when-the-agent-cant-finish) lists the cases. Changing instructions does not fix those dependencies.
2 changes: 2 additions & 0 deletions docs/fr/platform/projects/project-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ Pour donner au projet un agent propre, choisis **Nouvel agent**. Dès lors, le p

## Modifier ou retirer un agent

Quand tu modifies un agent existant, Tale vérifie à l’enregistrement que ses paramètres n’ont pas changé depuis son ouverture. Si quelqu’un a enregistré avant toi, ton enregistrement est refusé et tes modifications non enregistrées restent dans le dialogue. Copie celles que tu veux garder avant de le fermer, puis rouvre l’agent pour charger les paramètres actuels et y intégrer tes modifications avant d’enregistrer à nouveau.

Utilise le menu de sa ligne pour le modifier ou le supprimer. L’agent standard n’a que **Supprimer l'agent**. Les changements concernent les prochaines exécutions ; une exécution active conserve sa configuration initiale. La suppression retire les affectations à l’agent mais conserve l’historique des tâches. Elle efface aussi les [espaces de travail de sandbox](/fr/platform/admin/sandboxes#explain-why-a-workspace-disappeared) de l’agent avec leurs fichiers, y compris ceux des Membres. Examine le travail en cours et conserve les résultats nécessaires avant de retirer l’agent concerné.

Si la création échoue, lis la cause affichée : un nom déjà utilisé, un accès au projet manquant, un modèle indisponible et un skill invisible sont des problèmes distincts. Une exécution qui échoue définitivement indique en haut de sa tâche ce qui s’est passé et qui peut y remédier ; [Quand l’agent ne peut pas terminer](/fr/platform/projects/task-automation#quand-lagent-ne-peut-pas-terminer) détaille les cas. Modifier les instructions ne résout pas ces prérequis.
30 changes: 30 additions & 0 deletions packages/shared/src/schemas/projects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,38 @@ import {
updateProjectIdentitySchema,
updateProjectInstructionsSchema,
updateProjectSharingSchema,
updateProjectAgentInputSchema,
} from './projects';

describe('updateProjectAgentInputSchema', () => {
const config = {
name: 'Reviewer',
harness: 'claude-code',
model: 'test-model',
skills: [],
connectors: [],
};

it('preserves a read stamp and supports legacy unconditioned clients', () => {
expect(
updateProjectAgentInputSchema.parse({ ...config, expectedUpdatedAt: 20 }),
).toEqual({ ...config, expectedUpdatedAt: 20 });
expect(updateProjectAgentInputSchema.parse(config)).toEqual(config);
});

it.each([-1, 1.5, '20', null, Infinity, NaN, 8_640_000_000_000_001])(
'refuses an invalid epoch stamp: %j',
(expectedUpdatedAt) => {
expect(
updateProjectAgentInputSchema.safeParse({
...config,
expectedUpdatedAt,
}).success,
).toBe(false);
},
);
});

describe('projectColorSchema', () => {
it('accepts a valid token', () => {
expect(projectColorSchema.parse('emerald')).toBe('emerald');
Expand Down
6 changes: 6 additions & 0 deletions packages/shared/src/schemas/projects.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { z } from 'zod/v4';

import { epochMsSchema } from './epoch-ms';

/**
* Allowlist for project icons (lucide-react icon names).
*
Expand Down Expand Up @@ -120,6 +122,10 @@ export const projectAgentInputSchema = z.object({
instructions: z.string().max(PROJECT_AGENT_INSTRUCTIONS_MAX).optional(),
});

export const updateProjectAgentInputSchema = projectAgentInputSchema.extend({
expectedUpdatedAt: epochMsSchema.optional(),
});

export const createProjectInputSchema = z.object({
organizationId: z.string().min(1),
name: projectNameSchema,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const MODELS = [
// A row saved before picks carried providers: model only, no modelProvider.
const LEGACY_AGENT = {
_id: 'agent-1',
updatedAt: 20,
name: 'PR reviewer',
harness: 'claude-code',
model: 'claude-fable-5',
Expand All @@ -89,6 +90,7 @@ function renderDialog(agent: ProjectAgentRow, models = MODELS) {
beforeEach(() => {
createAgent.mockClear();
updateAgent.mockClear();
vi.mocked(toast).mockClear();
previewState.data = undefined;
});

Expand Down Expand Up @@ -132,6 +134,81 @@ describe('ProjectAgentDialog create', () => {
});

describe('ProjectAgentDialog model pin', () => {
it('saves the opening stamp and retains a refused draft across row refreshes', async () => {
updateAgent.mockRejectedValueOnce(
new AppError({ code: 'PROJECT_AGENT_STALE' }),
);
updateAgent.mockRejectedValueOnce(
new AppError({ code: 'PROJECT_AGENT_STALE' }),
);
const onOpenChange = vi.fn();
const dialog = (agent: ProjectAgentRow, open = true) => (
<ProjectAgentDialog
open={open}
onOpenChange={onOpenChange}
projectId="p1"
organizationId="org-1"
harnesses={[{ harness: 'claude-code', label: 'Claude Code' }]}
models={MODELS}
skills={[]}
connectors={[]}
agent={agent}
/>
);
const { user, rerender } = render(dialog(LEGACY_AGENT));
await user.clear(screen.getByRole('textbox', { name: /Name/ }));
await user.type(screen.getByRole('textbox', { name: /Name/ }), 'My draft');
await user.type(
screen.getByRole('textbox', { name: 'Instructions' }),
'Draft instructions',
);
await user.click(screen.getByRole('button', { name: 'Save changes' }));
expect(updateAgent).toHaveBeenCalledWith(
expect.objectContaining({
name: 'My draft',
instructions: 'Draft instructions',
expectedUpdatedAt: 20,
}),
);
expect(onOpenChange).not.toHaveBeenCalled();
expect(toast).toHaveBeenCalledTimes(1);
expect(toast).toHaveBeenCalledWith({
title: expect.stringContaining('changed'),
variant: 'destructive',
});
const refreshed = {
...LEGACY_AGENT,
name: 'Concurrent edit',
updatedAt: 30,
};
rerender(dialog(refreshed));
expect(screen.getByRole('textbox', { name: /Name/ })).toHaveValue(
'My draft',
);
expect(screen.getByRole('textbox', { name: 'Instructions' })).toHaveValue(
'Draft instructions',
);
await user.click(screen.getByRole('button', { name: 'Save changes' }));
expect(updateAgent).toHaveBeenLastCalledWith(
expect.objectContaining({ name: 'My draft', expectedUpdatedAt: 20 }),
);
rerender(dialog(refreshed, false));
rerender(dialog(refreshed));
expect(screen.getByRole('textbox', { name: /Name/ })).toHaveValue(
'Concurrent edit',
);
expect(screen.getByRole('textbox', { name: 'Instructions' })).toHaveValue(
'',
);
await user.click(screen.getByRole('button', { name: 'Save changes' }));
expect(updateAgent).toHaveBeenLastCalledWith(
expect.objectContaining({
name: 'Concurrent edit',
expectedUpdatedAt: 30,
}),
);
});

it('finds a friendly-named model by its API id and saves its provider', async () => {
const { user } = renderDialog(LEGACY_AGENT, [
{ ...MODELS[0], label: 'Claude Fable 5' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,18 @@ export function ProjectAgentDialog({
// Whether this opening of a create dialog already ticked the document
// skills — once, so unticking one sticks while the catalog refetches.
const documentSkillsSeeded = useRef(false);
const snapshot = useRef<{ agentId?: string; updatedAt?: number } | null>(
null,
);

// Re-seed from the row each time the dialog opens; create mode seeds blank.
useEffect(() => {
if (!open) return;
if (!open) {
snapshot.current = null;
return;
}
if (snapshot.current && snapshot.current.agentId === agent?._id) return;
snapshot.current = { agentId: agent?._id, updatedAt: agent?.updatedAt };
setName(agent?.name ?? '');
setHarness(agent?.harness ?? '');
setModel(agent?.model ?? '');
Expand Down Expand Up @@ -256,7 +264,11 @@ export function ProjectAgentDialog({
: {}),
};
if (agent) {
await updateAgent({ agentId: agent._id, ...payload });
await updateAgent({
agentId: agent._id,
expectedUpdatedAt: snapshot.current?.updatedAt,
...payload,
});
} else {
const agentId = await createAgent({ projectId, ...payload });
onCreated?.(agentId);
Expand All @@ -275,6 +287,7 @@ export function ProjectAgentDialog({
setNameError(t(`errors.${code}`));
} else if (
code === 'PROJECT_AGENT_HARNESS_INVALID' ||
code === 'PROJECT_AGENT_STALE' ||
code === 'PROJECT_AGENT_MODEL_INVALID' ||
code === 'PROJECT_AGENT_INSTRUCTIONS_TOO_LONG' ||
code === 'PROJECT_AGENT_LIMIT' ||
Expand Down
1 change: 1 addition & 0 deletions services/platform/app/lib/backend/contract/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export interface ProjectsContract {
'projects/mutations:updateProjectAgent': {
kind: 'mutation';
args: {
expectedUpdatedAt?: number;
secrets?: string[];
modelProvider?: string;
tools?: string[];
Expand Down
27 changes: 27 additions & 0 deletions services/platform/app/lib/backend/projects.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { AppError } from '@/lib/shared/errors/app-error';

import { activeOrganizationId } from './adapters';
import {
projectActionQueryAdapters,
Expand Down Expand Up @@ -305,6 +307,31 @@ describe('project read adapters', () => {
});

describe('project write adapters', () => {
it('sends the agent read stamp and refreshes only for a stale refusal', async () => {
const fetchSpy = vi
.spyOn(window, 'fetch')
.mockResolvedValue(jsonResponse(200, { ok: true }));
const adapter =
projectWriteAdapters['projects/mutations:updateProjectAgent'];
await adapter?.run(
{ agentId: 'a1', name: 'Draft', expectedUpdatedAt: 20 },
{ organizationId: 'org-1' },
);
const [url, init] = fetchSpy.mock.calls[0] ?? [];
expect(url).toBe('/api/app/projects/agents/a1?orgId=org-1');
expect(jsonBody(init)).toEqual({ name: 'Draft', expectedUpdatedAt: 20 });
expect(
adapter?.refusalInvalidates?.(
new AppError({ code: 'PROJECT_AGENT_STALE' }),
),
).toBe(true);
expect(
adapter?.refusalInvalidates?.(new AppError({ code: 'RBAC_FORBIDDEN' })),
).toBe(false);
expect(
adapter?.refusalInvalidates?.(new TypeError('Network failure')),
).toBe(false);
});
it('creates a project and answers the new id like the 0.4 mutation', async () => {
const fetchSpy = vi
.spyOn(window, 'fetch')
Expand Down
3 changes: 3 additions & 0 deletions services/platform/app/lib/backend/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { setProjectTaskReviewerInputSchema } from '@tale/shared/schemas/task-rev
import type { QueryClient } from '@tanstack/react-query';

import type { ItemOf, ReturnsOf } from '@/app/lib/backend/contract';
import { backendErrorCode } from '@/lib/utils/backend-error';

import type {
AdaptedReadOptions,
Expand Down Expand Up @@ -707,6 +708,8 @@ export const projectWriteAdapters: Record<string, WriteAdapter> = {
return null;
},
invalidate: projectWriteInvalidate,
refusalInvalidates: (error) =>
backendErrorCode(error) === 'PROJECT_AGENT_STALE',
},
'projects/mutations:deleteProjectAgent': {
run: async (args, ctx) => {
Expand Down
41 changes: 41 additions & 0 deletions services/platform/backend/domains/projects/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,47 @@ describe('project agent session routes share REST configuration limits', () => {
},
);

it('preserves the read stamp on an app replacement', async () => {
expect(
(await send('POST', '/agents/a1', { ...agent, expectedUpdatedAt: 20 }))
.status,
).toBe(200);
expect(service.updateProjectAgent).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
{ ...agent, agentId: 'a1', expectedUpdatedAt: 20 },
);
});

it('returns the stale service refusal as 409 with the current stamp', async () => {
const { ProjectError } = await import('./service.ts');
service.updateProjectAgent.mockRejectedValueOnce(
new ProjectError('PROJECT_AGENT_STALE', 'Reload and merge', 409, {
updatedAt: 30,
}),
);
const response = await send('POST', '/agents/a1', {
...agent,
expectedUpdatedAt: 20,
});
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({
error: 'PROJECT_AGENT_STALE',
data: { updatedAt: 30 },
});
});

it.each([-1, 1.5, '20', null, 8_640_000_000_000_001])(
'rejects an invalid read stamp without writing: %j',
async (expectedUpdatedAt) => {
expect(
(await send('POST', '/agents/a1', { ...agent, expectedUpdatedAt }))
.status,
).toBe(400);
expect(service.updateProjectAgent).not.toHaveBeenCalled();
},
);

it('forwards valid configuration with its project path', async () => {
expect((await send('POST', '/p1/agents', agent)).status).toBe(200);
expect(service.createProjectAgent).toHaveBeenCalledWith(
Expand Down
3 changes: 2 additions & 1 deletion services/platform/backend/domains/projects/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
createProjectInputSchema,
deleteProjectInputSchema,
projectAgentInputSchema,
updateProjectAgentInputSchema,
updateProjectIdentitySchema,
updateProjectInstructionsSchema,
updateProjectSharingSchema,
Expand Down Expand Up @@ -417,7 +418,7 @@ export function createProjectRoutes(deps: {
});

app.post('/agents/:agentId', async (c) => {
const body = projectAgentInputSchema.safeParse(await c.req.json());
const body = updateProjectAgentInputSchema.safeParse(await c.req.json());
if (!body.success) {
return invalidBodyResponse(c, body.error);
}
Expand Down
1 change: 1 addition & 0 deletions services/platform/messages/de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8664,6 +8664,7 @@ projects:
PROJECT_INSTRUCTIONS_TOO_LONG: Anweisungen überschreiten das Limit von {cap}
Zeichen. Kürze sie vor dem Speichern.
PROJECT_AGENT_NAME_INVALID: Der Agentenname muss 1–120 Zeichen lang sein.
PROJECT_AGENT_STALE: Dieser Agent wurde seit dem Öffnen geändert. Deine Änderungen sind noch hier. Kopiere sie vor dem Schließen, öffne den Agenten erneut und füge sie in die aktuellen Einstellungen ein.
PROJECT_AGENT_NAME_TAKEN: Ein anderer Agent in diesem Projekt trägt diesen Namen bereits.
PROJECT_AGENT_HARNESS_INVALID: Dieses Harness lässt sich nicht für Projekt-Agenten verwenden.
PROJECT_AGENT_MODEL_INVALID: Wähle ein Modell für diesen Agenten.
Expand Down
1 change: 1 addition & 0 deletions services/platform/messages/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5665,6 +5665,7 @@ projects:
PROJECT_INSTRUCTIONS_TOO_LONG: Instructions exceed the {cap}-character limit. Trim before saving.
PROJECT_AGENT_NAME_INVALID: Agent name must be 1–120 characters.
PROJECT_AGENT_NAME_TAKEN: Another agent in this project already has that name.
PROJECT_AGENT_STALE: This agent changed since you opened it. Your edits are still here. Copy them before closing, then reopen the agent and merge them with the latest settings.
PROJECT_AGENT_HARNESS_INVALID: That harness can't be used for project agents.
PROJECT_AGENT_MODEL_INVALID: Pick a model for this agent.
PROJECT_AGENT_INSTRUCTIONS_TOO_LONG: Instructions exceed the 20,000-character limit. Trim before saving.
Expand Down
1 change: 1 addition & 0 deletions services/platform/messages/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8758,6 +8758,7 @@ projects:
PROJECT_INSTRUCTIONS_TOO_LONG: Les instructions dépassent la limite de {cap}
caractères. Raccourcis-les avant d'enregistrer.
PROJECT_AGENT_NAME_INVALID: Le nom de l'agent doit faire entre 1 et 120 caractères.
PROJECT_AGENT_STALE: Cet agent a changé depuis que tu l'as ouvert. Tes modifications sont toujours là. Copie-les avant de fermer, puis rouvre l'agent et intègre-les aux paramètres actuels.
PROJECT_AGENT_NAME_TAKEN: Un autre agent de ce projet porte déjà ce nom.
PROJECT_AGENT_HARNESS_INVALID: Ce harness ne peut pas être utilisé pour les agents de projet.
PROJECT_AGENT_MODEL_INVALID: Choisis un modèle pour cet agent.
Expand Down
Loading