mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 12:37:55 +01:00
fix(ui): refine agent profiles, identity editing, and list actions (#19535)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent pages expose identity files, reporting relationships, and
runtime settings.
> - Several controls had inconsistent spacing, weak navigation, or
misleading save feedback.
> - Empty task-row detail slots also reduced the title width before
truncation.
> - This pull request fixes those behaviors and aligns the reviewed UI
details.
> - The result is clearer agent editing and more readable task and agent
lists.
## Linked Issues or Issue Description
**What happened?**
Agent headers and file controls had inconsistent layout. The Identity
footer appeared without edits and did not provide clear save
confirmation. File names could wrap or omit the Markdown suffix. Task
titles truncated while empty detail slots occupied the row.
**Expected behavior**
Keep headers and actions aligned. Reveal the Identity footer only for
changes or save feedback. Use valid Markdown file names and actual file
dates. Let titles use available space.
**Steps to reproduce**
1. Open an agent overview, then its Identity tab.
2. Edit, undo, save, copy, and add an instruction file.
3. Resize the file panel and inspect file names and date labels.
4. Hover an agent row and inspect the Chat action and tooltip.
5. Open a task list with no recovery or external details and inspect
title width.
Related: #18716 is the prior UI bundle. #16934 and #14483 concern role
editing; this change does not add a role picker.
## What Changed
- Refine the character header, inline title and name editing, crown
position, runtime shortcut, and Chat/New task actions.
- Align profile metadata and manager selection; hide empty direct
reports.
- Refine Identity panels, Markdown filename validation, file-row hover,
truncation, Paper Mono typography, and copy feedback.
- Add a viewport-bound save footer with dirty, saving, and saved states.
Keep undo/discard separate from successful saves.
- Return recorded creation or modification dates for instruction files.
Reuse the active file transaction for metadata reads to avoid exhausting
the small connection pool.
- Reveal the agent-row Chat icon and label on hover, with a standard
delayed tooltip.
- Collapse empty task-row details so titles can use the available width.
## Verification
- Browser checks covered the local overview and Identity flows, narrow
file panels, successful file creation/update, undo/discard, header
navigation, row hover, tooltip delayed-open state, and full task titles.
- Focused instruction, save-footer, date, font-asset, and task-row tests
passed during development. After review, 55 file/instruction tests
passed, including cold restoration with recorded and unknown dates;
server typecheck and 18 immediate-save response tests also passed.
- Full `pnpm -r typecheck` and `pnpm build` passed after rebase onto
current master. The complete `pnpm test:run` attempt hit a 15-second
timeout in the existing chat Retry HTTP integration test; that case
passed in isolation (1 test passed). A second full attempt hit timeouts
in two other chat integration cases (GitHub webhook draining and
delivery retry budget); both passed in isolation without increasing
timeouts. All 55 remote checks passed on f31405a730, including the full
test matrix, build, typecheck, and final verification gate.
- `pnpm check:token-gates`, `node scripts/check-maps.mjs`, and `git diff
--check` passed on the submitted revision.
## Risks
- File dates are optional. Managed files require recorded dates because
restored projections have synthetic filesystem timestamps. External
files can use modification time; unknown dates are omitted.
- Save-footer timing depends on animation completion; reduced-motion and
failed-save paths have tests.
- Global Paper Mono typography can change text widths. Browser checks
covered the edited surfaces.
- No schema migration or new execution permissions are introduced.
## Model Used
OpenAI Codex, GPT-6, with repository tools, code execution, and browser
verification. The exact serving model ID and context-window size are not
exposed in this session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes:` / `Closes:`
/ `Refs:` OR (b) described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub references)
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run the relevant tests locally and they pass; full-run
timeout limitations and successful isolated reruns are documented above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
705c3e955d
commit
c650f36007
31 files changed
+671
-156
No files matched your search
@@ -111,6 +111,31 @@ describe("durable agent file authority", () => {
|
||||
} })).toEqual({ entryFile: "missing.md", contentHash: null });
|
||||
});
|
||||
|
||||
it("keeps recorded file dates through restore without treating projection times as edits", async () => {
|
||||
await materializeInstructionBytes(root, "AGENTS.md", Buffer.from("Historical instructions"));
|
||||
await db.update(agents).set({ adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root,
|
||||
instructionsEntryFile: "AGENTS.md" } }).where(eq(agents.id, agentId));
|
||||
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
|
||||
await store().read(companyId, agentId, "AGENTS.md", actor());
|
||||
await store().write({ companyId, agentId, path: "NOTES.md", bytes: Buffer.from("Recorded creation"), baseHash: null }, actor());
|
||||
const instructions = agentInstructionsService(db);
|
||||
const created = await instructions.readFile(agent, "NOTES.md");
|
||||
expect(Number.isFinite(Date.parse(created.createdAt!))).toBe(true);
|
||||
await replaceFilesystem();
|
||||
vi.stubEnv("PAPERCLIP_DURABLE_AGENT_FILES", "false");
|
||||
const restored = await instructions.readFile(agent, "AGENTS.md");
|
||||
expect(restored.content).toBe("Historical instructions");
|
||||
expect(restored.createdAt).toBeUndefined();
|
||||
expect(restored.updatedAt).toBeUndefined();
|
||||
const summary = (await instructions.getBundle(agent)).files.find(file => file.path === "AGENTS.md");
|
||||
expect(summary).toBeDefined();
|
||||
expect(summary?.createdAt).toBeUndefined();
|
||||
expect(summary?.updatedAt).toBeUndefined();
|
||||
const recorded = await instructions.readFile(agent, "NOTES.md");
|
||||
expect(recorded.createdAt).toBe(created.createdAt);
|
||||
expect(recorded.updatedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("imports legacy bytes, modes and empty entries, then restores without any old filesystem", async () => {
|
||||
const binary = Buffer.alloc(2 * 1024 * 1024, 0x81);
|
||||
await materializeInstructionBytes(root, "AGENTS.md", Buffer.from("Original"));
|
||||
|
||||
@@ -7,6 +7,7 @@ import { and, eq, sql } from "drizzle-orm";
|
||||
import { agents, agentApiKeys, companies, authUsers, companyMemberships, principalPermissionGrants, heartbeatRuns,
|
||||
agentInstructionRevisions, agentInstructionHeads, issueThreadInteractions, issues, createDb } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { agentFileStore } from "../services/agent-file-store.js";
|
||||
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
||||
import { agentInstructionWorkingCopyService } from "../services/agent-instruction-working-copies.js";
|
||||
import { instructionBytes, instructionPath, materializeInstructionBytes, readInstructionBytes } from "../services/agent-instruction-files.js";
|
||||
@@ -64,6 +65,31 @@ describe("canonical instruction revisions", () => {
|
||||
async function save(content: string, baseRevisionId: string | null) {
|
||||
return service.commit({ ...target(), entryFile, content, baseRevisionId, source: "cleanup" }, actor);
|
||||
}
|
||||
it("exposes recorded creation dates and update dates for root and supporting files", async () => {
|
||||
const files = agentFileStore(db);
|
||||
const instructions = agentInstructionsService(db);
|
||||
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
|
||||
const supporting = "NOTES.md";
|
||||
const created = await files.write({ ...target(), path: supporting, bytes: Buffer.from("first"), baseHash: null }, actor);
|
||||
const first = await instructions.readFile(agent!, supporting);
|
||||
expect(Number.isFinite(Date.parse(first.createdAt!))).toBe(true);
|
||||
expect(first.updatedAt).toBeUndefined();
|
||||
await files.write({ ...target(), path: supporting, bytes: Buffer.from("second"), baseHash: created.contentHash }, actor);
|
||||
// The file-storage pool has two connections. Concurrent locked reads must
|
||||
// reuse their transactions for metadata rather than wait on a third lease.
|
||||
const [updated] = await Promise.all([
|
||||
instructions.readFile(agent!, supporting), instructions.getBundle(agent!),
|
||||
instructions.readFile(agent!, supporting), instructions.getBundle(agent!),
|
||||
]);
|
||||
expect(updated.createdAt).toBeUndefined();
|
||||
expect(Date.parse(updated.updatedAt!)).toBeGreaterThanOrEqual(Date.parse(first.createdAt!));
|
||||
// The root file uses the revision-compatible API, with the same recorded dates.
|
||||
await fs.unlink(path.join(root, entryFile));
|
||||
const rootCreated = await save("new root", null);
|
||||
expect(await instructions.getFileDates(agent!, entryFile, rootCreated.revision.contentHash)).toHaveProperty("createdAt");
|
||||
const rootUpdated = await save("updated root", rootCreated.revision.id);
|
||||
expect(await instructions.getFileDates(agent!, entryFile, rootUpdated.revision.contentHash)).toHaveProperty("updatedAt");
|
||||
});
|
||||
it("reads peer instructions with read-only agent and responsible-user grants but denies saves", async () => {
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));
|
||||
await db.insert(principalPermissionGrants).values([
|
||||
|
||||
@@ -17,6 +17,7 @@ const mockBuiltInAgentService = vi.hoisted(() => ({
|
||||
|
||||
const mockAgentInstructionsService = vi.hoisted(() => ({
|
||||
getBundle: vi.fn(),
|
||||
getFileDates: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
updateBundle: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
@@ -206,6 +207,7 @@ describe("agent instructions bundle routes", () => {
|
||||
...makeAgent(),
|
||||
adapterConfig: patch.adapterConfig ?? {},
|
||||
}));
|
||||
mockAgentInstructionsService.getFileDates.mockResolvedValue({ updatedAt: "2026-11-05T12:00:00.000Z" });
|
||||
mockAgentInstructionsService.getBundle.mockResolvedValue({
|
||||
agentId: "11111111-1111-4111-8111-111111111111",
|
||||
companyId: "company-1",
|
||||
@@ -597,6 +599,7 @@ describe("agent instructions bundle routes", () => {
|
||||
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file?path=AGENTS.md"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.content).toBe("committed");
|
||||
expect(res.body.updatedAt).toBe("2026-11-05T12:00:00.000Z");
|
||||
expect(res.body.revision.id).toBe("33333333-3333-4333-8333-333333333333");
|
||||
expect(mockAgentInstructionsService.readFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -59,6 +59,33 @@ describe("agent instructions service", () => {
|
||||
if (entry === "../invalid") expect(bundle.warnings.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("records creation on new unversioned supporting files, then modification on updates", async () => {
|
||||
const root = await makeTempDir("external-new-file-"); cleanupDirs.add(root);
|
||||
await fs.writeFile(path.join(root, "AGENTS.md"), "instructions");
|
||||
const agent = makeAgent({ instructionsBundleMode: "external", instructionsRootPath: root });
|
||||
const svc = agentInstructionsService();
|
||||
const first = await svc.writeFile(agent, "NOTES.md", "first");
|
||||
expect(Number.isFinite(Date.parse(first.file.createdAt!))).toBe(true);
|
||||
expect(first.file.updatedAt).toBeUndefined();
|
||||
const second = await svc.writeFile(agent, "NOTES.md", "second");
|
||||
expect(second.file.createdAt).toBeUndefined();
|
||||
expect(Number.isFinite(Date.parse(second.file.updatedAt!))).toBe(true);
|
||||
});
|
||||
|
||||
it("returns actual modification dates without inventing creation dates", async () => {
|
||||
const root = await makeTempDir("external-file-dates-"); cleanupDirs.add(root);
|
||||
const filename = path.join(root, "AGENTS.md");
|
||||
await fs.writeFile(filename, "instructions");
|
||||
const updated = new Date("2026-10-01T12:00:00.000Z");
|
||||
await fs.utimes(filename, updated, updated);
|
||||
const agent = makeAgent({ instructionsBundleMode: "external", instructionsRootPath: root });
|
||||
const svc = agentInstructionsService();
|
||||
const file = await svc.readFile(agent, "AGENTS.md");
|
||||
expect(file.updatedAt).toBe(updated.toISOString());
|
||||
expect(file.createdAt).toBeUndefined();
|
||||
expect((await svc.getBundle(agent)).files[0]?.updatedAt).toBe(updated.toISOString());
|
||||
});
|
||||
|
||||
it("lists external bundles containing large binary assets", async () => {
|
||||
const root = await makeTempDir("external-large-assets-"); cleanupDirs.add(root);
|
||||
await fs.writeFile(path.join(root, "AGENTS.md"), "external instructions");
|
||||
|
||||
@@ -801,10 +801,10 @@ export function agentRoutes(
|
||||
const agentFiles = agentFileStore(db);
|
||||
const instructionRevisions = agentInstructionRevisionService(db);
|
||||
const instructionWorkingCopies = agentInstructionWorkingCopyService(db);
|
||||
function instructionFileDetail(snapshot: import("@paperclipai/shared").AgentInstructionSnapshot,
|
||||
async function instructionFileDetail(agent: NonNullable<Awaited<ReturnType<typeof svc.getById>>>, snapshot: import("@paperclipai/shared").AgentInstructionSnapshot,
|
||||
receipt?: import("@paperclipai/shared").AgentInstructionCommitReceipt) {
|
||||
const path = snapshot.revision.entryFile;
|
||||
return { path, content: snapshot.content, contentHash: snapshot.revision.contentHash, size: snapshot.revision.byteLength, revision: snapshot.revision, receipt,
|
||||
return { path, ...await instructions.getFileDates(agent, path, snapshot.revision.contentHash), content: snapshot.content, contentHash: snapshot.revision.contentHash, size: snapshot.revision.byteLength, revision: snapshot.revision, receipt,
|
||||
language: path.toLowerCase().endsWith(".md") ? "markdown" : "text", markdown: path.toLowerCase().endsWith(".md"),
|
||||
isEntryFile: true, editable: true, deprecated: false, virtual: false };
|
||||
}
|
||||
@@ -5250,7 +5250,7 @@ export function agentRoutes(
|
||||
}
|
||||
if (agentInstructionsBundleMode(existing) !== "external" && instructionPath(relativePath) === deriveBundleState(existing).entryFile) {
|
||||
const snapshot = await instructionRevisions.readCurrent({ companyId: existing.companyId, agentId: existing.id }, req.actor);
|
||||
if (snapshot) { res.json(instructionFileDetail(snapshot)); return; }
|
||||
if (snapshot) { res.json(await instructionFileDetail(existing, snapshot)); return; }
|
||||
}
|
||||
res.json(await instructions.readFile(existing, relativePath));
|
||||
});
|
||||
@@ -5286,7 +5286,7 @@ export function agentRoutes(
|
||||
await svc.update(existing.id, { adapterConfig });
|
||||
}
|
||||
}
|
||||
res.json(instructionFileDetail(receipt, receipt));
|
||||
res.json(await instructionFileDetail(existing, receipt, receipt));
|
||||
return;
|
||||
}
|
||||
await assertCanManageInstructionsPath(req, existing);
|
||||
@@ -5331,6 +5331,8 @@ export function agentRoutes(
|
||||
entityId: existing.id,
|
||||
details: {
|
||||
path: result.file.path,
|
||||
contentHash: result.file.contentHash,
|
||||
created: Boolean(result.file.createdAt),
|
||||
size: result.file.size,
|
||||
clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate === true,
|
||||
},
|
||||
@@ -5354,7 +5356,7 @@ export function agentRoutes(
|
||||
if (!isUuidLike(runId)) throw unprocessable("Invalid instruction candidate run id");
|
||||
const receipt = await instructionWorkingCopies.resolve({ companyId: existing.companyId, agentId: existing.id,
|
||||
runId, baseRevisionId: req.body.baseRevisionId, content: req.body.content }, req.actor);
|
||||
res.json(instructionFileDetail(receipt, receipt));
|
||||
res.json(await instructionFileDetail(existing, receipt, receipt));
|
||||
});
|
||||
|
||||
router.get("/agents/:id/instructions-bundle/history", async (req, res) => {
|
||||
@@ -5396,7 +5398,7 @@ export function agentRoutes(
|
||||
runId: req.actor.runId, entryFile: receipt.revision.entryFile, revisionId: receipt.revision.id,
|
||||
contentHash: receipt.revision.contentHash }).catch(() => undefined);
|
||||
}
|
||||
res.json(instructionFileDetail(receipt, receipt));
|
||||
res.json(await instructionFileDetail(existing, receipt, receipt));
|
||||
});
|
||||
|
||||
router.delete("/agents/:id/instructions-bundle/file", async (req, res) => {
|
||||
|
||||
@@ -249,7 +249,7 @@ export function agentFileStore(db: Db) {
|
||||
}
|
||||
if (input.bytes === null) await fs.unlink(await assertInstructionPathSafe(root, relative));
|
||||
else await materializeInstructionBytes(root, relative, input.bytes);
|
||||
await audit(tx, agent, bound, { path: relative, contentHash: incomingHash });
|
||||
await audit(tx, agent, bound, { path: relative, contentHash: incomingHash, created: previous === null && input.bytes !== null });
|
||||
return { contentHash: incomingHash, changed: true };
|
||||
}),
|
||||
apply: (input: { companyId: string; agentId: string; sourceDir: string; baseline: DirectorySnapshot; checkpoint?: AgentFileManifest }, actor: AuthorizationActor) =>
|
||||
|
||||
@@ -255,7 +255,7 @@ export function agentInstructionRevisionService(db: Db) {
|
||||
actorId: (bound.type === "plugin" ? bound.pluginId : bound.type === "board" ? bound.userId : bound.agentId)!,
|
||||
agentId: bound.type === "agent" ? bound.agentId : null, runId: row.sourceRunId,
|
||||
responsibleUserId: row.responsibleUserId, action: "agent.files_updated", entityType: "agent", entityId: input.agentId,
|
||||
details: { path: input.entryFile, contentHash: row.contentHash, source: restored ? "legacy_restore" : (input as InstructionCommitInput).source } });
|
||||
details: { path: input.entryFile, contentHash: row.contentHash, created: current === null, source: restored ? "legacy_restore" : (input as InstructionCommitInput).source } });
|
||||
const bindEntry = async () => {
|
||||
if (
|
||||
!state.agent.adapterConfig.instructionsRootPath ||
|
||||
|
||||
@@ -2,8 +2,8 @@ import { adoptAgentFiles, inspectAgentFile, fileHash, agentFilePath, MAX_AGENT_F
|
||||
import { invalidateAgentFileProjection, persistDurableAgentFiles, restoreDurableAgentFiles } from "./agent-file-durability.js";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { agentFileRoots, agentInstructionHeads, agents, fileStorageDb, type Db } from "@paperclipai/db";
|
||||
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { activityLog, agentFileRoots, agentInstructionHeads, agents, fileStorageDb, type Db } from "@paperclipai/db";
|
||||
import { instructionPath, assertInstructionPathSafe, instructionBytes, readInstructionBytes } from "./agent-instruction-files.js";
|
||||
import { notFound, unprocessable } from "../errors.js";
|
||||
import { resolveHomeAwarePath, resolvePaperclipInstanceRoot } from "../home-paths.js";
|
||||
@@ -41,6 +41,9 @@ type AgentLike = {
|
||||
|
||||
type AgentInstructionsFileSummary = {
|
||||
path: string;
|
||||
/** Creation is exposed only when recorded; historical files may only have a modification date. */
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
contentHash?: string;
|
||||
binary?: boolean;
|
||||
size: number;
|
||||
@@ -218,12 +221,12 @@ async function listFilesRecursive(
|
||||
return output.sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
|
||||
async function readFileSummary(rootPath: string, relativePath: string, entryFile: string): Promise<AgentInstructionsFileSummary> {
|
||||
async function readFileSummary(rootPath: string, relativePath: string, entryFile: string, includeFilesystemDate: boolean): Promise<AgentInstructionsFileSummary> {
|
||||
const absolutePath = resolvePathWithinRoot(rootPath, relativePath);
|
||||
const stat = await fs.stat(absolutePath);
|
||||
// External bundles may contain large assets; listing must not read them.
|
||||
const file = stat.size > MAX_AGENT_FILE_BYTES ? null : await inspectAgentFile(rootPath, relativePath);
|
||||
return summarizeFile(relativePath, entryFile, file?.size ?? stat.size, file?.bytes ?? null, file?.hash);
|
||||
return { ...summarizeFile(relativePath, entryFile, file?.size ?? stat.size, file?.bytes ?? null, file?.hash), ...(includeFilesystemDate ? { updatedAt: stat.mtime.toISOString() } : {}) };
|
||||
}
|
||||
|
||||
function summarizeFile(relativePath: string, entryFile: string, size: number, bytes: Buffer | null, hash?: string): AgentInstructionsFileSummary {
|
||||
@@ -517,6 +520,25 @@ export function syncInstructionsBundleConfigFromFilePath(
|
||||
|
||||
export function agentInstructionsService(db?: Db) {
|
||||
if (db) db = fileStorageDb(db);
|
||||
async function getFileDates(agent: AgentLike, relativePath: string, contentHash?: string, connection?: Pick<Db, "select">): Promise<{ createdAt?: string; updatedAt?: string }> {
|
||||
const state = await recoverManagedBundleState(agent, deriveBundleState(agent));
|
||||
if (!state.rootPath) return {};
|
||||
const filename = await assertInstructionPathSafe(state.rootPath, relativePath);
|
||||
if (connection && contentHash) {
|
||||
// One bounded lookup for the open file, never one query per tree row.
|
||||
// Match the content hash so an unrecorded external edit cannot inherit an old save date.
|
||||
const [saved] = await connection.select({ date: activityLog.createdAt, details: activityLog.details }).from(activityLog)
|
||||
.where(and(eq(activityLog.companyId, agent.companyId), eq(activityLog.entityType, "agent"),
|
||||
eq(activityLog.entityId, agent.id), inArray(activityLog.action, ["agent.files_updated", "agent.instructions_file_updated"]),
|
||||
eq(sql<string>`${activityLog.details}->>'path'`, relativePath),
|
||||
eq(sql<string>`${activityLog.details}->>'contentHash'`, contentHash)))
|
||||
.orderBy(desc(activityLog.createdAt)).limit(1);
|
||||
if (saved) return saved.details?.created === true ? { createdAt: saved.date.toISOString() } : { updatedAt: saved.date.toISOString() };
|
||||
}
|
||||
if (db && state.mode !== "external") return {};
|
||||
const stat = await statIfExists(filename);
|
||||
return stat?.isFile() ? { updatedAt: stat.mtime.toISOString() } : {};
|
||||
}
|
||||
async function getManagedEntryFingerprint(agent: AgentLike): Promise<{ entryFile: string; contentHash: string | null } | null> {
|
||||
if (!db || agentInstructionsBundleMode(agent) !== "managed") return null;
|
||||
const state = deriveBundleState(agent);
|
||||
@@ -555,12 +577,12 @@ export function agentInstructionsService(db?: Db) {
|
||||
const summaries: AgentInstructionsFileSummary[] = [];
|
||||
// Bound open descriptors and text buffers even for a large personal folder.
|
||||
for (let index = 0; index < files.length; index += 8) {
|
||||
summaries.push(...await Promise.all(files.slice(index, index + 8).map(relativePath => readFileSummary(state.rootPath!, relativePath, state.entryFile))));
|
||||
summaries.push(...await Promise.all(files.slice(index, index + 8).map(relativePath => readFileSummary(state.rootPath!, relativePath, state.entryFile, !db || state.mode === "external"))));
|
||||
}
|
||||
return toBundle(agent, state, summaries);
|
||||
}
|
||||
|
||||
async function readFile(agent: AgentLike, relativePath: string): Promise<AgentInstructionsFileDetail> {
|
||||
async function readFile(agent: AgentLike, relativePath: string, connection?: Pick<Db, "select">): Promise<AgentInstructionsFileDetail> {
|
||||
const state = await recoverManagedBundleState(agent, deriveBundleState(agent));
|
||||
if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) {
|
||||
const content = asString(state.config[PROMPT_KEY]);
|
||||
@@ -582,7 +604,7 @@ export function agentInstructionsService(db?: Db) {
|
||||
const file = await inspectAgentFile(state.rootPath, relativePath);
|
||||
if (file === null) throw notFound("Instructions file not found");
|
||||
const summary = summarizeFile(relativePath, state.entryFile, file.size, file.bytes, file.hash);
|
||||
return { ...summary, content: summary.binary ? "" : file.bytes!.toString("utf8") };
|
||||
return { ...summary, ...await getFileDates(agent, relativePath, file.hash, connection), content: summary.binary ? "" : file.bytes!.toString("utf8") };
|
||||
}
|
||||
|
||||
async function ensureWritableBundle(
|
||||
@@ -722,12 +744,16 @@ export function agentInstructionsService(db?: Db) {
|
||||
await assertInstructionPathSafe(prepared.state.rootPath!, relativePath);
|
||||
const absolutePath = resolvePathWithinRoot(prepared.state.rootPath!, relativePath);
|
||||
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
|
||||
const existed = Boolean(await statIfExists(absolutePath));
|
||||
await fs.writeFile(absolutePath, content, "utf8");
|
||||
const writtenAt = new Date().toISOString();
|
||||
const nextAgent = { ...agent, adapterConfig: prepared.adapterConfig };
|
||||
const [bundle, file] = await Promise.all([
|
||||
getBundle(nextAgent),
|
||||
readFile(nextAgent, relativePath),
|
||||
]);
|
||||
if (existed) file.updatedAt = writtenAt;
|
||||
else { file.createdAt = writtenAt; delete file.updatedAt; }
|
||||
return { bundle, file, adapterConfig: prepared.adapterConfig };
|
||||
}
|
||||
|
||||
@@ -882,7 +908,7 @@ export function agentInstructionsService(db?: Db) {
|
||||
|
||||
// Public managed reads and configuration changes share the same row lock as
|
||||
// editor/runtime writes. Internal helpers operate on the already-loaded tree.
|
||||
async function withProjection<T>(agent: AgentLike, write: boolean, operation: (current: AgentLike) => Promise<T>, managedDestination = false) {
|
||||
async function withProjection<T>(agent: AgentLike, write: boolean, operation: (current: AgentLike, connection?: Pick<Db, "select">) => Promise<T>, managedDestination = false) {
|
||||
if (!db) return operation(agent);
|
||||
return db.transaction(async tx => {
|
||||
const [current] = await tx.select().from(agents).where(and(eq(agents.id, agent.id), eq(agents.companyId, agent.companyId))).for("update");
|
||||
@@ -891,7 +917,7 @@ export function agentInstructionsService(db?: Db) {
|
||||
const root = managed ? await adoptAgentFiles(tx, current) : managedDestination ? resolveManagedInstructionsRoot(current) : null;
|
||||
if (!managed && root) await restoreDurableAgentFiles(tx, current, root);
|
||||
if (write && root) await invalidateAgentFileProjection(root);
|
||||
const result = await operation(current);
|
||||
const result = await operation(current, tx);
|
||||
if (write && root) await persistDurableAgentFiles(tx, current, root);
|
||||
return result;
|
||||
});
|
||||
@@ -899,9 +925,10 @@ export function agentInstructionsService(db?: Db) {
|
||||
|
||||
return {
|
||||
getManagedEntryFingerprint,
|
||||
getFileDates: (agent: AgentLike, relativePath: string, hash?: string) => getFileDates(agent, relativePath, hash, db),
|
||||
getBundleLocation: (agent: AgentLike) => withProjection(agent, false, getBundleLocation),
|
||||
getBundle: (agent: AgentLike) => withProjection(agent, false, getBundle),
|
||||
readFile: (agent: AgentLike, relativePath: string) => withProjection(agent, false, current => readFile(current, relativePath)),
|
||||
readFile: (agent: AgentLike, relativePath: string) => withProjection(agent, false, (current, connection) => readFile(current, relativePath, connection)),
|
||||
updateBundle: (agent: AgentLike, input: Parameters<typeof updateBundle>[1]) => withProjection(agent, true, current => updateBundle(current, input), input.mode === "managed"),
|
||||
writeFile,
|
||||
deleteFile,
|
||||
|
||||
Reference in new issue
Block a user