Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6511e4ec62 | |||
| 220309db12 | |||
| c3d88c0685 | |||
| e4ecd116a2 | |||
| 8d0477e0f7 | |||
| e7e9cb20d8 | |||
| ebfae9b891 | |||
| 3ab484ddc0 | |||
| 6bcef26446 | |||
| 240444eafd | |||
| d09c9d6633 | |||
| bc44cbc8b7 | |||
| e7060a5e42 | |||
| 4b8f59695b | |||
| da7b86d5c8 | |||
| efe21c79e9 | |||
| ee119fe437 | |||
| d97c403aab |
@@ -15,8 +15,10 @@ import { FileText, Loader2 } from "lucide-react";
|
||||
import { artifactDocument, frameSandbox } from "../lib/artifactView";
|
||||
import { blobText, inlineHtml, type FetchFile } from "../lib/htmlInline";
|
||||
|
||||
/** A page read by `fetchFile` is shown up to this size. */
|
||||
const HTML_MAX = 10 * 1024 * 1024;
|
||||
/** A page read by `fetchFile` is shown up to this size. A self-contained
|
||||
* page (a slide deck with its video and images inlined as base64) is easily
|
||||
* past 10 MB; the iframe renders far larger documents than this. */
|
||||
const HTML_MAX = 64 * 1024 * 1024;
|
||||
|
||||
export function HtmlFrame({
|
||||
path,
|
||||
|
||||
@@ -7,10 +7,11 @@
|
||||
* folder's account with that account's own SSH key / HTTPS login — and opens
|
||||
* a workspace on the new folder. A 409 `ECREDENTIALS` opens a login row (sent
|
||||
* once, optionally remembered), `ESSHAUTH` points to Settings → Git.
|
||||
* A running clone shows `CloneProgress` and never holds the page: closing the
|
||||
* dialog only hides it behind a small progress chip (click to reopen), the
|
||||
* A clone runs in the background from the moment it starts: the dialog steps
|
||||
* aside for a small progress chip (`CloneProgress`; click to reopen), the
|
||||
* request keeps going, and its outcome arrives as a toast — a failure is kept
|
||||
* for the next open so a login row is still there to fill in.
|
||||
* for the next open, and one asking for a login reopens the dialog with its
|
||||
* login row.
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
@@ -111,6 +112,9 @@ export function CloneHereDialog({
|
||||
setTarget(into);
|
||||
setError(null);
|
||||
setSshRefused(false);
|
||||
// Runs in the background by default: the dialog steps aside for the
|
||||
// progress chip, and comes back only if the clone needs a login.
|
||||
onClose();
|
||||
try {
|
||||
const result = await api.lanes.clone({
|
||||
url: u,
|
||||
@@ -156,6 +160,8 @@ export function CloneHereDialog({
|
||||
if (!openRef.current) {
|
||||
keepRef.current = true;
|
||||
toast.error(message);
|
||||
// A login to type: show the form again with its login row.
|
||||
if (e.code === "ECREDENTIALS") onReopen();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -229,6 +229,8 @@ async function walkEntry(
|
||||
out.push({ file, rel: `${prefix}${entry.name}` });
|
||||
return;
|
||||
}
|
||||
// The server takes nothing into .git: never read one off the disk at all.
|
||||
if (entry.name === ".git") return;
|
||||
const reader = (entry as FileSystemDirectoryEntry).createReader();
|
||||
// readEntries answers in pages until it answers [].
|
||||
for (;;) {
|
||||
@@ -367,16 +369,21 @@ export function FileBrowser({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [laneId, initialHome, session, source, initialPath]);
|
||||
|
||||
useEffect(() => {
|
||||
// Re-read after every change here too: deleting a workspace's folder takes
|
||||
// it out of the places (a workspace whose folder is gone has nothing to show).
|
||||
const loadLanes = useCallback(() => {
|
||||
api.lanes
|
||||
.list()
|
||||
.then((r) => setLanes(r.lanes))
|
||||
.catch(() => setLanes([]));
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
loadLanes();
|
||||
api.files
|
||||
.homes()
|
||||
.then((r) => setHomes(r.homes))
|
||||
.catch(() => setHomes([]));
|
||||
}, []);
|
||||
}, [loadLanes]);
|
||||
// Another user's home (an admin's view) is read-only.
|
||||
const ro = isHomePlace(target) && !!homes.find((h) => h.id === target.home)?.readOnly;
|
||||
// Clone into the open folder: the absolute path of a workspace's own folder
|
||||
@@ -437,6 +444,8 @@ export function FileBrowser({
|
||||
} else if (view === "trash") setTrash((await api.files.trash(target)).items);
|
||||
else setListing(await api.files.list(target, path));
|
||||
} catch (e) {
|
||||
// Never leave the last folder's entries under another folder's error.
|
||||
if (view === "files") setListing(null);
|
||||
// A dashboard that does not know /fs yet (not restarted) answers 404.
|
||||
setError(
|
||||
(e as { status?: number }).status === 404 && !errCode(e) ? t("fx.unavailable") : errText(e)
|
||||
@@ -453,6 +462,7 @@ export function FileBrowser({
|
||||
|
||||
const changed = () => {
|
||||
void load();
|
||||
loadLanes();
|
||||
onChanged?.();
|
||||
};
|
||||
|
||||
@@ -614,8 +624,14 @@ export function FileBrowser({
|
||||
};
|
||||
|
||||
/** Upload `files` (each with its path inside the pick/drop) under `dir`. */
|
||||
const uploadAll = async (files: { file: File; rel: string }[], dir = path) => {
|
||||
const uploadAll = async (picked: { file: File; rel: string }[], dir = path) => {
|
||||
setMenu(null);
|
||||
// A dropped/picked repo carries its .git, which the server refuses file by
|
||||
// file — skip it here with ONE notice instead of a toast per object.
|
||||
const files = picked.filter((f) => !f.rel.split("/").includes(".git"));
|
||||
if (files.length < picked.length) {
|
||||
toast.info(t("fx.gitSkipped", { count: picked.length - files.length }));
|
||||
}
|
||||
if (!files.length) return;
|
||||
const bytes = files.reduce((n, f) => n + f.file.size, 0);
|
||||
if (bytes > FX_BATCH_MAX_BYTES) {
|
||||
@@ -924,11 +940,18 @@ export function FileBrowser({
|
||||
// owner whose home this viewer may not open (an analyst's view of other
|
||||
// users) still gets a row, one that only groups. A workspace with no owner
|
||||
// stays in the flat Workspaces list. Which rows are open is per browser.
|
||||
// A workspace whose folder was deleted has nothing to browse — it stays a
|
||||
// place only while it is the one open (so its error has a row to sit on).
|
||||
const placeLanes = useMemo(
|
||||
() =>
|
||||
lanes.filter((l) => !l.folder_missing || (!isHomePlace(target) && laneOf(target) === l.id)),
|
||||
[lanes, target]
|
||||
);
|
||||
const { lanesOfHome, userRows } = useMemo(() => {
|
||||
const ids = new Set(homes.map((h) => h.id));
|
||||
const map = new Map<string, Lane[]>();
|
||||
const extra = new Map<string, UserRow>();
|
||||
for (const l of lanes) {
|
||||
for (const l of placeLanes) {
|
||||
const home =
|
||||
myId != null && l.owner_id === myId && ids.has("me")
|
||||
? "me"
|
||||
@@ -951,9 +974,9 @@ export function FileBrowser({
|
||||
...[...extra.values()].sort((a, b) => a.label.localeCompare(b.label)),
|
||||
];
|
||||
return { lanesOfHome: map, userRows: rows };
|
||||
}, [homes, lanes, myId]);
|
||||
}, [homes, placeLanes, myId]);
|
||||
const grouped = new Set([...lanesOfHome.values()].flat().map((l) => l.id));
|
||||
const looseLanes = lanes.filter((l) => !grouped.has(l.id));
|
||||
const looseLanes = placeLanes.filter((l) => !grouped.has(l.id));
|
||||
// A home holding the open workspace shows it, whatever was stored.
|
||||
const homeIsOpen = (id: string, own: Lane[]) =>
|
||||
openHomes.has(id) ||
|
||||
@@ -1679,9 +1702,7 @@ export function FileBrowser({
|
||||
</MenuItem>
|
||||
)}
|
||||
{isHtml(menuItem) && menuTargets.length === 1 && (
|
||||
<MenuItem onSelect={close(() => download([menuItem]))}>
|
||||
{t("fx.download")}
|
||||
</MenuItem>
|
||||
<MenuItem onSelect={close(() => download([menuItem]))}>{t("fx.download")}</MenuItem>
|
||||
)}
|
||||
<MenuSeparator />
|
||||
{!ro && (
|
||||
|
||||
@@ -1470,25 +1470,40 @@ export function LaneChangesPanel({
|
||||
}
|
||||
};
|
||||
|
||||
// Discard all: every non-conflicted file in one `discard`, asked once in a
|
||||
// dialog that names how many untracked files it will delete.
|
||||
const discardAll = async () => {
|
||||
const rows = files.filter((f) => !f.conflicted);
|
||||
if (!rows.length) return;
|
||||
// Discard selected: exactly what Commit would take — the ticked files, and
|
||||
// only the ticked blocks of a partly ticked one (#87: it used to discard
|
||||
// every file, ticked or not) — in one `discard`, asked once in a dialog
|
||||
// that names how many untracked files it will delete.
|
||||
const discardTicked = async () => {
|
||||
if (!tickedPaths.length) return;
|
||||
const ok = await confirmDialog({
|
||||
title: t("changes.discardAllTitle"),
|
||||
message: t("changes.discardAllConfirm", {
|
||||
count: rows.length,
|
||||
untracked: rows.filter((f) => f.untracked).length,
|
||||
title: t("changes.discardTickedTitle"),
|
||||
message: t("changes.discardTickedConfirm", {
|
||||
count: tickedPaths.length,
|
||||
untracked: files.filter((f) => f.untracked && tickedPaths.includes(f.path)).length,
|
||||
}),
|
||||
confirmLabel: t("changes.discardAll"),
|
||||
confirmLabel: t("changes.discardTicked"),
|
||||
});
|
||||
if (ok)
|
||||
await act(
|
||||
"discard",
|
||||
rows.map((f) => f.path),
|
||||
true
|
||||
);
|
||||
if (!ok) return;
|
||||
const lane = laneId;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { paths, hunks } = await selection();
|
||||
await api.lanes.gitAction(target, "discard", {
|
||||
paths,
|
||||
...(hunks ? { hunks, context: CONTEXT_STEPS[0] } : {}),
|
||||
confirm: true,
|
||||
});
|
||||
if (laneNow.current !== lane) return;
|
||||
setConfirmDiscard(null);
|
||||
refreshGit();
|
||||
await load();
|
||||
} catch (err) {
|
||||
if (laneNow.current === lane) setError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
if (laneNow.current === lane) setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// resolve / merge-commit / merge-abort: same shape as `act`, other body.
|
||||
@@ -2067,8 +2082,7 @@ export function LaneChangesPanel({
|
||||
// An HTML page's relative CSS/scripts/images, read like a download — only
|
||||
// from the working tree: a commit's page would get today's files.
|
||||
const htmlFetch = useMemo(
|
||||
() =>
|
||||
range === "commit" ? null : fetchVia((p) => api.lanes.gitDownloadUrl(target, p)),
|
||||
() => (range === "commit" ? null : fetchVia((p) => api.lanes.gitDownloadUrl(target, p))),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[range, JSON.stringify(target)]
|
||||
);
|
||||
@@ -2863,13 +2877,13 @@ export function LaneChangesPanel({
|
||||
<button
|
||||
type="button"
|
||||
data-testid="lane-changes-discard-all"
|
||||
disabled={busy}
|
||||
onClick={() => void discardAll()}
|
||||
title={t("changes.discardAllTitle")}
|
||||
disabled={busy || tickedPaths.length === 0}
|
||||
onClick={() => void discardTicked()}
|
||||
title={t("changes.discardTickedTitle")}
|
||||
className="shrink-0 flex items-center gap-1 rounded border border-border-light px-1.5 py-0.5 text-[11px] text-status-danger hover:bg-status-danger/10 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" aria-hidden />
|
||||
{t("changes.discardAll")}
|
||||
{t("changes.discardTicked", { count: tickedPaths.length })}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -179,6 +179,18 @@ export function langFor(filePath: string) {
|
||||
}
|
||||
|
||||
/** Tokenized line text. `emph` marks the span that actually changed. */
|
||||
/** The tail of a row the server cut down (`LaneDiffLine.elided`). */
|
||||
function Elided({ n }: { n?: number }) {
|
||||
const { t, i18n } = useTranslation("lanes");
|
||||
if (!n) return null;
|
||||
const size = new Intl.NumberFormat(i18n.language, { notation: "compact" }).format(n);
|
||||
return (
|
||||
<span className="ml-1 select-none rounded bg-surface-3 px-1 font-sans text-[10px] text-fg-muted">
|
||||
{t("changes.lineElided", { size })}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Code({ text, lang, emph }: { text: string; lang: string; emph?: [number, number] }) {
|
||||
if (emph) {
|
||||
const [from, to] = emph;
|
||||
@@ -544,6 +556,7 @@ function UnifiedLine({
|
||||
{line.type === "add" ? "+" : line.type === "del" ? "-" : " "}
|
||||
</span>
|
||||
<Code text={line.text} lang={lang} emph={emph} />
|
||||
<Elided n={line.elided} />
|
||||
</span>
|
||||
{bar && <HunkBar change={bar} />}
|
||||
</Row>
|
||||
@@ -621,6 +634,7 @@ function SplitLine({
|
||||
/>
|
||||
<span className="whitespace-pre px-1">
|
||||
{line ? <Code text={line.text} lang={lang} emph={e} /> : null}
|
||||
{line ? <Elided n={line.elided} /> : null}
|
||||
</span>
|
||||
{bar && <HunkBar change={bar} />}
|
||||
</Row>
|
||||
|
||||
@@ -161,12 +161,19 @@ export function WorkspaceRow({
|
||||
e.preventDefault();
|
||||
onReorder(index, index + (e.key === "ArrowUp" ? -1 : 1));
|
||||
}}
|
||||
title={`${lane.cwd}\n${readOnly ?? t("row.hint")}`}
|
||||
title={`${lane.cwd}\n${lane.folder_missing ? t("row.folderMissing") : (readOnly ?? t("row.hint"))}`}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left"
|
||||
>
|
||||
<span aria-hidden className={`h-2 w-2 shrink-0 rounded-full ${workspaceDot(lane)}`} />
|
||||
<span className="sr-only">{t(`row.state.${workspaceDotLabel(lane)}`)}</span>
|
||||
<span className="truncate text-[13px] font-medium text-fg-primary">{name}</span>
|
||||
<span
|
||||
data-folder-missing={lane.folder_missing ? "true" : undefined}
|
||||
className={`truncate text-[13px] font-medium ${
|
||||
lane.folder_missing ? "text-fg-muted line-through" : "text-fg-primary"
|
||||
}`}
|
||||
>
|
||||
{name}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{readOnly && <Eye aria-label={readOnly} className="mr-1 h-3 w-3 shrink-0 text-fg-muted" />}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
* opens sub-folders, makes a folder inline, deletes into the Trash without a
|
||||
* confirm, copies in one workspace and pastes into another (`fromLane`),
|
||||
* asks Replace / Keep both / Skip when an upload's name is taken, refuses a
|
||||
* batch over 500 MB before sending anything, restores from the user's own
|
||||
* batch over 500 MB before sending anything, leaves a repo's .git out of a
|
||||
* folder upload with one notice, restores from the user's own
|
||||
* Trash, opens an admin's Trash on one folder per user (counted, an unreadable
|
||||
* one saying why), opens each user's Trash from its folder (asking before a
|
||||
* purge there, sending the item's store) and
|
||||
@@ -269,6 +270,23 @@ describe("FileExplorer", () => {
|
||||
expect(api.files.uploadBatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves a picked repo's .git out of a folder upload, with one notice", async () => {
|
||||
vi.mocked(api.files.upload).mockResolvedValue({ path: "x" });
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
const mk = (rel: string) => {
|
||||
const f = new File(["hi"], rel.split("/").pop()!);
|
||||
Object.defineProperty(f, "webkitRelativePath", { value: rel });
|
||||
return f;
|
||||
};
|
||||
const files = ["repo/.git/HEAD", "repo/.git/objects/d4/ab", "repo/src/a.js"].map(mk);
|
||||
fireEvent.change(screen.getByTestId("fx-upload-folder"), { target: { files } });
|
||||
await waitFor(() => expect(api.files.upload).toHaveBeenCalledTimes(1));
|
||||
expect(vi.mocked(api.files.upload).mock.calls[0]![1]).toBe("repo/src/a.js");
|
||||
expect(toast.info).toHaveBeenCalledTimes(1);
|
||||
expect(toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a batch over 500 MB before sending anything", async () => {
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
@@ -441,6 +459,33 @@ describe("FileExplorer", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves a workspace whose folder was deleted out of the places", async () => {
|
||||
vi.mocked(api.lanes.list).mockResolvedValue({
|
||||
lanes: [
|
||||
{ id: 1, title: "one", cwd: "/w/one" },
|
||||
{ id: 2, title: "two", cwd: "/w/two", folder_missing: true },
|
||||
],
|
||||
counts: {},
|
||||
} as never);
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
await waitFor(() => expect(api.lanes.list).toHaveBeenCalled());
|
||||
await screen.findByText("one", { selector: "aside span" });
|
||||
expect(screen.queryByRole("button", { name: "two" })).toBeNull();
|
||||
});
|
||||
|
||||
it("drops the last folder's entries when the next one cannot be read", async () => {
|
||||
vi.mocked(api.files.list).mockImplementation(async (_t, p = "") => {
|
||||
if (p === "src") throw new Error("ENOENT: no such file or directory");
|
||||
return root;
|
||||
});
|
||||
open();
|
||||
await screen.findByText("a.txt");
|
||||
fireEvent.doubleClick(row("src"));
|
||||
await screen.findByText(/ENOENT/);
|
||||
expect(screen.queryByText("a.txt")).toBeNull();
|
||||
});
|
||||
|
||||
it("right-clicks a sidebar workspace and a path crumb", async () => {
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
@@ -614,14 +659,16 @@ describe("FileExplorer — New → Clone repository", () => {
|
||||
const dialog = await openClone(user);
|
||||
await user.type(within(dialog).getByLabelText("Repository URL"), "git@host:o/repo.git");
|
||||
await user.click(within(dialog).getByTestId("fx-clone-submit"));
|
||||
expect(await within(dialog).findByRole("progressbar")).toHaveAttribute("aria-valuenow", "45");
|
||||
await user.click(within(dialog).getByRole("button", { name: "Run in background" }));
|
||||
// In the background straight away: the chip carries the progress.
|
||||
expect(screen.queryByTestId("fx-clone-dialog")).toBeNull();
|
||||
const chip = await screen.findByTestId("fx-clone-chip");
|
||||
expect(within(chip).getByText(/repo/)).toBeInTheDocument();
|
||||
expect(await within(chip).findByRole("progressbar")).toHaveAttribute("aria-valuenow", "45");
|
||||
await user.click(chip);
|
||||
expect(screen.getByTestId("fx-clone-dialog")).toBeInTheDocument();
|
||||
await user.keyboard("{Escape}");
|
||||
const back = screen.getByTestId("fx-clone-dialog");
|
||||
expect(await within(back).findByRole("progressbar")).toHaveAttribute("aria-valuenow", "45");
|
||||
await user.click(within(back).getByRole("button", { name: "Run in background" }));
|
||||
expect(screen.queryByTestId("fx-clone-dialog")).toBeNull();
|
||||
finish({
|
||||
lane: { id: 9, title: "repo", cwd: "/w/one/repo" },
|
||||
created: true,
|
||||
@@ -631,7 +678,7 @@ describe("FileExplorer — New → Clone repository", () => {
|
||||
expect(screen.queryByTestId("fx-clone-chip")).toBeNull();
|
||||
});
|
||||
|
||||
it("toasts a failure that lands while hidden and keeps it for the next open", async () => {
|
||||
it("toasts a failure that lands while hidden, and reopens the form for a login", async () => {
|
||||
let fail: (e: unknown) => void = () => {};
|
||||
vi.mocked(api.lanes.clone).mockReturnValue(new Promise((_, r) => (fail = r)) as never);
|
||||
vi.mocked(api.lanes.cloneProgress).mockRejectedValue(new Error("404"));
|
||||
@@ -641,12 +688,12 @@ describe("FileExplorer — New → Clone repository", () => {
|
||||
const dialog = await openClone(user);
|
||||
await user.type(within(dialog).getByLabelText("Repository URL"), "https://git.example/o/r.git");
|
||||
await user.click(within(dialog).getByTestId("fx-clone-submit"));
|
||||
await user.keyboard("{Escape}");
|
||||
fail(
|
||||
Object.assign(new Error("login"), { code: "ECREDENTIALS", auth: { host: "git.example" } })
|
||||
);
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalled());
|
||||
const again = await openClone(user);
|
||||
// A login to type reopens the form by itself, its row ready.
|
||||
const again = await screen.findByTestId("fx-clone-dialog");
|
||||
expect(within(again).getByTestId("fx-clone-login")).toBeInTheDocument();
|
||||
expect(within(again).getByLabelText("Repository URL")).toHaveValue(
|
||||
"https://git.example/o/r.git"
|
||||
@@ -669,10 +716,11 @@ describe("FileExplorer — New → Clone repository", () => {
|
||||
const dialog = await openClone(user);
|
||||
await user.type(within(dialog).getByLabelText("Repository URL"), "https://git.example/o/r.git");
|
||||
await user.click(within(dialog).getByTestId("fx-clone-submit"));
|
||||
const login = await within(dialog).findByTestId("fx-clone-login");
|
||||
const reopened = await screen.findByTestId("fx-clone-dialog");
|
||||
const login = await within(reopened).findByTestId("fx-clone-login");
|
||||
await user.type(within(login).getByLabelText("Username"), "ann");
|
||||
await user.type(within(login).getByLabelText("Password or access token"), "tok");
|
||||
await user.click(within(dialog).getByTestId("fx-clone-submit"));
|
||||
await user.click(within(reopened).getByTestId("fx-clone-submit"));
|
||||
await waitFor(() =>
|
||||
expect(api.lanes.clone).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -837,10 +837,12 @@ describe("LaneChangesPanel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("discards every file at once only after the dialog is confirmed", async () => {
|
||||
it("discards only the ticked files, and only after the dialog is confirmed (#87)", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LaneChangesPanel laneId={7} />);
|
||||
await screen.findByTestId("lane-changes-overview");
|
||||
// notes.txt (unversioned) starts unticked; untick docs/API.md too.
|
||||
await user.click(tickOf("docs/API.md"));
|
||||
|
||||
vi.mocked(confirmDialog).mockResolvedValueOnce(false);
|
||||
await user.click(screen.getByTestId("lane-changes-discard-all"));
|
||||
@@ -849,10 +851,14 @@ describe("LaneChangesPanel", () => {
|
||||
await user.click(screen.getByTestId("lane-changes-discard-all"));
|
||||
await waitFor(() =>
|
||||
expect(api.lanes.gitAction).toHaveBeenCalledWith(7, "discard", {
|
||||
paths: ["server/lib/git-ops.js", "notes.txt", "docs/API.md"],
|
||||
paths: ["server/lib/git-ops.js"],
|
||||
confirm: true,
|
||||
})
|
||||
);
|
||||
|
||||
// Nothing ticked: nothing to discard.
|
||||
await user.click(tickOf("server/lib/git-ops.js"));
|
||||
expect(screen.getByTestId("lane-changes-discard-all")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("right-click on a changed file offers Commit File, a two-click discard, copy path and patch", async () => {
|
||||
@@ -1673,6 +1679,25 @@ describe("LaneChangesPanel", () => {
|
||||
expect(api.lanes.gitAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("discards only the ticked change blocks of a partly ticked file (#87)", async () => {
|
||||
const user = userEvent.setup();
|
||||
await openReview(user);
|
||||
await user.click(
|
||||
screen.getAllByRole("checkbox", { name: "Include this change in the commit" })[1]!
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "Changes" }));
|
||||
await screen.findByTestId("lane-changes-commit");
|
||||
await user.click(screen.getByTestId("lane-changes-discard-all"));
|
||||
await waitFor(() =>
|
||||
expect(api.lanes.gitAction).toHaveBeenCalledWith(7, "discard", {
|
||||
paths: [],
|
||||
hunks: { "server/lib/git-ops.js": [{ hunk: "@@ -1,2 +1,3 @@", blocks: [0] }] },
|
||||
context: 3,
|
||||
confirm: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("commits only the ticked change blocks of a partly ticked file (hunks)", async () => {
|
||||
const user = userEvent.setup();
|
||||
await openReview(user);
|
||||
|
||||
@@ -609,3 +609,26 @@ describe("LaneDiffView — line comments", () => {
|
||||
expect(screen.queryByTestId("diff-comment-line-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("LaneDiffView — a row the server cut down", () => {
|
||||
const CUT: LaneChangeFile = {
|
||||
...FILE,
|
||||
hunks: [
|
||||
{
|
||||
...FILE.hunks![0]!,
|
||||
lines: [
|
||||
{ type: "del", oldLine: 1, newLine: null, text: '<video src="AAAA', elided: 3_000_000 },
|
||||
{ type: "add", oldLine: null, newLine: 1, text: '<video src="BBBB', elided: 3_000_000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("says how much of the row it hides, in both layouts", () => {
|
||||
const { unmount } = render(<LaneDiffView file={CUT} layout="unified" />);
|
||||
expect(screen.getAllByText(/3M more characters on this line/)).toHaveLength(2);
|
||||
unmount();
|
||||
render(<LaneDiffView file={CUT} layout="split" />);
|
||||
expect(screen.getAllByText(/3M more characters on this line/)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,6 +96,36 @@ type DropState = "hint" | "paste" | "uploading" | "failed" | "tooBig" | "tooBigL
|
||||
/** localStorage flag for xterm's screen-reader mode (a Settings toggle can set it later). */
|
||||
export const SCREEN_READER_KEY = "agenthub.terminal.screenReader";
|
||||
/** localStorage flag: the "Shift+drag selects text" hint was dismissed. */
|
||||
/** The atlas a WebGL addon draws from: @xterm/addon-webgl 0.19 keeps these
|
||||
* fields unminified in its build. Undefined on any other shape. */
|
||||
type AtlasPages = { pages: { version: number }[] };
|
||||
const atlasOf = (addon: WebglAddon): AtlasPages | undefined => {
|
||||
const atlas = (addon as unknown as { _renderer?: { _charAtlas?: AtlasPages } })._renderer
|
||||
?._charAtlas;
|
||||
return Array.isArray(atlas?.pages) ? atlas : undefined;
|
||||
};
|
||||
/** Last version handed out by `restampAtlas`, shared by every pane. */
|
||||
let atlasStamp = 0;
|
||||
/**
|
||||
* Gives every page of the addon's glyph atlas a version no texture slot has
|
||||
* uploaded, so EVERY renderer sharing that atlas re-uploads every page from
|
||||
* its canvas on its next draw — what addon-webgl 0.20 does with globally
|
||||
* monotonic page versions. 0.19 counts per page, so after a merge shifts the
|
||||
* pages down a slot can hold a stale page whose counter happens to match, and
|
||||
* glyphs are sampled squeezed or foreign. Steps of 2^24 stay clear of the
|
||||
* per-glyph increments a page makes before the next restamp. False when the
|
||||
* addon is not the shape this knows.
|
||||
*/
|
||||
const restampAtlas = (addon: WebglAddon): boolean => {
|
||||
const atlas = atlasOf(addon);
|
||||
if (!atlas) return false;
|
||||
for (const page of atlas.pages) {
|
||||
atlasStamp += 2 ** 24;
|
||||
page.version = atlasStamp;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const SELECT_HINT_KEY = "agenthub.terminal.selectHintSeen";
|
||||
const readFlag = (key: string) => {
|
||||
try {
|
||||
@@ -763,31 +793,40 @@ export const TerminalView = memo(function TerminalView({
|
||||
};
|
||||
document.fonts?.addEventListener("loadingdone", onFontLoaded);
|
||||
// @xterm/addon-webgl 0.19 shares ONE glyph atlas between every terminal
|
||||
// with the same font, and when it fills up it merges four pages into one
|
||||
// larger page and shifts the rest down. A GPU texture is re-uploaded only
|
||||
// when its page's `version` differs from the uploaded one, and after a
|
||||
// shift those counters can coincide, so a slot keeps a stale page of
|
||||
// another size: every glyph is sampled squeezed or foreign while the
|
||||
// buffer stays correct (fixed upstream only in 0.20 betas). Any option
|
||||
// change makes each renderer re-acquire its atlas and re-upload all pages,
|
||||
// so this toggles the family's trailing space (as onFontLoaded does) on
|
||||
// a merge. `clearTextureAtlas` is no fix: it empties the SHARED atlas
|
||||
// with the same font. When it fills up it merges four pages into one
|
||||
// larger page and shifts the rest down, and a GPU texture is re-uploaded
|
||||
// only when its page's `version` differs from the uploaded one — after a
|
||||
// shift those per-page counters can coincide, so a slot keeps a stale
|
||||
// page of another size and every glyph is drawn squeezed or foreign
|
||||
// while the buffer stays correct (fixed upstream only in 0.20 betas).
|
||||
// Any change to the page list therefore restamps every page's version
|
||||
// (`restampAtlas`) synchronously, before the next draw of ANY pane on
|
||||
// that atlas. `clearTextureAtlas` is no fix: it empties the SHARED atlas
|
||||
// but redraws only this pane, leaving its siblings slicing reused space.
|
||||
// An addon of another shape falls back to toggling the family's
|
||||
// trailing space on the next frame, which makes each renderer re-acquire
|
||||
// its atlas (as onFontLoaded does).
|
||||
let atlasFrame = 0;
|
||||
const rebuildAtlas = () => {
|
||||
if (atlasFrame) return;
|
||||
if (gpu && restampAtlas(gpu)) return true;
|
||||
if (atlasFrame) return false;
|
||||
// Never inside the render that is rasterizing the merging glyph.
|
||||
atlasFrame = requestAnimationFrame(() => {
|
||||
atlasFrame = 0;
|
||||
const family = term.options.fontFamily ?? "";
|
||||
term.options.fontFamily = family.endsWith(" ") ? family.trimEnd() : `${family} `;
|
||||
});
|
||||
return false;
|
||||
};
|
||||
const atlasMerged = gpu?.onRemoveTextureAtlasCanvas(rebuildAtlas);
|
||||
const atlasGrew = gpu?.onAddTextureAtlasCanvas(rebuildAtlas);
|
||||
// The browser may also drop the textures without a context-loss event
|
||||
// (sleep/resume, a long-backgrounded tab): rebuild when the page is back.
|
||||
// (sleep/resume, a long-backgrounded tab): re-upload when the page is
|
||||
// back, and repaint, since nothing else asks this pane to draw.
|
||||
const onPageShown = () => {
|
||||
if (document.visibilityState === "visible") rebuildAtlas();
|
||||
if (document.visibilityState === "visible" && rebuildAtlas()) {
|
||||
term.refresh(0, term.rows - 1);
|
||||
}
|
||||
};
|
||||
document.addEventListener("visibilitychange", onPageShown);
|
||||
window.addEventListener("focus", onPageShown);
|
||||
@@ -811,6 +850,7 @@ export const TerminalView = memo(function TerminalView({
|
||||
document.fonts?.removeEventListener("loadingdone", onFontLoaded);
|
||||
if (atlasFrame) cancelAnimationFrame(atlasFrame);
|
||||
atlasMerged?.dispose();
|
||||
atlasGrew?.dispose();
|
||||
document.removeEventListener("visibilitychange", onPageShown);
|
||||
window.removeEventListener("focus", onPageShown);
|
||||
window.removeEventListener(FONT_SIZE_EVENT, onFontPref);
|
||||
|
||||
@@ -63,6 +63,9 @@ const termState = {
|
||||
};
|
||||
const onResizeHandlers: Array<() => void> = [];
|
||||
const termOptions: { theme?: unknown } = {};
|
||||
const refreshMock = vi.fn();
|
||||
/** The atlas the next WebGL addon draws from; null = an addon of another shape. */
|
||||
const nextAtlas: { pages: { version: number }[] | null } = { pages: null };
|
||||
const ctorArgs: Array<{ theme?: unknown }> = [];
|
||||
|
||||
vi.mock("@xterm/xterm", () => ({
|
||||
@@ -92,6 +95,7 @@ vi.mock("@xterm/xterm", () => ({
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
dispose: disposeMock,
|
||||
refresh: refreshMock,
|
||||
loadAddon: loadAddonMock,
|
||||
attachCustomWheelEventHandler: wheelHandlerMock,
|
||||
attachCustomKeyEventHandler: keyHandlerMock,
|
||||
@@ -113,7 +117,12 @@ vi.mock("@xterm/addon-fit", () => ({
|
||||
}));
|
||||
// The newest WebGL addon, with the context-loss listener the view gave it.
|
||||
const gpu: {
|
||||
last: { dispose: ReturnType<typeof vi.fn>; lose: () => void; merge: () => void } | null;
|
||||
last: {
|
||||
dispose: ReturnType<typeof vi.fn>;
|
||||
lose: () => void;
|
||||
merge: () => void;
|
||||
grow: () => void;
|
||||
} | null;
|
||||
} = {
|
||||
last: null,
|
||||
};
|
||||
@@ -121,8 +130,10 @@ vi.mock("@xterm/addon-webgl", () => ({
|
||||
WebglAddon: vi.fn().mockImplementation(() => {
|
||||
let onLoss = () => {};
|
||||
let onMerge = () => {};
|
||||
let onGrow = () => {};
|
||||
const addon = {
|
||||
__webgl: true,
|
||||
...(nextAtlas.pages ? { _renderer: { _charAtlas: { pages: nextAtlas.pages } } } : {}),
|
||||
dispose: vi.fn(),
|
||||
onContextLoss: (fn: () => void) => {
|
||||
onLoss = fn;
|
||||
@@ -132,8 +143,17 @@ vi.mock("@xterm/addon-webgl", () => ({
|
||||
onMerge = fn;
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
onAddTextureAtlasCanvas: (fn: () => void) => {
|
||||
onGrow = fn;
|
||||
return { dispose: vi.fn() };
|
||||
},
|
||||
};
|
||||
gpu.last = {
|
||||
dispose: addon.dispose,
|
||||
lose: () => onLoss(),
|
||||
merge: () => onMerge(),
|
||||
grow: () => onGrow(),
|
||||
};
|
||||
gpu.last = { dispose: addon.dispose, lose: () => onLoss(), merge: () => onMerge() };
|
||||
return addon;
|
||||
}),
|
||||
}));
|
||||
@@ -495,9 +515,37 @@ describe("TerminalView", () => {
|
||||
expect(disposeMock).not.toHaveBeenCalled(); // the terminal itself lives on
|
||||
});
|
||||
|
||||
it("restamps every atlas page at once when the page list changes", () => {
|
||||
// addon-webgl 0.19 counts versions per page, so after a merge shifts the
|
||||
// pages a texture slot can keep a stale page whose counter matches. Every
|
||||
// page gets a version no slot has uploaded — in every pane on the atlas.
|
||||
const pages = [{ version: 3 }, { version: 7 }, { version: 1 }];
|
||||
nextAtlas.pages = pages;
|
||||
const raf = vi.spyOn(window, "requestAnimationFrame");
|
||||
try {
|
||||
render(<TerminalView runId="agenthub-lane-1" wsBaseUrl="ws://localhost:4820" />);
|
||||
gpu.last!.merge();
|
||||
const first = pages.map((p) => p.version);
|
||||
expect(new Set(first).size).toBe(3);
|
||||
expect(first.every((v) => v > 7)).toBe(true);
|
||||
gpu.last!.grow();
|
||||
expect(pages.every((p, i) => p.version > Math.max(...first) && p.version !== first[i])).toBe(
|
||||
true
|
||||
);
|
||||
expect(raf).not.toHaveBeenCalled(); // synchronous, before any pane draws
|
||||
// The page coming back re-uploads and repaints this pane.
|
||||
refreshMock.mockClear();
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
expect(refreshMock).toHaveBeenCalledWith(0, 27);
|
||||
} finally {
|
||||
nextAtlas.pages = null;
|
||||
raf.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("re-acquires the glyph atlas on the next frame after a page merge", () => {
|
||||
// addon-webgl 0.19 may keep a stale page in a GPU slot after it merges
|
||||
// atlas pages; any option change makes it re-upload every page.
|
||||
// An addon whose atlas this cannot reach: any option change makes each
|
||||
// renderer re-acquire its atlas and re-upload every page.
|
||||
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation(() => 1);
|
||||
render(<TerminalView runId="agenthub-lane-1" wsBaseUrl="ws://localhost:4820" />);
|
||||
const opts = termOptions as { fontFamily?: string };
|
||||
|
||||
@@ -28,6 +28,12 @@
|
||||
"unshare": "Unshare",
|
||||
"shareDone": "Shared to the Hub",
|
||||
"unshareDone": "Removed from the Hub",
|
||||
"reshare": "Share again",
|
||||
"reshareDone": "New version shared — people who installed it are offered Update",
|
||||
"reshareSame": "Already the newest version — shared",
|
||||
"reshareAskTitle": "Choose the {{name}} folder again",
|
||||
"reshareAskBody": "This server has no copy of {{name}}. Choose the skill's folder (the one holding SKILL.md): it replaces this version, and people who installed it are offered Update. For a .zip, upload it through Add skill → Upload: a skill with the same name updates your existing one.",
|
||||
"resharePick": "Choose folder",
|
||||
"open": "Open",
|
||||
"copyLink": "Copy link",
|
||||
"preview": "Preview",
|
||||
@@ -136,6 +142,11 @@
|
||||
"installsYou": "You",
|
||||
"installsUnknown": "A removed user",
|
||||
"installsReplaced": "replaced an older copy",
|
||||
"versionAt": "Updated {{ago}}",
|
||||
"versionAtFull": "Last updated {{date}}",
|
||||
"installState.latest": "Latest",
|
||||
"installState.outdated": "Old version",
|
||||
"installState.removed": "Removed",
|
||||
"installsPluginWhere": "claude plugin install --scope user",
|
||||
"installsUnrecorded": "{{count}} earlier installs were counted before details were kept",
|
||||
"installsNoneOfYours": "You have not installed it — only your own installs are listed.",
|
||||
@@ -179,7 +190,7 @@
|
||||
"stat.installs": "Installs",
|
||||
"stat.files": "Files",
|
||||
"stat.size": "Size",
|
||||
"stat.updated": "Updated",
|
||||
"stat.updated": "Last updated",
|
||||
"detail.runAs": "Run it as",
|
||||
"detail.market": "Marketplace",
|
||||
"detail.added": "Added {{date}}",
|
||||
|
||||
@@ -92,6 +92,7 @@
|
||||
"changes.expandFile": "Expand {{path}}",
|
||||
"changes.fileGone": "That file no longer has changes in this range.",
|
||||
"changes.fileTruncated": "Diff cut short — open the file in an editor for the rest.",
|
||||
"changes.lineElided": "… {{size}} more characters on this line",
|
||||
"changes.commentLine": "Comment on line {{n}} — pasted into this workspace's pane",
|
||||
"changes.commentOn": "Comment on {{at}} — pasted into the pane you used last; nothing is sent until you press Enter there",
|
||||
"changes.commentSend": "Paste into pane",
|
||||
@@ -342,6 +343,7 @@
|
||||
"changes.takeTheirsHint": "Take the incoming version of the whole file",
|
||||
"row.actions": "Workspace actions",
|
||||
"row.hint": "Double-click to rename · drag or Alt+↑/↓ to reorder · right-click for actions",
|
||||
"row.folderMissing": "Folder deleted — remove this workspace from its ⋯ menu",
|
||||
"menu.rename": "Rename",
|
||||
"menu.newHere": "New workspace here…",
|
||||
"menu.copyPath": "Copy path",
|
||||
@@ -531,9 +533,9 @@
|
||||
"changes.unversionedGroup": "Unversioned Files",
|
||||
"changes.commitTicked": "Commit ({{count}})",
|
||||
"changes.commitAndPush": "Commit and Push",
|
||||
"changes.discardAll": "Discard all",
|
||||
"changes.discardAllTitle": "Discard all changes?",
|
||||
"changes.discardAllConfirm": "Every change in {{count}} file(s) goes back to the last commit, and {{untracked}} new file(s) git does not track yet are deleted. This cannot be undone.",
|
||||
"changes.discardTicked": "Discard ({{count}})",
|
||||
"changes.discardTickedTitle": "Discard the ticked changes?",
|
||||
"changes.discardTickedConfirm": "The ticked changes in {{count}} file(s) go back to the last commit, and {{untracked}} ticked new file(s) git does not track yet are deleted. Unticked files and blocks are kept. This cannot be undone.",
|
||||
"changes.amendAndPush": "Amend and Push",
|
||||
"changes.pushFailed": "Committed, but the push failed: {{error}}",
|
||||
"changes.tickFile": "Include {{path}} in the commit",
|
||||
@@ -589,6 +591,7 @@
|
||||
"fx.dropHint": "Drag files or folders here to upload · drag onto a folder to move (Ctrl: copy)",
|
||||
"fx.uploading": "Uploading {{done}}/{{total}}…",
|
||||
"fx.uploaded": "Uploaded {{count}} file(s).",
|
||||
"fx.gitSkipped": "Skipped {{count}} file(s) inside .git — nothing is uploaded into .git.",
|
||||
"fx.uploadFailed": "Could not upload {{name}}: {{message}}",
|
||||
"fx.tooBig": "{{size}} is more than one upload may carry ({{max}}). Upload fewer files at a time.",
|
||||
"fx.trashed": "Moved {{count}} item(s) to the Trash.",
|
||||
|
||||
@@ -28,6 +28,12 @@
|
||||
"unshare": "Bỏ chia sẻ",
|
||||
"shareDone": "Đã chia sẻ lên Hub",
|
||||
"unshareDone": "Đã gỡ khỏi Hub",
|
||||
"reshare": "Share lại",
|
||||
"reshareDone": "Đã share bản mới — người đã cài sẽ thấy nút Cập nhật",
|
||||
"reshareSame": "Đã là bản mới nhất — đã share",
|
||||
"reshareAskTitle": "Chọn lại thư mục {{name}}",
|
||||
"reshareAskBody": "Server không có bản của {{name}}. Chọn thư mục của skill (thư mục chứa SKILL.md): bản này sẽ được thay, và người đã cài sẽ thấy nút Cập nhật. Với file .zip, tải lên qua Thêm skill → Tải lên: skill trùng tên sẽ cập nhật mục bạn đã có.",
|
||||
"resharePick": "Chọn thư mục",
|
||||
"open": "Mở",
|
||||
"copyLink": "Sao chép link",
|
||||
"preview": "Xem",
|
||||
@@ -137,6 +143,11 @@
|
||||
"installsYou": "Bạn",
|
||||
"installsUnknown": "Người dùng đã xoá",
|
||||
"installsReplaced": "thay bản cũ",
|
||||
"versionAt": "Cập nhật {{ago}}",
|
||||
"versionAtFull": "Cập nhật lần cuối {{date}}",
|
||||
"installState.latest": "Bản mới nhất",
|
||||
"installState.outdated": "Bản cũ",
|
||||
"installState.removed": "Đã gỡ",
|
||||
"installsPluginWhere": "claude plugin install --scope user",
|
||||
"installsUnrecorded": "{{count}} lượt cài trước đây chỉ được đếm, không lưu chi tiết",
|
||||
"installsNoneOfYours": "Bạn chưa cài — chỉ hiện các lượt cài của bạn.",
|
||||
@@ -180,7 +191,7 @@
|
||||
"stat.installs": "Lượt cài",
|
||||
"stat.files": "File",
|
||||
"stat.size": "Dung lượng",
|
||||
"stat.updated": "Cập nhật",
|
||||
"stat.updated": "Cập nhật lần cuối",
|
||||
"detail.runAs": "Gọi bằng",
|
||||
"detail.market": "Marketplace",
|
||||
"detail.added": "Thêm lúc {{date}}",
|
||||
|
||||
@@ -92,6 +92,7 @@
|
||||
"changes.expandFile": "Mở {{path}}",
|
||||
"changes.fileGone": "File này không còn thay đổi nào trong phạm vi đang xem.",
|
||||
"changes.fileTruncated": "Diff bị cắt bớt — mở file trong editor để xem phần còn lại.",
|
||||
"changes.lineElided": "… còn {{size}} ký tự trên dòng này",
|
||||
"changes.commentLine": "Comment dòng {{n}} — dán vào pane của workspace này",
|
||||
"changes.commentOn": "Comment {{at}} — dán vào pane bạn dùng gần nhất; chưa gửi gì cho tới khi bạn nhấn Enter ở đó",
|
||||
"changes.commentSend": "Dán vào pane",
|
||||
@@ -342,6 +343,7 @@
|
||||
"changes.takeTheirsHint": "Lấy bản kia cho cả file",
|
||||
"row.actions": "Thao tác workspace",
|
||||
"row.hint": "Nhấp đúp để đổi tên · kéo hoặc Alt+↑/↓ để sắp xếp · chuột phải để xem thao tác",
|
||||
"row.folderMissing": "Thư mục đã bị xóa — gỡ workspace này trong menu ⋯",
|
||||
"menu.rename": "Đổi tên",
|
||||
"menu.newHere": "Workspace mới tại đây…",
|
||||
"menu.copyPath": "Sao chép đường dẫn",
|
||||
@@ -531,9 +533,9 @@
|
||||
"changes.unversionedGroup": "File chưa theo dõi",
|
||||
"changes.commitTicked": "Commit ({{count}})",
|
||||
"changes.commitAndPush": "Commit và Push",
|
||||
"changes.discardAll": "Bỏ tất cả",
|
||||
"changes.discardAllTitle": "Bỏ tất cả thay đổi?",
|
||||
"changes.discardAllConfirm": "Mọi thay đổi trong {{count}} file sẽ trở về commit cuối, và {{untracked}} file mới chưa được git theo dõi sẽ bị xoá. Không thể hoàn tác.",
|
||||
"changes.discardTicked": "Bỏ ({{count}})",
|
||||
"changes.discardTickedTitle": "Bỏ các thay đổi đã chọn?",
|
||||
"changes.discardTickedConfirm": "Các thay đổi đã chọn trong {{count}} file sẽ trở về commit cuối, và {{untracked}} file mới đã chọn chưa được git theo dõi sẽ bị xoá. File và đoạn không chọn được giữ nguyên. Không thể hoàn tác.",
|
||||
"changes.amendAndPush": "Amend và Push",
|
||||
"changes.pushFailed": "Đã commit, nhưng push thất bại: {{error}}",
|
||||
"changes.tickFile": "Đưa {{path}} vào commit",
|
||||
@@ -589,6 +591,7 @@
|
||||
"fx.dropHint": "Kéo file hoặc thư mục vào đây để tải lên · kéo vào một thư mục để di chuyển (Ctrl: sao chép)",
|
||||
"fx.uploading": "Đang tải lên {{done}}/{{total}}…",
|
||||
"fx.uploaded": "Đã tải lên {{count}} file.",
|
||||
"fx.gitSkipped": "Đã bỏ qua {{count}} file trong .git — không tải gì vào .git.",
|
||||
"fx.uploadFailed": "Không tải lên được {{name}}: {{message}}",
|
||||
"fx.tooBig": "{{size}} vượt quá giới hạn một lần tải lên ({{max}}). Hãy tải ít file hơn mỗi lần.",
|
||||
"fx.trashed": "Đã chuyển {{count}} mục vào Thùng rác.",
|
||||
|
||||
+23
-6
@@ -3324,16 +3324,17 @@ export const api = {
|
||||
* several skills at once (one artifact each). `path` keeps a folder's layout. */
|
||||
uploadSkills: (
|
||||
files: { file: File; path: string }[],
|
||||
fields: { name?: string; title?: string; description?: string } = {}
|
||||
/** `id`: Share again — the upload replaces that skill row's version. */
|
||||
fields: { name?: string; title?: string; description?: string; id?: string } = {}
|
||||
) => {
|
||||
const form = new FormData();
|
||||
for (const f of files) form.append("files", f.file, f.file.name);
|
||||
form.append("paths", JSON.stringify(files.map((f) => f.path)));
|
||||
for (const [k, v] of Object.entries(fields)) if (v) form.append(k, v);
|
||||
return request<{ items: Artifact[] }>("/artifacts/skill/upload", {
|
||||
method: "POST",
|
||||
body: form,
|
||||
});
|
||||
return request<{ items: (Artifact & { replaced?: boolean; changed?: boolean })[] }>(
|
||||
"/artifacts/skill/upload",
|
||||
{ method: "POST", body: form }
|
||||
);
|
||||
},
|
||||
/** One file from the user's computer, kept like a pinned one (≤ 25 MB). */
|
||||
uploadFile: (file: File, fields: { title?: string; description?: string } = {}) => {
|
||||
@@ -3372,6 +3373,12 @@ export const api = {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
/** POST /api/artifacts/:id/reshare — Share again: the owner's skill folder on
|
||||
* the server becomes the new version (409 ENOSOURCE when it has none). */
|
||||
reshare: (id: number) =>
|
||||
request<{ item: Artifact; changed: boolean }>(`/artifacts/${id}/reshare`, {
|
||||
method: "POST",
|
||||
}),
|
||||
/** `kept`: a shared one left your library but stays in the Hub. */
|
||||
remove: (id: number) =>
|
||||
request<{ ok: true; kept: boolean }>(`/artifacts/${id}`, { method: "DELETE" }),
|
||||
@@ -4713,11 +4720,21 @@ export interface Artifact {
|
||||
suggestedForMe?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
/** When its content last changed (a new snapshot); a page or plugin: when it was added. */
|
||||
versionAt: string;
|
||||
}
|
||||
|
||||
/** GET /api/artifacts/:id/installs. `paths` only for your own installs (or an admin). */
|
||||
export interface ArtifactInstalls {
|
||||
items: { user: string | null; mine: boolean; at: string; replaced: boolean; paths?: string[] }[];
|
||||
items: {
|
||||
user: string | null;
|
||||
mine: boolean;
|
||||
at: string;
|
||||
replaced: boolean;
|
||||
/** Skills: where that install's copy stands against the newest version now. */
|
||||
state?: "latest" | "outdated" | "removed" | "unknown";
|
||||
paths?: string[];
|
||||
}[];
|
||||
/** Installs counted before the list was kept. */
|
||||
unrecorded: number;
|
||||
}
|
||||
|
||||
@@ -2731,6 +2731,8 @@ export interface Lane {
|
||||
stage_seconds: number | null;
|
||||
last_event_seconds: number | null;
|
||||
liveness: "active" | "idle" | "dead";
|
||||
/** The workspace's folder no longer exists (deleted from Files or a shell). */
|
||||
folder_missing?: boolean;
|
||||
/** Stage id the server's heuristic infers from ingested tool events, or null
|
||||
* if no signal was seen. Independent of `stage` (the agent's own declaration). */
|
||||
detected_stage: string | null;
|
||||
@@ -2974,6 +2976,9 @@ export interface LaneDiffLine {
|
||||
/** Line number on the right (after) side; null on a removed line. */
|
||||
newLine: number | null;
|
||||
text: string;
|
||||
/** Characters cut off the end of a very long row (a base64 blob, a minified
|
||||
* bundle): `text` holds only its start. Absent on a whole row. */
|
||||
elided?: number;
|
||||
}
|
||||
|
||||
/** `GET /api/lanes/:id/git/blame` — Annotate: who last changed each line of
|
||||
|
||||
@@ -28,9 +28,14 @@
|
||||
* **Installed** instead of the Install button; **Uninstall** (a skill's
|
||||
* copies moved aside, a plugin `claude plugin uninstall`) is offered only in
|
||||
* the card's ⋯ menu. A skill follows its owner's folder (the server takes a
|
||||
* change there as a new snapshot when the Hub is listed); an installed copy
|
||||
* change there as a new snapshot when the Hub is listed; **Share again**
|
||||
* takes its folder on the server — or a plugin's copy — on a click, else
|
||||
* asks for the folder and uploads it onto the same row); an installed copy
|
||||
* that differs from the newest version shows **Update** (a pack: "Update N"),
|
||||
* which replaces it after a confirmation, the old copy moved aside. Editing a skill
|
||||
* which replaces it after a confirmation, the old copy moved aside. A skill or
|
||||
* file row says when its CONTENT last changed ("Updated 3h ago", `versionAt`),
|
||||
* and the install count's list marks each installer's copy Latest / Old
|
||||
* version / Removed. Editing a skill
|
||||
* edits its SKILL.md (name, description, instructions — a new snapshot);
|
||||
* its preview opens with what it installs as and when Claude uses it. Deleting a shared
|
||||
* row of your own only takes it out of your library — it stays in the Hub
|
||||
@@ -79,6 +84,7 @@ import { toast } from "../lib/toast";
|
||||
import { confirmDialog } from "../lib/confirm";
|
||||
import { useDialog } from "../hooks/useDialog";
|
||||
import { copyText } from "../lib/clipboard";
|
||||
import { timeAgo } from "../lib/format";
|
||||
import { ContextMenu, MenuItem, MenuSeparator, useContextMenu } from "../components/ContextMenu";
|
||||
import {
|
||||
FileUploadPanel,
|
||||
@@ -277,6 +283,53 @@ export function Artifacts() {
|
||||
}
|
||||
};
|
||||
|
||||
// Share again: the server's copy of the skill, else the folder picked again
|
||||
// (uploaded onto the same row). Either way installers are offered Update.
|
||||
const reshareInput = useRef<HTMLInputElement>(null);
|
||||
const reshareRow = useRef<Artifact | null>(null);
|
||||
useEffect(() => {
|
||||
reshareInput.current?.setAttribute("webkitdirectory", "");
|
||||
}, []);
|
||||
const reshared = (changed: boolean) => {
|
||||
toast.success(t(changed ? "reshareDone" : "reshareSame"));
|
||||
load();
|
||||
};
|
||||
const reshare = async (a: Artifact) => {
|
||||
try {
|
||||
const r = await api.artifacts.reshare(a.id);
|
||||
reshared(r.changed);
|
||||
} catch (err) {
|
||||
if ((err as { code?: string }).code !== "ENOSOURCE") return toast.error(err);
|
||||
if (
|
||||
!(await confirmDialog({
|
||||
title: t("reshareAskTitle", { name: a.source ?? a.title }),
|
||||
message: t("reshareAskBody", { name: a.source ?? a.title }),
|
||||
confirmLabel: t("resharePick"),
|
||||
}))
|
||||
)
|
||||
return;
|
||||
reshareRow.current = a;
|
||||
reshareInput.current?.click();
|
||||
}
|
||||
};
|
||||
const reshareUpload = async (list: FileList | null) => {
|
||||
const a = reshareRow.current;
|
||||
reshareRow.current = null;
|
||||
if (!a || !list?.length) return;
|
||||
try {
|
||||
const r = await api.artifacts.uploadSkills(
|
||||
Array.from(list).map((file) => ({
|
||||
file,
|
||||
path: (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name,
|
||||
})),
|
||||
{ id: String(a.id) }
|
||||
);
|
||||
reshared(r.items.some((i) => i.changed !== false));
|
||||
} catch (err) {
|
||||
toast.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
const [renaming, setRenaming] = useState<Artifact | null>(null);
|
||||
|
||||
const remove = async (a: Artifact) => {
|
||||
@@ -442,6 +495,7 @@ export function Artifacts() {
|
||||
const actionsFor = (a: Artifact): CardActions => ({
|
||||
onOpen: () => setDetailId(a.id),
|
||||
onShare: () => void share(a),
|
||||
onReshare: () => void reshare(a),
|
||||
onRename: () => {
|
||||
setDetailId(null);
|
||||
setRenaming(a);
|
||||
@@ -572,6 +626,17 @@ export function Artifacts() {
|
||||
|
||||
return (
|
||||
<div className="animate-fade-in space-y-5" data-testid="artifacts-page">
|
||||
<input
|
||||
ref={reshareInput}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
data-testid="artifact-reshare-folder"
|
||||
onChange={(e) => {
|
||||
void reshareUpload(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-lg font-semibold text-fg-primary">{t("title")}</h1>
|
||||
@@ -1066,6 +1131,8 @@ function EmptyState({
|
||||
type CardActions = {
|
||||
onOpen: () => void;
|
||||
onShare: () => void;
|
||||
/** A skill of your own: its newest version, shared (installers get Update). */
|
||||
onReshare: () => void;
|
||||
onRename: () => void;
|
||||
onDelete: () => void;
|
||||
onInstall: () => void;
|
||||
@@ -1208,6 +1275,7 @@ function Meta({
|
||||
server: boolean;
|
||||
date?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const parts: React.ReactNode[] = [];
|
||||
if (server && a.owner && !a.mine)
|
||||
parts.push(
|
||||
@@ -1215,7 +1283,18 @@ function Meta({
|
||||
{a.owner}
|
||||
</span>
|
||||
);
|
||||
if (date)
|
||||
// A skill or file is a snapshot that changes: when it last did. Anything else: when added.
|
||||
if (a.kind === "skill" || a.kind === "file")
|
||||
parts.push(
|
||||
<span
|
||||
key="at"
|
||||
className="shrink-0"
|
||||
title={t("versionAtFull", { date: new Date(a.versionAt).toLocaleString() })}
|
||||
>
|
||||
{t("versionAt", { ago: timeAgo(a.versionAt) })}
|
||||
</span>
|
||||
);
|
||||
else if (date)
|
||||
parts.push(
|
||||
<span key="at" className="shrink-0" title={new Date(a.createdAt).toLocaleString()}>
|
||||
{fmtDate(a.createdAt)}
|
||||
@@ -1237,6 +1316,7 @@ function ArtifactMenu({
|
||||
menu,
|
||||
onOpen,
|
||||
onShare,
|
||||
onReshare,
|
||||
onRename,
|
||||
onDelete,
|
||||
onInstall,
|
||||
@@ -1297,6 +1377,9 @@ function ArtifactMenu({
|
||||
{t(hubOnly ? "hubRemove" : a.shared ? "unshare" : "share")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{server && a.kind === "skill" && (
|
||||
<MenuItem onSelect={pick(onReshare)}>{t("reshare")}</MenuItem>
|
||||
)}
|
||||
<MenuItem onSelect={pick(onRename)}>{t("rename")}</MenuItem>
|
||||
{!hubOnly && (
|
||||
<MenuItem danger onSelect={pick(onDelete)}>
|
||||
@@ -1447,6 +1530,7 @@ function DetailDialog({
|
||||
canInstall,
|
||||
onClose,
|
||||
onShare,
|
||||
onReshare,
|
||||
onRename,
|
||||
onDelete,
|
||||
onInstall,
|
||||
@@ -1468,7 +1552,10 @@ function DetailDialog({
|
||||
: []),
|
||||
...(a.files.length ? [{ label: t("stat.files"), value: String(a.files.length) }] : []),
|
||||
...(a.size ? [{ label: t("stat.size"), value: fmtBytes(a.size) }] : []),
|
||||
{ label: t("stat.updated"), value: fmtDate(a.updatedAt) },
|
||||
{
|
||||
label: t("stat.updated"),
|
||||
value: new Date(a.versionAt).toLocaleString(),
|
||||
},
|
||||
];
|
||||
return (
|
||||
<Modal title={a.title} onClose={onClose} size="md">
|
||||
@@ -1611,6 +1698,11 @@ function DetailDialog({
|
||||
{t(hubOnly ? "hubRemove" : a.shared ? "unshare" : "share")}
|
||||
</button>
|
||||
)}
|
||||
{server && a.kind === "skill" && (
|
||||
<button type="button" className={secondary} onClick={onReshare}>
|
||||
{t("reshare")}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={secondary} onClick={onRename}>
|
||||
{t("rename")}
|
||||
</button>
|
||||
@@ -1634,6 +1726,13 @@ function DetailDialog({
|
||||
* The list floats over the page (a portal at the button, below it or above
|
||||
* when there is no room, kept inside the window): inside the card list's
|
||||
* `overflow-hidden` it was cut off at the last card. */
|
||||
/** An installer's copy against the newest version: green, amber, grey. */
|
||||
const STATE_CLASS = {
|
||||
latest: "bg-status-success/15 text-status-success",
|
||||
outdated: "bg-status-warning/15 text-status-warning",
|
||||
removed: "bg-surface-2 text-fg-muted",
|
||||
} as const;
|
||||
|
||||
function InstallsButton({ item }: { item: Artifact }) {
|
||||
const { t } = useTranslation("artifacts");
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -1725,6 +1824,14 @@ function InstallsButton({ item }: { item: Artifact }) {
|
||||
<span className="ml-1 text-fg-muted">· {t("installsReplaced")}</span>
|
||||
)}
|
||||
</span>
|
||||
{i.state && i.state !== "unknown" && (
|
||||
<span
|
||||
data-testid="install-state"
|
||||
className={`shrink-0 rounded px-1 text-[10px] ${STATE_CLASS[i.state]}`}
|
||||
>
|
||||
{t(`installState.${i.state}`)}
|
||||
</span>
|
||||
)}
|
||||
<span className="shrink-0 text-[11px] text-fg-muted">
|
||||
{new Date(i.at).toLocaleString()}
|
||||
</span>
|
||||
|
||||
@@ -50,7 +50,10 @@ export function FilesPage() {
|
||||
// The workspace last shown first: Files reached from a workspace opens
|
||||
// THAT workspace (from PhuNT → AC_SHOP it opened your own home, empty
|
||||
// but for hidden files); the home is the fallback.
|
||||
const { lanes } = await api.lanes.list().catch(() => ({ lanes: [] }));
|
||||
// A workspace whose folder was deleted has nothing to open.
|
||||
const lanes = (await api.lanes.list().catch(() => ({ lanes: [] }))).lanes.filter(
|
||||
(l) => !l.folder_missing
|
||||
);
|
||||
const last = lastWorkspace();
|
||||
const shown = lanes.find((l) => l.id === last);
|
||||
if (shown) return setStart({ lane: shown.id });
|
||||
|
||||
@@ -46,6 +46,7 @@ vi.mock("../../lib/api", () => ({
|
||||
addPlugin: vi.fn(),
|
||||
inspectMarket: vi.fn(),
|
||||
uploadSkills: vi.fn(),
|
||||
reshare: vi.fn(),
|
||||
writeSkill: vi.fn(),
|
||||
uploadFile: vi.fn(),
|
||||
candidates: vi.fn(),
|
||||
@@ -76,6 +77,7 @@ const item = (over: Partial<Artifact>): Artifact => ({
|
||||
installs: 0,
|
||||
createdAt: "2026-10-14T00:00:00Z",
|
||||
updatedAt: "2026-10-14T00:00:00Z",
|
||||
versionAt: "2026-10-14T00:00:00Z",
|
||||
...over,
|
||||
});
|
||||
|
||||
@@ -348,9 +350,16 @@ describe("Artifacts", () => {
|
||||
mine: true,
|
||||
at: "2026-10-19T10:00:00Z",
|
||||
replaced: false,
|
||||
state: "latest",
|
||||
paths: ["/h/.claude/skills/deploy"],
|
||||
},
|
||||
{ user: "khoa", mine: false, at: "2026-10-18T10:00:00Z", replaced: true },
|
||||
{
|
||||
user: "khoa",
|
||||
mine: false,
|
||||
at: "2026-10-18T10:00:00Z",
|
||||
replaced: true,
|
||||
state: "outdated",
|
||||
},
|
||||
],
|
||||
unrecorded: 1,
|
||||
});
|
||||
@@ -362,6 +371,12 @@ describe("Artifacts", () => {
|
||||
expect(await within(box).findByText("/h/.claude/skills/deploy")).toBeInTheDocument();
|
||||
expect(within(box).getByText(/khoa/)).toBeInTheDocument();
|
||||
expect(within(box).getByText(/1 earlier installs/)).toBeInTheDocument();
|
||||
// Each install says whether its copy is the newest version.
|
||||
expect(
|
||||
within(box)
|
||||
.getAllByTestId("install-state")
|
||||
.map((b) => b.textContent)
|
||||
).toEqual(["Latest", "Old version"]);
|
||||
// Over the page, outside the card list that clips its overflow — and a
|
||||
// click inside it keeps it open.
|
||||
expect(box.parentElement).toBe(document.body);
|
||||
@@ -394,6 +409,65 @@ describe("Artifacts", () => {
|
||||
expect(calls[calls.length - 1]?.[0].title).toMatch(/Remove “hub-only” from the Hub/);
|
||||
});
|
||||
|
||||
it("Share again takes the server's copy, else uploads the picked folder onto that skill", async () => {
|
||||
vi.mocked(api.artifacts.uploadSkills).mockClear();
|
||||
vi.mocked(api.artifacts.settings).mockResolvedValue({
|
||||
serverMode: true,
|
||||
canShare: true,
|
||||
installsEnabled: true,
|
||||
canManage: true,
|
||||
});
|
||||
vi.mocked(api.artifacts.list).mockResolvedValue({
|
||||
items: [item({ id: 2, kind: "skill", title: "sg-flow", source: "sg-flow", shared: true })],
|
||||
});
|
||||
vi.mocked(api.artifacts.reshare).mockResolvedValueOnce({
|
||||
item: item({ id: 2 }),
|
||||
changed: true,
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
open();
|
||||
const card = await screen.findByTestId("artifact-2");
|
||||
await menuAction(user, "Share again", card);
|
||||
await waitFor(() => expect(api.artifacts.reshare).toHaveBeenCalledWith(2));
|
||||
expect(api.artifacts.uploadSkills).not.toHaveBeenCalled();
|
||||
|
||||
// No copy on the server: the folder is asked for and lands on THIS row.
|
||||
vi.mocked(api.artifacts.reshare).mockRejectedValueOnce(
|
||||
Object.assign(new Error("no copy"), { code: "ENOSOURCE" })
|
||||
);
|
||||
vi.mocked(confirmDialog).mockResolvedValueOnce(true);
|
||||
vi.mocked(api.artifacts.uploadSkills).mockResolvedValueOnce({
|
||||
items: [{ ...item({ id: 2 }), changed: true }],
|
||||
});
|
||||
await menuAction(user, "Share again", card);
|
||||
await waitFor(() => expect(confirmDialog).toHaveBeenCalled());
|
||||
const md = new File(["---\nname: sg-flow\n---\n"], "SKILL.md");
|
||||
await user.upload(screen.getByTestId("artifact-reshare-folder"), md);
|
||||
await waitFor(() =>
|
||||
expect(api.artifacts.uploadSkills).toHaveBeenCalledWith([{ file: md, path: "SKILL.md" }], {
|
||||
id: "2",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("says when a skill's content last changed, not when it was renamed", async () => {
|
||||
vi.mocked(api.artifacts.list).mockResolvedValue({
|
||||
items: [
|
||||
item({
|
||||
id: 2,
|
||||
kind: "skill",
|
||||
title: "deploy",
|
||||
source: "deploy",
|
||||
updatedAt: new Date().toISOString(),
|
||||
versionAt: new Date(Date.now() - 3 * 3600_000).toISOString(),
|
||||
}),
|
||||
],
|
||||
});
|
||||
open();
|
||||
const card = await screen.findByTestId("artifact-2");
|
||||
expect(within(card).getByText("Updated 3h ago")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers Update for an installed skill its owner changed, after a confirmation", async () => {
|
||||
vi.mocked(api.artifacts.list).mockResolvedValue({
|
||||
items: [
|
||||
|
||||
@@ -7316,7 +7316,7 @@ exports[`screen snapshots > Settings — about 1`] = `
|
||||
<span
|
||||
class="text-status-warning/90"
|
||||
>
|
||||
UI build v2.8.42 (rebuild client to match)
|
||||
UI build v2.8.50 (rebuild client to match)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+13
-6
@@ -817,6 +817,11 @@ that file.
|
||||
- Three caps guard the response: **300** files listed, **200 KB** of patch per
|
||||
file, **1 MB** of patch in a `full` read. A cap that bit sets `truncated` on
|
||||
the response and on the file it cut.
|
||||
- A row longer than **4,000** characters (an inlined base64 image or video, a
|
||||
minified bundle) comes back cut to its first 1,000 with `elided: <characters
|
||||
hidden>`, BEFORE the per-file cap is applied, so one huge line no longer eats
|
||||
the hunks after it. Each file's raw patch is read up to 16 M characters; past
|
||||
that it is still `truncated`.
|
||||
- Read-only, no same-origin guard. `available: false` (HTTP **200**) for a cwd
|
||||
git cannot read; `range=branch` compares against the workspace's base branch,
|
||||
else the repo's default branch (what `origin/HEAD` names, else `main`/`master`)
|
||||
@@ -1058,7 +1063,7 @@ cannot collide on `index.lock`.
|
||||
| `push` | `git push -u <remote> HEAD` — the branch's upstream remote, else the only remote, else `origin`, else `400 ENOREMOTE` | — |
|
||||
| `stage` | `git add -- <paths>` | `{"paths": ["..."]}` |
|
||||
| `unstage` | `git restore --staged -- <paths>` (a staged rename also passes its original path, so both halves unstage) | `{"paths": ["..."]}` |
|
||||
| `discard` | `git restore --source=HEAD --staged --worktree` (tracked) / `git clean -fd` (untracked) | `{"paths": ["..."], "confirm": true}` |
|
||||
| `discard` | `git restore --source=HEAD --staged --worktree` (tracked) / `git clean -fd` (untracked); with `hunks` (a partly ticked file's ticked change blocks, named as in `commit`), `git apply -R` of only those blocks off the working tree first — every patch built before any is applied, so a stale one is `409 EHUNKGONE` with nothing undone | `{"paths": ["..."], "confirm": true}` / `{"paths": [], "hunks": {"<path>": [{"hunk": "@@ … @@", "blocks": [0]}]}, "context": 3, "confirm": true}` |
|
||||
| `stage-hunk` | `git apply --cached` of ONE hunk of `git diff -U<context> HEAD -- <path>` — or, with `block`, of only that hunk's `block`-th run of +/- lines (the other runs folded into context, as an edited `git add -p` hunk) | `{"path": "...", "hunk": "@@ -1,2 +1,3 @@", "block": 0, "context": 3}` |
|
||||
| `discard-hunk` | `git apply -R` of that one hunk (or that one `block` of it), off the working tree | `{"path": "...", "hunk": "@@ ... @@", "block": 0, "context": 3, "confirm": true}` |
|
||||
| `commit` | `git add -A` then `git commit -m <message>`, or the index as it stands with `only: "staged"`, or — with `paths` — `git commit --only -- <paths>`: exactly those files' working-tree content (an untracked one is added first, and taken back out if the commit fails), every other change left as it was | `{"message": "...", "only": "staged"}` / `{"message": "...", "paths": ["..."]}` |
|
||||
@@ -1198,7 +1203,7 @@ GET /api/me/git { account: "member"|"host", writable, ssh: {
|
||||
POST /api/me/git/ssh-key Make an SSH key — Body: { replace?, type?: "ed25519" | "rsa", name? } — without `name` the DEFAULT key of that type (`id_ed25519`/`id_rsa`), with `name` (lowercase letters, digits, `-`, ≤ 32; 400 EBADKEYNAME) one more beside it, `id_<type>_<name>` — for another AWS account or a second GitHub user. 409 EEXISTS when that key exists without replace, or the name is taken by a key of the other type; 409 ETOOMANYKEYS past 10 keys → 201, same shape
|
||||
DELETE /api/me/git/ssh-key Delete one key — `?id=<key id>` (400 EBADKEYNAME for a malformed id), or the default key of `?type=ed25519|rsa` — or every key without either (404 ENOTFOUND, 400 EBADKEYTYPE). A login naming a deleted key goes back to every key; our terminal `core.sshCommand` follows the keys and goes with the last one
|
||||
PUT /api/me/git/ssh-terminal Use the keys for git typed in the account's own terminal — Body: { on } — sets/unsets `core.sshCommand` in its `~/.gitconfig` (every AgentHub key first, then `~/.ssh/id_*`; rewritten as keys are made or deleted while on); on by default when a member makes a key; 409 EFOREIGNSSH over one the user wrote, which is never touched
|
||||
PUT /api/me/git/ssh-user An SSH login — Body: { host, user, alias?, key? } — writes `url."ssh://<user>@<host>/".insteadOf "ssh://<from>/"` to the account's `~/.gitconfig`, `<from>` = `alias` or the host itself (replacing ours for that host/alias), so `ssh://<from>/…` logs in as `user` (AWS CodeCommit: the IAM SSH key ID `APKA…`). `alias` (lowercase letters, digits, `-`, NO dot — 400 EBADALIAS) is one more account on the same host: two AWS accounts clone as `ssh://aws-prod/v1/repos/x` and `ssh://aws-dev/v1/repos/x`. `key` (a key id, 400 ENOKEY) is stored as `agenthub.<from>.sshKey` there: a clone of a `ssh://<from>/…` URL then offers ONLY that key (`IdentitiesOnly`) and persists it into the clone's config; without it every key is offered. 400 EBADHOST / EBADSSHUSER
|
||||
PUT /api/me/git/ssh-user An SSH login — Body: { host, user, alias?, key? } — writes `url."ssh://<user>@<host>/".insteadOf "ssh://<from>/"` to the account's `~/.gitconfig`, `<from>` = `alias` or the host itself (replacing ours for that host/alias), so `ssh://<from>/…` logs in as `user` (AWS CodeCommit: the IAM SSH key ID `APKA…`). `alias` (lowercase letters, digits, `-`, NO dot — 400 EBADALIAS) is one more account on the same host: two AWS accounts clone as `ssh://aws-prod/v1/repos/x` and `ssh://aws-dev/v1/repos/x`. `key` (a key id, 400 ENOKEY) is stored as `agenthub.<from>.sshKey` there: a clone of a `ssh://<from>/…` URL then offers ONLY that key (`IdentitiesOnly`) and persists it into the clone's config; without it every key is offered. An IAM SSH key ID logs in to every region of its AWS account, so a Clone of `ssh://git-codecommit.<region>.amazonaws.com/…` whose region has no login of its own borrows the ones saved for other CodeCommit regions (each with its own key): the first the remote accepts (`git ls-remote`), or the only one, and the clone's `origin` then names that user. 400 EBADHOST / EBADSSHUSER
|
||||
DELETE /api/me/git/ssh-user/:from Drop the rule of that host or alias and its key link (404 ENOTFOUND); any other `insteadOf` the user wrote is never touched
|
||||
POST /api/me/git/https Save an https login — Body: { host, username, password }
|
||||
DELETE /api/me/git/https/:host Delete one (404 ENOTFOUND)
|
||||
@@ -3142,7 +3147,7 @@ A snapshot freezes a session as it is at that moment into one immutable `session
|
||||
### Artifacts hub
|
||||
|
||||
```http
|
||||
GET /api/artifacts?scope=all|mine|hub|unowned&kind=page|file|skill|plugin&q= {items} — each with `installed` and `updateAvailable` (default scope `all`)
|
||||
GET /api/artifacts?scope=all|mine|hub|unowned&kind=page|file|skill|plugin&q= {items} — each with `installed`, `updateAvailable` and `versionAt` (when its content last changed — a new snapshot; a rename or share toggle moves only `updatedAt`) (default scope `all`)
|
||||
GET /api/artifacts/settings {serverMode, canShare, installsEnabled, canManage}
|
||||
PUT /api/artifacts/settings {installsEnabled: boolean} — admin (any caller in local mode); the UI is Settings → AI tools → Artifacts Hub
|
||||
GET /api/artifacts/candidates?laneId= {items: [{path, sessionId, at, exists, pinned}]}
|
||||
@@ -3151,7 +3156,7 @@ POST /api/artifacts/page {url, title?, description?}
|
||||
POST /api/artifacts/file {laneId, path, title?, sessionId?}
|
||||
POST /api/artifacts/file/upload multipart: files (one), title?, description? → {item}
|
||||
POST /api/artifacts/skill {name, laneId?, title?, description?}
|
||||
POST /api/artifacts/skill/upload multipart: files, paths (JSON, each file's relative path), name?, title?, description? → {items}
|
||||
POST /api/artifacts/skill/upload multipart: files, paths (JSON, each file's relative path), name?, title?, description?, id? → {items} — a skill named like one the caller already has becomes its new version (`replaced`, `changed`); `id` = Share again onto that row
|
||||
POST /api/artifacts/skill/new {name, description, content, title?} → {item, items}
|
||||
POST /api/artifacts/plugin/inspect {market} → {market, name, description, plugins: [{name, key, description, version, category}]}
|
||||
POST /api/artifacts/plugin {key: "name@marketplace", market: "owner/repo" | git URL | marketplace.json URL, title?, description?}
|
||||
@@ -3161,7 +3166,8 @@ DELETE /api/artifacts/:id {ok, kept} — kept: a shared row
|
||||
GET /api/artifacts/:id/raw?path=&download=1 one snapshot file (sandbox CSP, nosniff)
|
||||
POST /api/artifacts/:id/install {replace?, update?} → {installed, replaced?}
|
||||
POST /api/artifacts/:id/uninstall → {uninstalled, paths}
|
||||
GET /api/artifacts/:id/installs {items: [{user, mine, at, replaced, paths?}], unrecorded}
|
||||
POST /api/artifacts/:id/reshare → {item, changed} — Share again (skill, owner): the owner's folder on this server becomes the new version and the row is shared; 409 ENOSOURCE when the server has no copy
|
||||
GET /api/artifacts/:id/installs {items: [{user, mine, at, replaced, state?, paths?}], unrecorded} — state (skills): latest | outdated | removed | unknown, that install's Claude skill copies against the newest version now
|
||||
POST /api/artifacts/:id/claim → {item} — the suggested user, or an admin
|
||||
POST /api/artifacts/:id/decline → {id, declined} — the suggested user
|
||||
POST /api/artifacts/:id/assign {userId} → {item} — admin
|
||||
@@ -3170,8 +3176,9 @@ POST /api/artifacts/:id/assign {userId} → {item} — admin
|
||||
What agents produced, per OWNER (`server/lib/artifacts.js`, plan: `docs/plans/artifacts/README.md`):
|
||||
|
||||
- **page** — a claude.ai link (`https://claude.ai/…` only, `400 EBADURL`), one row per owner and link. A session's `Artifact` tool publish — or a Claude Docs `batch` that creates a doc (`container.create`; its title is the doc's name, later batches are skipped) — is captured from its PostToolUse hook (a doc's own `frame.artifactUrl`; for a publish the first `https://claude.ai/…artifact/…` in `tool_response`), owned by the session's workspace owner — or, for a session no workspace owns (a member's `claude` started from their own terminal under S3), by the member whose account sent the hook (by its connection's uid, never the body); the host account names nobody, so such a page from the host stays unowned, with `suggested_owner_id` set to the owner of the workspace whose folder holds the session's `cwd` (else, under S3, the member whose home it is).
|
||||
- **file** — `candidates` are the documents (html, md, pdf, images, csv, office…) the workspace's sessions wrote with Write/Edit/MultiEdit/NotebookEdit, inside its folder. **Captured at Stop:** when a session a workspace owns sends `Stop` or `SessionEnd`, each `.pptx`/`.docx`/`.xlsx`/`.pdf`/`.html` in the workspace it created or changed since it started (a repo's untracked or modified files — an HTML file only when untracked — or a plain folder's files; at most 20 per stop, ≤ 25 MB) is snapshotted into the workspace owner's library as `auto: true` (shown **Auto**), off the hook's response path. The same file at the mtime its snapshot recorded is skipped; a changed one replaces that row's snapshot; a file pinned by hand is left alone. A pin is read under the download route's guards (`lanePath`, `resolveInLane`, `ESECRET`, ≤ 25 MB, `413 ETOOBIG`) and SNAPSHOTTED to `<data dir>/artifacts/<random>/`.
|
||||
- **file** — `candidates` are the documents (html, md, pdf, images, csv, office…) the workspace's sessions wrote with Write/Edit/MultiEdit/NotebookEdit, inside its folder. **Captured at Stop:** when a session a workspace owns sends `Stop` or `SessionEnd`, each `.pptx`/`.docx`/`.xlsx`/`.pdf`/`.html` in the workspace it created or changed since it started (a repo's untracked or modified files — an HTML file only when untracked and not a web app's own page: never an `index.html`, one under `www`/`public`/`dist`/`build`/`src`/`static`/`templates`/`assets`/`site`/`_site`, or one beside `.js`/`.css`-type files in a folder other than the workspace root — or a plain folder's files; at most 20 per stop, ≤ 25 MB) is snapshotted into the workspace owner's library as `auto: true` (shown **Auto**), off the hook's response path. The same file at the mtime its snapshot recorded is skipped; a changed one replaces that row's snapshot; a file pinned by hand is left alone. A pin is read under the download route's guards (`lanePath`, `resolveInLane`, `ESECRET`, ≤ 25 MB, `413 ETOOBIG`) and SNAPSHOTTED to `<data dir>/artifacts/<random>/`.
|
||||
- **skill** — the caller's own `~/.claude/skills/<name>` (their member home under S3; the host's for an admin or in local mode, else `409 ENOACCOUNT`) or a workspace's `.claude/skills/<name>`. Snapshotted whole: ≤ 300 files, ≤ 5 MB, a symlink anywhere is `ESYMLINK`, a secret-looking file name (`.env`, `*.pem`, `id_rsa`, `.netrc`…, or a data file named `*token*`/`*secret*`/`*password*`/`*credential*` — the word alone does not count in Markdown, source code or images, e.g. `design-tokens.md`) `403 ESECRET`.
|
||||
- **Share again** (a skill's ⋯ menu and detail sheet, its owner, server mode) — `reshare` takes the owner's skill folder on THIS server as the new snapshot: the row's source folder, else the same-named `skills/<name>` of a plugin the owner installed at user scope (`installed_plugins.json`, the most recently updated one, never outside their `~/.claude/plugins/`), and shares the row; installers are then offered **Update**. With no copy on the server (a skill uploaded from a browser) it answers `409 ENOSOURCE` and the page asks for the skill's folder, uploaded with `id` onto that row. An upload whose skill is named like one the uploader already has (not a workspace's) also replaces that row's version rather than adding a twin.
|
||||
- **file upload** — one file from the user's computer (≤ 25 MB, `413 ETOOBIG`), snapshotted under its own base name (no folder kept).
|
||||
- **skill upload / new** — a skill made from files rather than picked: one Markdown/text file of any name becomes `SKILL.md`; several files or a picked/dropped folder (`paths` keeps the layout) need a `SKILL.md` (at the top or in one folder, which is stripped — `400 ENOSKILLMD` otherwise); a single `.zip`/`.skill` is unpacked (sizes checked from its directory first, a symlink entry `ESYMLINK`, `__MACOSX`/`.DS_Store`/`.git`/`node_modules` skipped); an upload holding several skill folders makes one artifact per skill, named by its folder, and stores NOTHING if any of them fails. The `name` the user typed (only for a single skill; else the frontmatter `name:`, the folder or the file name) is made a folder name (`skillSlug`: marks dropped, other characters → `-`; `400 EBADNAME` if nothing is left) and written into `SKILL.md`'s frontmatter as `name:`; a `description` given replaces the frontmatter's, and a skill with none anywhere is `400 ENODESCRIPTION`. Paths are relative with no `..` (`EBADPATH`); the same limits and `ESECRET` as a picked skill. `new` writes `SKILL.md` from `content` the same way.
|
||||
- **plugin** — only the spec and its marketplace source (`EBADPLUGIN`, `EBADMARKET`: `owner/repo`, a `validateRemoteUrl` URL, or an https link to a `marketplace.json`); no files. A GitHub web link becomes `owner/repo`, and a forge's `…/src/…`, `…/tree/…`, `…/blob/…` suffix or trailing slash is trimmed. The same `key` added again by its owner updates that row. **inspect** reads the marketplace's `.claude-plugin/marketplace.json` to list its plugins: a git link is cloned shallow, blob-less and without checkout into a temp dir that is removed after, with every credential helper switched off and no prompt (a repository that needs a login is `502 ENEEDLOGIN`; type the key by hand — installing then uses each user's own git login), https only (an ssh link is `400 ESSHMARKET`); a repo with only a `plugin.json` is `400 ENOTMARKET`; unreachable `502 EMARKETFETCH`. It reaches any https host a signed-in user names, like `publish` does — no login is ever sent with it.
|
||||
|
||||
@@ -1629,6 +1629,8 @@ curl -X POST http://localhost:4820/api/lanes/5/remove \
|
||||
|
||||
**Actions gated behind confirmation:** `remove` requires the `confirm` flag to prevent accidentally dropping a workspace's record. It deletes that record only — never the worktree, the branch or the database.
|
||||
|
||||
**A workspace whose folder was deleted** (from Files, or a shell) is not removed for you — its record still holds its sessions' history. Every workspace payload carries `folder_missing` (true only when its `cwd` is gone — `ENOENT`/`ENOTDIR`, never a folder the server merely cannot read): the Files page leaves such a workspace out of its places, and the Workspace sidebar shows its name struck through with a hint to remove it from its ⋯ menu.
|
||||
|
||||
## Proof gallery
|
||||
|
||||
A workspace's proof gallery is a collection of QC screenshots captured during active work, grouped by feature (the same slug from **Per-feature state and archive** above) and phase (e.g. desktop, mobile, e2e, visual). A QC agent running an MCP server like `playwright-mcp` captures screenshots to disk at `<lane.cwd>/.playwright-mcp/proof/<slug>/<phase-group>/` and generates an optional ticket report at `<slug>/ticket/REPORT.html`. The Workspace gallery panel displays these files grouped by feature, using the same feature picker as the per-feature state section.
|
||||
|
||||
+5
-1
@@ -555,6 +555,10 @@ agenthub accounts pin team-key mia --tool codex # pins work as for Claude
|
||||
is used only for a pane that runs as its developer (one Linux user per
|
||||
account): AgentHub writes the account's `auth.json` into that developer's
|
||||
`~/.codex` as them (0600) just before the pane starts.
|
||||
- The pane runs `codex --no-daemon` (when that Codex lists the flag in
|
||||
`--help`): Codex ≥ 0.164 otherwise hands a plain session to the home's
|
||||
shared app-server daemon, which outlives every pane and keeps the login
|
||||
it started with — the new `auth.json` would not be used.
|
||||
- A host pane never gets one: its `CODEX_HOME` holds the host's own login.
|
||||
- A developer who signed Codex in themselves keeps their own login.
|
||||
- While a pane of theirs runs on a pool account, their next pane uses the
|
||||
@@ -882,7 +886,7 @@ What runs as the member, and how:
|
||||
- In a member's folder, git and `gh` run as `sudo -n -u ah-<name> git …`, so git's own ownership check passes and every file stays the member's.
|
||||
- The editor and `.gitignore` saves go through `/opt/agenthub/libexec/write-as`.
|
||||
- A file uploaded in the Files tab (`POST /api/lanes/:id/git/upload`) is written the same way, AS the member through `write-as` (content on stdin), and only as a NEW file in an existing folder of the workspace — never over an existing name, never into `.git`, never a home dot folder, at most 25 MB. With **Download** on a file (`GET /api/lanes/:id/git/download`, read like any member file below, up to 512 MB) this is how a member with no SSH or `scp` to the host moves files in and out of their own folder; both work in a folder that is not a git repo.
|
||||
- AgentHub's stored git logins are never handed to a member's git, and a password typed in the git bar goes into the member's OWN store (below) for that one call — through `write-as`'s stdin, never sudo's argv or env — and out again unless "remember" was ticked; a store that cannot be read is never rewritten (`409 ESTOREUNREADABLE`). The member keeps their OWN identity in Settings → Git → **Your git identity** (`/api/me/git`): a commit author (`user.name`/`user.email` in their `~/.gitconfig` — commits fail without one; a new member has none), SSH keys AgentHub makes for them (an ED25519 and/or an RSA one — AWS CodeCommit takes only RSA) and HTTPS logins, both under `~/.config/agenthub/` in their home, written as them by `write-as` (0600). Add workspace → **Clone** (`POST /api/lanes/clone`) clones as them with it and writes it into the clone's own config (`core.sshCommand` / `credential.helper=store --file=…`), so the git bar and their agents' pushes in that repo use it too. A plain `git` they type themselves in a pane reads none of that, so making the key also sets `core.sshCommand` in their `~/.gitconfig` (the key first, then `~/.ssh/id_*`; a switch under the key, issue #82) — unless they already set their own, which is left alone. The SSH keys are shown one TAB per kind of host, each with only its own steps: **GitHub · GitLab** (ED25519, for Gitea and Bitbucket too) and **AWS CodeCommit** (RSA: copy → upload in IAM → paste the SSH key ID `APKA…` and pick the region), then **Other hosts** (advanced); a tab's **Add another key** makes one more key of that kind at once (named `aws-2`, `aws-3`… / `git-2`…) as its own card below, with the same steps (an AWS one's step 3 saves its key ID under the key's name, tied to that key — clone `ssh://<name>/v1/repos/<repo>`; a GitHub one's ties the key to its host — clone `ssh://<name>/<org>/<repo>.git`); it opens on the AWS tab when only an RSA key exists. The terminal switch sits under the tabs. The key ID (or another host's user) is saved as `url."ssh://<user>@<host>/".insteadOf "ssh://<host>/"` in the same `~/.gitconfig`, so the plain `git clone ssh://git-codecommit.<region>.amazonaws.com/v1/repos/<repo>` works in a pane and in Clone. A login typed in the Clone dialog goes to their store through `write-as`'s stdin, never sudo's argv or env, and is removed again after the clone unless "remember" was ticked.
|
||||
- AgentHub's stored git logins are never handed to a member's git, and a password typed in the git bar goes into the member's OWN store (below) for that one call — through `write-as`'s stdin, never sudo's argv or env — and out again unless "remember" was ticked; a store that cannot be read is never rewritten (`409 ESTOREUNREADABLE`). The member keeps their OWN identity in Settings → Git → **Your git identity** (`/api/me/git`): a commit author (`user.name`/`user.email` in their `~/.gitconfig` — commits fail without one; a new member has none), SSH keys AgentHub makes for them (an ED25519 and/or an RSA one — AWS CodeCommit takes only RSA) and HTTPS logins, both under `~/.config/agenthub/` in their home, written as them by `write-as` (0600). Add workspace → **Clone** (`POST /api/lanes/clone`) clones as them with it and writes it into the clone's own config (`core.sshCommand` / `credential.helper=store --file=…`), so the git bar and their agents' pushes in that repo use it too. A plain `git` they type themselves in a pane reads none of that, so making the key also sets `core.sshCommand` in their `~/.gitconfig` (the key first, then `~/.ssh/id_*`; a switch under the key, issue #82) — unless they already set their own, which is left alone. The SSH keys are shown one TAB per kind of host, each with only its own steps: **GitHub · GitLab** (ED25519, for Gitea and Bitbucket too) and **AWS CodeCommit** (RSA: copy → upload in IAM → paste the SSH key ID `APKA…` and pick the region), then **Other hosts** (advanced); a tab's **Add another key** makes one more key of that kind at once (named `aws-2`, `aws-3`… / `git-2`…) as its own card below, with the same steps (an AWS one's step 3 saves its key ID under the key's name, tied to that key — clone `ssh://<name>/v1/repos/<repo>`; a GitHub one's ties the key to its host — clone `ssh://<name>/<org>/<repo>.git`); it opens on the AWS tab when only an RSA key exists. The terminal switch sits under the tabs. The key ID (or another host's user) is saved as `url."ssh://<user>@<host>/".insteadOf "ssh://<host>/"` in the same `~/.gitconfig`, so the plain `git clone ssh://git-codecommit.<region>.amazonaws.com/v1/repos/<repo>` works in a pane and in Clone — and Clone also lends a region with no key ID of its own the key IDs saved for other regions (an IAM key ID works in every region of its AWS account), keeping the one that logs in in the clone's `origin`. A login typed in the Clone dialog goes to their store through `write-as`'s stdin, never sudo's argv or env, and is removed again after the clone unless "remember" was ticked.
|
||||
- **Files a pane reads.** These are written into `~/.agenthub/handoff/` AS the member (`write-as`). The dashboard never writes, changes or deletes anything in a member's home itself: the member could have swapped the name for a link. The files are:
|
||||
- the workspace prompt and its context files;
|
||||
- the AI Proxy settings: no key, only that pane's own token for the gateway;
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.42",
|
||||
"version": "2.8.50",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "agenthub",
|
||||
"version": "2.8.42",
|
||||
"version": "2.8.50",
|
||||
"hasInstallScript": true,
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "agenthub",
|
||||
"version": "2.8.42",
|
||||
"version": "2.8.50",
|
||||
"bin": {
|
||||
"agenthub": "bin/agenthub.js"
|
||||
},
|
||||
|
||||
@@ -665,6 +665,128 @@ describe("skills from files or written", () => {
|
||||
assert.equal(bad.body.error.code, "EBADNAME");
|
||||
});
|
||||
|
||||
it("updates the uploader's same-named skill instead of adding a twin", async () => {
|
||||
const md = (v) => `---\nname: sg-again\ndescription: version ${v}\n---\nBody ${v}.\n`;
|
||||
const first = await upload("/api/artifacts/skill/upload", [["sg-again/SKILL.md", md(1)]]);
|
||||
assert.equal(first.status, 201, JSON.stringify(first.body));
|
||||
const id = first.body.items[0].id;
|
||||
const again = await upload("/api/artifacts/skill/upload", [["sg-again/SKILL.md", md(2)]]);
|
||||
assert.equal(again.status, 201, JSON.stringify(again.body));
|
||||
assert.equal(again.body.items[0].id, id);
|
||||
assert.equal(again.body.items[0].replaced, true);
|
||||
assert.equal(again.body.items[0].changed, true);
|
||||
assert.equal(again.body.items[0].description, "version 2");
|
||||
assert.match(snapText(again.body.items[0]), /Body 2\./);
|
||||
const rows = db
|
||||
.prepare("SELECT COUNT(*) AS n FROM artifacts WHERE kind = 'skill' AND source = 'sg-again'")
|
||||
.get();
|
||||
assert.equal(rows.n, 1);
|
||||
const same = await upload("/api/artifacts/skill/upload", [["sg-again/SKILL.md", md(2)]]);
|
||||
assert.equal(same.body.items[0].changed, false);
|
||||
});
|
||||
|
||||
it("dates a skill by its content, and tells each install's copy from the newest", async () => {
|
||||
const md = (v) => `---\nname: sg-state\ndescription: d\n---\nState ${v}.\n`;
|
||||
const first = await upload("/api/artifacts/skill/upload", [["sg-state/SKILL.md", md(1)]]);
|
||||
const id = first.body.items[0].id;
|
||||
const at1 = first.body.items[0].versionAt;
|
||||
assert.ok(at1);
|
||||
const states = async () =>
|
||||
(await request("GET", `/api/artifacts/${id}/installs`)).body.items.map((i) => i.state);
|
||||
assert.equal((await request("POST", `/api/artifacts/${id}/install`, {})).status, 200);
|
||||
assert.deepEqual(await states(), ["latest"]);
|
||||
|
||||
// A rename is no new version; new content is.
|
||||
const renamed = await request("PATCH", `/api/artifacts/${id}`, { title: "State" });
|
||||
assert.equal(renamed.body.item.versionAt, at1);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
const next = await upload("/api/artifacts/skill/upload", [["sg-state/SKILL.md", md(2)]]);
|
||||
assert.ok(next.body.items[0].versionAt > at1);
|
||||
assert.deepEqual(await states(), ["outdated"]);
|
||||
|
||||
fs.rmSync(path.join(process.env.CLAUDE_HOME, "skills", "sg-state"), { recursive: true });
|
||||
assert.deepEqual(await states(), ["removed"]);
|
||||
});
|
||||
|
||||
it("Share again: an uploaded skill asks for its folder, which replaces that row", async () => {
|
||||
const md = (v) => `---\nname: sg-up\ndescription: d\n---\nUp ${v}.\n`;
|
||||
const first = await upload("/api/artifacts/skill/upload", [["sg-up/SKILL.md", md(1)]]);
|
||||
const id = first.body.items[0].id;
|
||||
const no = await request("POST", `/api/artifacts/${id}/reshare`);
|
||||
assert.equal(no.status, 409);
|
||||
assert.equal(no.body.error.code, "ENOSOURCE");
|
||||
// The folder picked again, under any folder name: onto THIS row.
|
||||
const r = await upload("/api/artifacts/skill/upload", [["renamed/SKILL.md", md(2)]], {
|
||||
id: String(id),
|
||||
});
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
assert.equal(r.body.items[0].id, id);
|
||||
assert.equal(r.body.items[0].source, "sg-up");
|
||||
assert.match(snapText(r.body.items[0]), /^---\nname: sg-up\n[\s\S]*Up 2\./);
|
||||
const two = await upload(
|
||||
"/api/artifacts/skill/upload",
|
||||
[
|
||||
["p/a/SKILL.md", "---\nname: a\ndescription: d\n---\n"],
|
||||
["p/b/SKILL.md", "---\nname: b\ndescription: d\n---\n"],
|
||||
],
|
||||
{ id: String(id) }
|
||||
);
|
||||
assert.equal(two.body.error.code, "EBADUPLOAD");
|
||||
});
|
||||
|
||||
it("Share again takes the owner's folder, else the skill of an installed plugin", async () => {
|
||||
const home = process.env.CLAUDE_HOME;
|
||||
// An uploaded skill whose name a user-scope plugin also ships.
|
||||
const first = await upload("/api/artifacts/skill/upload", [
|
||||
["sg-plug/SKILL.md", "---\nname: sg-plug\ndescription: d\n---\nOld.\n"],
|
||||
]);
|
||||
const id = first.body.items[0].id;
|
||||
const writePlugin = (ver, text) => {
|
||||
const at = path.join(home, "plugins", "cache", "m", "p", ver);
|
||||
fs.mkdirSync(path.join(at, "skills", "sg-plug"), { recursive: true });
|
||||
fs.writeFileSync(path.join(at, "skills", "sg-plug", "SKILL.md"), text);
|
||||
return at;
|
||||
};
|
||||
const v1 = writePlugin("1.0.0", "---\nname: sg-plug\ndescription: d\n---\nPlugin one.\n");
|
||||
const v2 = writePlugin("2.0.0", "---\nname: sg-plug\ndescription: d\n---\nPlugin two.\n");
|
||||
fs.writeFileSync(
|
||||
path.join(home, "plugins", "installed_plugins.json"),
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
plugins: {
|
||||
"p@m": [{ scope: "user", installPath: v2, lastUpdated: "2026-10-30T00:00:00Z" }],
|
||||
"old@m": [{ scope: "user", installPath: v1, lastUpdated: "2026-01-01T00:00:00Z" }],
|
||||
"proj@m": [
|
||||
{ scope: "project", installPath: "/etc", lastUpdated: "2027-01-01T00:00:00Z" },
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
const r = await request("POST", `/api/artifacts/${id}/reshare`);
|
||||
assert.equal(r.status, 200, r.text);
|
||||
assert.equal(r.body.changed, true);
|
||||
assert.match(snapText(r.body.item), /Plugin two\./);
|
||||
assert.equal((await request("POST", `/api/artifacts/${id}/reshare`)).body.changed, false);
|
||||
|
||||
// The owner's own ~/.claude/skills folder outranks a plugin's copy.
|
||||
const own = path.join(home, "skills", "sg-plug");
|
||||
fs.mkdirSync(own, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(own, "SKILL.md"),
|
||||
"---\nname: sg-plug\ndescription: d\n---\nMine.\n"
|
||||
);
|
||||
const mine = await request("POST", `/api/artifacts/${id}/reshare`);
|
||||
assert.equal(mine.body.changed, true);
|
||||
assert.match(snapText(mine.body.item), /Mine\./);
|
||||
// Recorded as the folder's state: the 15 s sync does not take it twice.
|
||||
assert.deepEqual(
|
||||
artifacts.syncSkillSources({ force: true }).filter((c) => c.id === id),
|
||||
[]
|
||||
);
|
||||
fs.rmSync(path.join(home, "plugins"), { recursive: true, force: true });
|
||||
fs.rmSync(own, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("keeps an uploaded file as a snapshot, by its own base name", async () => {
|
||||
const r = await upload("/api/artifacts/file/upload", [["report.html", "<h1>x</h1>"]], {
|
||||
title: "Report",
|
||||
@@ -859,6 +981,23 @@ describe("outputs captured at a session's stop", () => {
|
||||
);
|
||||
assert.deepEqual(await artifacts.captureOutputs("no-such-session"), []);
|
||||
});
|
||||
|
||||
it("leaves a web app's own pages alone and still takes a standalone HTML report", async () => {
|
||||
const put = (rel, text = "<p>x</p>") => {
|
||||
fs.mkdirSync(path.dirname(path.join(ws, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(ws, rel), text);
|
||||
const soon = new Date(Date.now() + 5 * 60 * 1000);
|
||||
fs.utimesSync(path.join(ws, rel), soon, soon);
|
||||
};
|
||||
put("app/index.html");
|
||||
put("app/www/page.html");
|
||||
put("widget/view.html");
|
||||
put("widget/view.js", "x()");
|
||||
put("summary-report.html");
|
||||
put("out/q3.html");
|
||||
const got = (await artifacts.captureOutputs("s1")).map((r) => r.source).sort();
|
||||
assert.deepEqual(got, ["out/q3.html", "summary-report.html"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unowned rows", () => {
|
||||
|
||||
@@ -243,6 +243,29 @@ describe("codex pool: spawn", () => {
|
||||
assert.equal(row.account, "c");
|
||||
});
|
||||
|
||||
it("runs a ChatGPT pane without the shared daemon, only when its Codex has the flag", () => {
|
||||
// The home's app-server daemon keeps the login it started with: a placed
|
||||
// login reaches only a pane that runs its own app server.
|
||||
const fakeCodex = (name, help) => {
|
||||
const file = path.join(TMP, name);
|
||||
fs.writeFileSync(file, `#!/bin/sh\necho '${help}'\n`, { mode: 0o755 });
|
||||
return file;
|
||||
};
|
||||
const prev = process.env.AGENTHUB_CODEX_BIN;
|
||||
try {
|
||||
pool.addAccount("c", { auth: AUTH("acct-c") });
|
||||
process.env.AGENTHUB_CODEX_BIN = fakeCodex("codex-new", " --no-daemon Run without");
|
||||
assert.deepEqual(pool.forSpawn(MIA).argv, ["--no-daemon"]);
|
||||
process.env.AGENTHUB_CODEX_BIN = fakeCodex("codex-old", " --oss Use a local model");
|
||||
assert.deepEqual(pool.forSpawn(MIA).argv, [], "an older Codex would refuse the flag");
|
||||
process.env.AGENTHUB_CODEX_BIN = path.join(TMP, "no-such-codex");
|
||||
assert.deepEqual(pool.forSpawn(MIA).argv, []);
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.AGENTHUB_CODEX_BIN;
|
||||
else process.env.AGENTHUB_CODEX_BIN = prev;
|
||||
}
|
||||
});
|
||||
|
||||
it("never replaces a member's own login, and stays on the account their live pane uses", () => {
|
||||
pool.addAccount("c", { auth: AUTH("acct-c") });
|
||||
pool.addAccount("d", { auth: AUTH("acct-d") });
|
||||
@@ -272,7 +295,10 @@ describe("codex pool: spawn", () => {
|
||||
fs.writeFileSync(MIA_AUTH, JSON.stringify(own));
|
||||
assert.equal(pool.pickAccount(MIA), null);
|
||||
pty.spawnRun({ laneId: 50, cwd: path.join(MIA.home, "p"), tool: "codex" });
|
||||
assert.equal(JSON.parse(fs.readFileSync(MIA_AUTH, "utf8")).tokens.refresh_token, "rt-mias-seat");
|
||||
assert.equal(
|
||||
JSON.parse(fs.readFileSync(MIA_AUTH, "utf8")).tokens.refresh_token,
|
||||
"rt-mias-seat"
|
||||
);
|
||||
});
|
||||
|
||||
it("copies the newest auth.json back into the pool", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* ECREDENTIALS for a remote wanting a login), `/api/me/git` (key made once,
|
||||
* only the public half returned, 0600 on disk; named keys beside the default
|
||||
* ones, SSH logins per alias tied to one key, which a clone then offers
|
||||
* alone), and the member (S3) path of
|
||||
* alone; a CodeCommit region with no login borrowing another region's), and the member (S3) path of
|
||||
* `server/lib/git-identity.js` with run-as and git stubbed — what reaches
|
||||
* git's argv, and that a login typed without "remember" leaves the member's
|
||||
* store as it was.
|
||||
@@ -650,6 +650,44 @@ describe("several accounts: named keys and SSH logins per alias", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CodeCommit: a region with no login borrows another region's", () => {
|
||||
it("clones as the first saved CodeCommit user the remote accepts, and keeps that user in origin", async () => {
|
||||
const bare = path.join(ROOT, "bare.git");
|
||||
const R = "git-codecommit.ap-southeast-2.amazonaws.com";
|
||||
const saved = [
|
||||
["git-codecommit.ap-southeast-1.amazonaws.com", "APKAONE"],
|
||||
["git-codecommit.us-east-1.amazonaws.com", "APKATWO"],
|
||||
];
|
||||
for (const [host, user] of saved) {
|
||||
assert.equal((await request("PUT", "/api/me/git/ssh-user", { host, user })).status, 200);
|
||||
}
|
||||
// The test forge stands in for the region: APKAONE is refused (no such
|
||||
// repo behind it), APKATWO is the account that owns the repo.
|
||||
const rules = [
|
||||
[`url.file://${ROOT}/nowhere.git.insteadOf`, `ssh://APKAONE@${R}/v1/repos/r`],
|
||||
[`url.file://${bare}.insteadOf`, `ssh://APKATWO@${R}/v1/repos/r`],
|
||||
];
|
||||
for (const [k, v] of rules) execFileSync("git", ["config", "--global", "--add", k, v]);
|
||||
try {
|
||||
const r = await request("POST", "/api/lanes/clone", {
|
||||
url: `ssh://${R}/v1/repos/r`,
|
||||
parent: WORK,
|
||||
name: "borrowed-login",
|
||||
});
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const origin = execFileSync(
|
||||
"git",
|
||||
["-C", path.join(WORK, "borrowed-login"), "config", "remote.origin.url"],
|
||||
{ encoding: "utf8" }
|
||||
).trim();
|
||||
assert.equal(origin, `ssh://APKATWO@${R}/v1/repos/r`);
|
||||
} finally {
|
||||
for (const [k] of rules) execFileSync("git", ["config", "--global", "--unset-all", k]);
|
||||
for (const [host] of saved) await request("DELETE", `/api/me/git/ssh-user/${host}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("git-identity, member account (S3, stubbed)", () => {
|
||||
const runAs = require("../lib/run-as");
|
||||
const worktree = require("../lib/worktree");
|
||||
|
||||
@@ -473,6 +473,55 @@ describe("reads larger than the git() buffer report truncated, not missing", ()
|
||||
});
|
||||
});
|
||||
|
||||
describe("a page with megabyte-long lines (inlined base64) keeps every hunk", () => {
|
||||
const blob = (c) => c.repeat(3 * 1024 * 1024); // one 3 MB line
|
||||
|
||||
it("cuts the long rows down and still shows the hunks after them", async () => {
|
||||
const body = (mid, end) =>
|
||||
[
|
||||
"<h1>title</h1>",
|
||||
...Array.from({ length: 40 }, (_, i) => `row ${i}`),
|
||||
mid,
|
||||
...Array.from({ length: 40 }, (_, i) => `tail ${i}`),
|
||||
end,
|
||||
"",
|
||||
].join("\n");
|
||||
write(LANE, "deck.html", body(`<video src="${blob("A")}">`, "<p>old end</p>"));
|
||||
g(LANE, "add", "-A");
|
||||
g(LANE, "commit", "-qm", "deck");
|
||||
write(
|
||||
LANE,
|
||||
"deck.html",
|
||||
body(`<video src="${blob("B")}">`, "<p>new end</p>").replace(
|
||||
"<h1>title</h1>",
|
||||
"<h1>new title</h1>"
|
||||
)
|
||||
);
|
||||
const out = await collectChanges(LANE, { range: "work", file: "deck.html" });
|
||||
const f = out.files[0];
|
||||
assert.equal(f.truncated, undefined);
|
||||
assert.equal(out.truncated, false);
|
||||
const lines = f.hunks.flatMap((h) => h.lines);
|
||||
const long = lines.filter((l) => l.elided);
|
||||
assert.equal(long.length, 2);
|
||||
for (const l of long) {
|
||||
assert.ok(l.text.length < 2000);
|
||||
assert.equal(l.text.length + l.elided, '<video src="'.length + 3 * 1024 * 1024 + 2);
|
||||
}
|
||||
// The change AFTER the 3 MB rows survives: the cap no longer eats it.
|
||||
assert.ok(lines.some((l) => l.type === "add" && l.text === "<p>new end</p>"));
|
||||
assert.ok(lines.some((l) => l.type === "add" && l.text === "<h1>new title</h1>"));
|
||||
});
|
||||
|
||||
it("leaves ordinary rows whole", async () => {
|
||||
write(LANE, "a.txt", "one\nTWO\n");
|
||||
const out = await collectChanges(LANE, { range: "work", file: "a.txt" });
|
||||
const lines = out.files[0].hunks.flatMap((h) => h.lines);
|
||||
assert.ok(lines.every((l) => l.elided === undefined));
|
||||
assert.ok(lines.some((l) => l.text === "TWO"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("loop 2: secret file at any depth, symlinked .claude", () => {
|
||||
const KEY = '{"env":{"ANTHROPIC_API_KEY":"sk-deep"}}';
|
||||
|
||||
|
||||
@@ -203,18 +203,21 @@ describe("collectChanges — work range", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("still returns content when a huge file has no newline to cut on", async () => {
|
||||
// A minified bundle is ONE line. Cutting the patch at the last newline
|
||||
// inside the cap would land at index -1 here and hand back an empty
|
||||
// patch — a file changed by a megabyte rendering as "no textual change".
|
||||
it("still returns content when a huge file is one line", async () => {
|
||||
// A minified bundle is ONE line. It used to be cut at the per-file cap
|
||||
// (and, cut at the last newline, could come back empty — a file changed
|
||||
// by a megabyte rendering as "no textual change"); now the row itself is
|
||||
// cut down and says how much it hides, and nothing is truncated.
|
||||
const { MAX_FILE_BYTES } = require("../lib/git-diff");
|
||||
write(LANE, "min.js", `${"x".repeat(MAX_FILE_BYTES + 5000)}\n`);
|
||||
const out = await collectChanges(LANE, { range: "work", file: "min.js" });
|
||||
const entry = out.files[0];
|
||||
assert.equal(entry.truncated, true);
|
||||
assert.equal(out.truncated, true);
|
||||
assert.ok(entry.hunks.length > 0, "a truncated patch still carries its hunk");
|
||||
assert.ok(entry.hunks[0].lines[0].text.startsWith("xxx"));
|
||||
assert.equal(entry.truncated, undefined);
|
||||
assert.equal(out.truncated, false);
|
||||
assert.ok(entry.hunks.length > 0, "the patch still carries its hunk");
|
||||
const row = entry.hunks[0].lines.find((l) => l.type === "add");
|
||||
assert.ok(row.text.startsWith("xxx"));
|
||||
assert.equal(row.text.length + row.elided, MAX_FILE_BYTES + 5000);
|
||||
});
|
||||
|
||||
it("reports a binary file without trying to diff it", async () => {
|
||||
@@ -848,6 +851,51 @@ describe("runGitAction — one change block inside a hunk (issue #50)", () => {
|
||||
assert.equal(fs.readFileSync(path.join(LANE, "tail.txt"), "utf8"), "l1\nl2\nl3\nl4\nl5\nl6");
|
||||
});
|
||||
|
||||
it("discards only the ticked blocks and whole files, nothing unticked (issue #87)", async () => {
|
||||
const edited = threeBlocks();
|
||||
write(LANE, "keep.txt", "untouched by discard\n");
|
||||
write(LANE, "drop.txt", "gone\n");
|
||||
const [hunk] = await hunkOf();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
runGitAction(LANE, "discard", {
|
||||
paths: ["drop.txt"],
|
||||
hunks: { "near.txt": [{ hunk: hunk.header, blocks: [0, 2] }] },
|
||||
}),
|
||||
{ code: "ECONFIRM" }
|
||||
);
|
||||
await runGitAction(LANE, "discard", {
|
||||
paths: ["drop.txt"],
|
||||
hunks: { "near.txt": [{ hunk: hunk.header, blocks: [0, 2] }] },
|
||||
confirm: true,
|
||||
});
|
||||
const want = [...edited];
|
||||
want.splice(11, 0, "line 11");
|
||||
want.splice(3, 2, "line 4", "line 5");
|
||||
assert.deepEqual(read(), [...want, ""]);
|
||||
assert.equal(fs.existsSync(path.join(LANE, "drop.txt")), false);
|
||||
assert.equal(fs.readFileSync(path.join(LANE, "keep.txt"), "utf8"), "untouched by discard\n");
|
||||
});
|
||||
|
||||
it("discards ticked blocks alone, and refuses a stale one with nothing undone", async () => {
|
||||
const edited = threeBlocks();
|
||||
const [hunk] = await hunkOf();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
runGitAction(LANE, "discard", {
|
||||
hunks: { "near.txt": [{ hunk: "@@ -1,2 +1,2 @@", blocks: [0] }] },
|
||||
confirm: true,
|
||||
}),
|
||||
{ code: "EHUNKGONE" }
|
||||
);
|
||||
assert.deepEqual(read(), [...edited, ""]);
|
||||
await runGitAction(LANE, "discard", {
|
||||
hunks: { "near.txt": [{ hunk: hunk.header, blocks: [1] }] },
|
||||
confirm: true,
|
||||
});
|
||||
assert.deepEqual(read(), [...edited.filter((l) => l !== "INSERTED"), ""]);
|
||||
});
|
||||
|
||||
it("refuses a block the hunk does not have", async () => {
|
||||
threeBlocks();
|
||||
const [hunk] = await hunkOf();
|
||||
|
||||
@@ -337,6 +337,16 @@ describe("lanes lib", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("payload says folder_missing only when the folder is gone", () => {
|
||||
const fs = require("node:fs");
|
||||
const dir = fs.mkdtempSync(pathMod.join(os.tmpdir(), "lane-gone-"));
|
||||
const l = lanes.createLane({ cwd: dir });
|
||||
assert.equal(lanes.lanePayload(lanes.getLane(l.id)).folder_missing, false);
|
||||
fs.rmSync(dir, { recursive: true });
|
||||
assert.equal(lanes.lanePayload(lanes.getLane(l.id)).folder_missing, true);
|
||||
lanes.deleteLane(l.id);
|
||||
});
|
||||
|
||||
it("payload carries node states and progress", () => {
|
||||
const l = lanes.createLane({ cwd: "/tmp/wt/d" });
|
||||
lanes.setStage(l.id, { stage: "review" });
|
||||
|
||||
@@ -973,11 +973,16 @@ for (const [col, ddl] of [
|
||||
["suggested_owner_id", "suggested_owner_id INTEGER"],
|
||||
["version", "version TEXT"],
|
||||
["source_hash", "source_hash TEXT"],
|
||||
["version_at", "version_at TEXT"],
|
||||
]) {
|
||||
try {
|
||||
db.prepare(`SELECT ${col} FROM artifacts LIMIT 1`).get();
|
||||
} catch {
|
||||
db.prepare(`ALTER TABLE artifacts ADD COLUMN ${ddl}`).run();
|
||||
// `version_at`: when a row's CONTENT last changed (a new snapshot) — a
|
||||
// rename or a share toggle moves `updated_at` but not this. An existing
|
||||
// row starts from its `updated_at`, the best record there is.
|
||||
if (col === "version_at") db.prepare("UPDATE artifacts SET version_at = updated_at").run();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+222
-16
@@ -173,6 +173,8 @@ function view(row, req, owners = null) {
|
||||
suggestedForMe: !!req?.user && row.owner_id == null && row.suggested_owner_id === req.user.id,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
// When its content last changed (a new snapshot): a page or plugin never does.
|
||||
versionAt: row.version_at || row.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -549,13 +551,38 @@ async function pinFile(req, { laneId, path: rel, title, description, sessionId }
|
||||
const OUTPUT_EXT = /\.(pptx|docx|xlsx|pdf|html?)$/i;
|
||||
/** Most files one stop captures, so a script that writes hundreds stays bounded. */
|
||||
const OUTPUT_MAX = 20;
|
||||
/** Folders that hold a site's own pages, never a report someone reads. */
|
||||
const SITE_DIR_RE = /^(www|public|dist|build|src|static|templates|assets|site|_site)$/i;
|
||||
/** What sits next to a site's page: its scripts and styles. */
|
||||
const SITE_ASSET_RE = /\.(m?js|jsx|tsx?|vue|svelte|css|s[ac]ss|less)$/i;
|
||||
|
||||
/**
|
||||
* An HTML file that is a web app's own page, not a report (`app/www/index.html`
|
||||
* of a project not yet committed): an `index.html`, one under a site folder
|
||||
* (`SITE_DIR_RE`), or one beside scripts or stylesheets in its folder. The
|
||||
* workspace root is exempt from that last test — a repo keeps its config
|
||||
* `.js` there next to the reports people write.
|
||||
*/
|
||||
async function isSitePage(cwd, rel) {
|
||||
const parts = rel.split("/");
|
||||
const name = parts.pop();
|
||||
if (/^index\.html?$/i.test(name)) return true;
|
||||
if (parts.some((d) => SITE_DIR_RE.test(d))) return true;
|
||||
if (!parts.length) return false;
|
||||
try {
|
||||
const names = await fs.promises.readdir(path.join(cwd, ...parts));
|
||||
return names.some((n) => SITE_ASSET_RE.test(n));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const capturing = new Map();
|
||||
|
||||
/**
|
||||
* The workspace's documents a session created or changed since it started:
|
||||
* untracked or modified files in a repo (an HTML file only when untracked, so a
|
||||
* site's own pages are not taken), every file of a plain folder. Paths are
|
||||
* workspace-relative.
|
||||
* untracked or modified files in a repo (an HTML file only when untracked and
|
||||
* not a site's own page — `isSitePage`), every file of a plain folder. Paths
|
||||
* are workspace-relative.
|
||||
*/
|
||||
async function outputCandidates(lane, since) {
|
||||
const gd = require("./git-diff");
|
||||
@@ -572,7 +599,7 @@ async function outputCandidates(lane, since) {
|
||||
const out = [];
|
||||
for (const rel of new Set(paths)) {
|
||||
if (!OUTPUT_EXT.test(rel)) continue;
|
||||
if (/\.html?$/i.test(rel) && tracked.has(rel)) continue;
|
||||
if (/\.html?$/i.test(rel) && (tracked.has(rel) || (await isSitePage(lane.cwd, rel)))) continue;
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(path.join(lane.cwd, rel));
|
||||
@@ -627,7 +654,7 @@ async function captureOutputsNow(laneId, sessionId) {
|
||||
const files = JSON.stringify([{ path: shot.name, size: shot.size, mtime: mtimeMs }]);
|
||||
if (row) {
|
||||
sql(
|
||||
"UPDATE artifacts SET snapshot = ?, files = ?, size = ?, session_id = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?"
|
||||
"UPDATE artifacts SET snapshot = ?, files = ?, size = ?, session_id = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), version_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?"
|
||||
).run(shot.snap.id, files, shot.size, String(sessionId), row.id);
|
||||
dropSnapshot(row.snapshot);
|
||||
done.push(sql("SELECT * FROM artifacts WHERE id = ?").get(row.id));
|
||||
@@ -1125,8 +1152,20 @@ function saveSkillFiles(req, { name, files, title, description }) {
|
||||
* `paths`). Answers every skill it made. Nothing is stored unless every
|
||||
* skill in the upload passes.
|
||||
*/
|
||||
function uploadSkills(req, { uploads, name, title, description }) {
|
||||
function uploadSkills(req, { uploads, name, title, description, id }) {
|
||||
// `id`: Share again for a skill the server has no copy of — the upload
|
||||
// replaces THAT row (one skill, named as the row is).
|
||||
let onto = null;
|
||||
if (id != null && id !== "") {
|
||||
onto = load(req, id);
|
||||
if (!canChange(req, onto)) throw fail("EFORBIDDEN", "only its owner changes an artifact");
|
||||
if (onto.kind !== "skill") throw fail("EBADKIND", "only a skill is shared again");
|
||||
name = onto.source;
|
||||
}
|
||||
const found = skillsFromUpload(uploads || [], { name, description });
|
||||
if (onto && found.length !== 1) {
|
||||
throw fail("EBADUPLOAD", "choose the folder or .zip of this one skill");
|
||||
}
|
||||
const typed = typeof name === "string" && name.trim();
|
||||
const prepared = found.map((sk) => ({
|
||||
name: validSkillName(found.length === 1 && typed ? typed : sk.fallbackName || ""),
|
||||
@@ -1140,16 +1179,46 @@ function uploadSkills(req, { uploads, name, title, description }) {
|
||||
withFrontmatter(md.data.toString("utf8"), p.name, found.length === 1 ? description : "");
|
||||
checkSkillFiles(p.files);
|
||||
}
|
||||
return prepared.map((p) =>
|
||||
saveSkillFiles(req, {
|
||||
return prepared.map((p) => {
|
||||
// A skill its uploader already has (same name, not a workspace's) gets
|
||||
// the new version on that row — installers see Update — never a twin.
|
||||
const own = onto || ownSkillRow(req, p.name);
|
||||
if (own) return replaceUploaded(req, own, p, found.length === 1 ? description : "");
|
||||
return saveSkillFiles(req, {
|
||||
name: p.name,
|
||||
files: p.files,
|
||||
title: found.length === 1 ? title : "",
|
||||
description: found.length === 1 ? description : "",
|
||||
})
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** The caller's newest skill row of that name taken from no workspace, or null. */
|
||||
function ownSkillRow(req, name) {
|
||||
const owner = req?.user ? req.user.id : null;
|
||||
return (
|
||||
sql(
|
||||
`SELECT * FROM artifacts WHERE kind = 'skill' AND source = ? AND lane_id IS NULL
|
||||
AND snapshot IS NOT NULL AND owner_id IS ? ORDER BY updated_at DESC, id DESC LIMIT 1`
|
||||
).get(name, owner) || null
|
||||
);
|
||||
}
|
||||
|
||||
/** An uploaded skill onto an existing row: same frontmatter rules as a new one. */
|
||||
function replaceUploaded(req, row, { name, files }, description) {
|
||||
const md = files.find((f) => f.path === "SKILL.md");
|
||||
const text = md.data.toString("utf8");
|
||||
if (text.includes("\uFFFD")) throw fail("EBADSKILL", "SKILL.md is not a UTF-8 text file");
|
||||
const fixed = Buffer.from(withFrontmatter(text, name, description), "utf8");
|
||||
const all = [{ path: "SKILL.md", data: fixed }, ...files.filter((f) => f !== md)];
|
||||
checkSkillFiles(all);
|
||||
const changed = contentHash(all) !== snapshotVersion(row);
|
||||
// The owner's folder as it is now (like `storeSkill`): only a LATER change
|
||||
// to it replaces this upload.
|
||||
if (changed) replaceSnapshot(row, all, sourceHash(row) ?? row.source_hash);
|
||||
return { ...shareNow(req, row.id, changed), replaced: true, changed };
|
||||
}
|
||||
|
||||
/** A skill written in the dialog: a name, a description and its instructions. */
|
||||
function writeSkill(req, { name, description, content, title }) {
|
||||
const n = validSkillName(name);
|
||||
@@ -1599,7 +1668,8 @@ function editSkill(req, row, { name, description, content }) {
|
||||
sql(
|
||||
`UPDATE artifacts SET source = ?, snapshot = ?, files = ?, size = ?, description = ?,
|
||||
version = ?, source_hash = ?,
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?`
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'),
|
||||
version_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?`
|
||||
).run(
|
||||
n,
|
||||
snap.id,
|
||||
@@ -1936,6 +2006,23 @@ function syncOne(row) {
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
replaceSnapshot(row, files, st.hash);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Point a skill row at a NEW snapshot holding `files` (`[{path, data}]`, already
|
||||
* checked), then drop the old one — never a write into the snapshot being
|
||||
* read. Installers then see Update (`updateCheck`). `sourceHash` is the
|
||||
* source folder's state to record, so `syncOne` takes only a LATER change.
|
||||
* The description follows SKILL.md's only while it still says what the old
|
||||
* one did.
|
||||
*/
|
||||
function replaceSnapshot(row, files, sourceHash) {
|
||||
const snap = newSnapshotDir();
|
||||
let total = 0;
|
||||
const next = [];
|
||||
@@ -1947,11 +2034,10 @@ function syncOne(row) {
|
||||
total += f.data.length;
|
||||
next.push({ path: f.path, size: f.data.length });
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
dropSnapshot(snap.id);
|
||||
return false;
|
||||
throw err;
|
||||
}
|
||||
// The description follows SKILL.md's only while it still says what the old one did.
|
||||
const md = (list) => list.find((f) => f.path === "SKILL.md");
|
||||
let oldSummary = "";
|
||||
try {
|
||||
@@ -1969,10 +2055,98 @@ function syncOne(row) {
|
||||
: row.description;
|
||||
sql(
|
||||
`UPDATE artifacts SET snapshot = ?, files = ?, size = ?, version = ?, source_hash = ?,
|
||||
description = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?`
|
||||
).run(snap.id, JSON.stringify(next), total, st.hash, st.hash, description, row.id);
|
||||
description = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'),
|
||||
version_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?`
|
||||
).run(
|
||||
snap.id,
|
||||
JSON.stringify(next),
|
||||
total,
|
||||
contentHash(files),
|
||||
sourceHash ?? null,
|
||||
description,
|
||||
row.id
|
||||
);
|
||||
if (row.snapshot && SNAPSHOT_RE.test(row.snapshot)) dropSnapshot(row.snapshot);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner's skill folder on THIS server as it is now, for Share again:
|
||||
* the row's own source folder (`sourceDirOf`), else — a skill not taken from
|
||||
* a workspace — the same-named skill of a plugin the owner installed at user
|
||||
* scope (`installed_plugins.json`; the most recently updated when several
|
||||
* have it), never outside the owner's `~/.claude/plugins/`. Answers
|
||||
* `{st, fromSource}` (`folderState`) or null when the server has no copy (an
|
||||
* uploaded skill: its owner picks the folder again).
|
||||
*/
|
||||
function machineSkill(row) {
|
||||
const src = sourceDirOf(row);
|
||||
const st = src && folderState(src.dir, src.top);
|
||||
if (st) return { st, fromSource: true };
|
||||
if (!src || row.lane_id != null) return null;
|
||||
const top = path.join(src.top, "plugins");
|
||||
let installed = {};
|
||||
try {
|
||||
const user = sql("SELECT id, username, role FROM users WHERE id = ?").get(row.owner_id);
|
||||
const file = path.join(top, "installed_plugins.json");
|
||||
const text =
|
||||
user && ownAccount({ user }).acct
|
||||
? require("./run-as").readFileSafe(file, "utf8", { max: 4 << 20 })
|
||||
: fs.readFileSync(file, "utf8");
|
||||
installed = JSON.parse(text)?.plugins || {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let best = null;
|
||||
for (const entries of Object.values(installed)) {
|
||||
for (const e of Array.isArray(entries) ? entries : []) {
|
||||
if (!e || e.scope !== "user" || typeof e.installPath !== "string") continue;
|
||||
const st2 = folderState(path.join(e.installPath, "skills", row.source), top);
|
||||
const at = Date.parse(e.lastUpdated || e.installedAt || "") || 0;
|
||||
if (st2 && (!best || at > best.at)) best = { st: st2, at };
|
||||
}
|
||||
}
|
||||
return best ? { st: best.st, fromSource: false } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Share again: take the owner's skill folder on this server as the row's new
|
||||
* snapshot (`machineSkill`) and share it (server mode), so installers are
|
||||
* offered Update. ENOSOURCE when the server has no copy — the client then
|
||||
* asks for the folder or .zip and uploads it onto this row (`uploadSkills`
|
||||
* with `id`). Answers `{item, changed}`.
|
||||
*/
|
||||
function reshareSkill(req, id) {
|
||||
const row = load(req, id);
|
||||
if (!canChange(req, row)) throw fail("EFORBIDDEN", "only its owner changes an artifact");
|
||||
if (row.kind !== "skill") throw fail("EBADKIND", "only a skill is shared again");
|
||||
const found = machineSkill(row);
|
||||
if (!found) {
|
||||
throw fail("ENOSOURCE", "this server has no copy of the skill: choose its folder or .zip");
|
||||
}
|
||||
const files = found.st.read();
|
||||
checkSkillFiles(files);
|
||||
const changed = found.st.hash !== snapshotVersion(row);
|
||||
if (changed) {
|
||||
replaceSnapshot(row, files, found.fromSource ? found.st.hash : row.source_hash);
|
||||
} else if (found.fromSource) {
|
||||
sql("UPDATE artifacts SET source_hash = ? WHERE id = ?").run(found.st.hash, row.id);
|
||||
}
|
||||
return { item: shareNow(req, row.id, changed), changed };
|
||||
}
|
||||
|
||||
/** Share a row (server mode, when it is not yet) and answer its view; `audit` names a new version. */
|
||||
function shareNow(req, id, changed) {
|
||||
const row = sql("SELECT * FROM artifacts WHERE id = ?").get(id);
|
||||
if (isServer() && row.shared !== 1) {
|
||||
sql(
|
||||
`UPDATE artifacts SET shared = 1, shared_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'),
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?`
|
||||
).run(id);
|
||||
audit(req, row, "shared");
|
||||
} else if (changed && row.shared === 1) {
|
||||
audit(req, row, "updated");
|
||||
}
|
||||
return view(sql("SELECT * FROM artifacts WHERE id = ?").get(id), req);
|
||||
}
|
||||
|
||||
const SYNC_EVERY_MS = 15 * 1000;
|
||||
@@ -2163,6 +2337,36 @@ async function uninstall(req, id) {
|
||||
* the installer and an admin. `unrecorded` = installs counted before this
|
||||
* list was kept.
|
||||
*/
|
||||
/**
|
||||
* Where one recorded install of a skill stands now, from its Claude
|
||||
* `skills/<name>` copies (one per account it went into; the cross-tool
|
||||
* `~/.agents/skills` twins are the same files) —
|
||||
* `outdated` when any differs from the row's newest snapshot (its user is
|
||||
* offered Update), `removed` when none is there any more, `unknown` when one
|
||||
* is there but unreadable as a skill, else `latest`. Only hashes are
|
||||
* compared; no content leaves the server. The paths are the ones the server
|
||||
* itself recorded at install, read like `updateCheck` reads the viewer's own.
|
||||
*/
|
||||
function installState(row, paths) {
|
||||
const version = snapshotVersion(row);
|
||||
const dirs = (Array.isArray(paths) ? paths : []).filter(
|
||||
(p) =>
|
||||
typeof p === "string" &&
|
||||
path.basename(p) === row.source &&
|
||||
path.basename(path.dirname(p)) === "skills" &&
|
||||
path.basename(path.dirname(path.dirname(p))) !== ".agents"
|
||||
);
|
||||
if (!version || !dirs.length) return "unknown";
|
||||
const states = dirs.map((dir) => {
|
||||
const st = folderState(dir, path.dirname(path.dirname(dir)));
|
||||
if (st) return st.hash === version ? "latest" : "outdated";
|
||||
return exists(dir) ? "unknown" : "removed";
|
||||
});
|
||||
if (states.includes("outdated")) return "outdated";
|
||||
if (states.every((x) => x === "removed")) return "removed";
|
||||
return states.includes("unknown") ? "unknown" : "latest";
|
||||
}
|
||||
|
||||
function installsOf(req, id) {
|
||||
const row = load(req, id);
|
||||
const u = req?.user;
|
||||
@@ -2186,6 +2390,7 @@ function installsOf(req, id) {
|
||||
mine,
|
||||
at: r.installed_at,
|
||||
replaced: r.replaced === 1,
|
||||
...(row.kind === "skill" ? { state: installState(row, paths) } : {}),
|
||||
...(mine || u?.role === "admin" ? { paths } : {}),
|
||||
};
|
||||
});
|
||||
@@ -2215,6 +2420,7 @@ module.exports = {
|
||||
availableSkills,
|
||||
addSkill,
|
||||
uploadSkills,
|
||||
reshareSkill,
|
||||
writeSkill,
|
||||
uploadFile,
|
||||
skillSlug,
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
* home AgentHub placed that account in, never dated in the future, and
|
||||
* only when its id_token names the same account (`mayCopyBack`); the 2026-10-08
|
||||
* spike showed an old refresh token still refreshes, so panes sharing an
|
||||
* account do not log each other out.
|
||||
* account do not log each other out. Such a pane runs `--no-daemon`
|
||||
* (when its Codex has the flag): the home's shared app-server daemon
|
||||
* would keep serving the login it started with.
|
||||
*
|
||||
* Records live in `<CLAUDE_HOME>/agenthub-codex-accounts/<name>.json` (dir
|
||||
* 0700, file 0600); no route returns a key or a token.
|
||||
@@ -424,6 +426,46 @@ function liveInHome(name, member) {
|
||||
});
|
||||
}
|
||||
|
||||
// Codex ≥ 0.164 hands a plain TUI (no `-c` override) to the CODEX_HOME's shared
|
||||
// app-server daemon, which outlives every TUI and keeps the login it started
|
||||
// with — so a ChatGPT login placed in the home reached no pane while the
|
||||
// member's daemon ran on the previous one (reproduced on 0.164.0). A pool pane
|
||||
// runs its own app server instead. An older Codex has neither the daemon nor
|
||||
// the flag (it would refuse to start), so the flag goes only to a binary whose
|
||||
// --help lists it: probed once per binary (path, size, mtime).
|
||||
const noDaemonCache = new Map();
|
||||
|
||||
function noDaemonArgv(member) {
|
||||
const bin =
|
||||
process.env.AGENTHUB_CODEX_BIN ||
|
||||
(member
|
||||
? require("./shared-tools").sharedPath("codex")
|
||||
: require("./ai-tools").detect("codex").path);
|
||||
if (!bin) return [];
|
||||
let key;
|
||||
try {
|
||||
const st = fs.statSync(bin);
|
||||
key = `${fs.realpathSync(bin)}:${st.size}:${st.mtimeMs}`;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (!noDaemonCache.has(key)) {
|
||||
let help = "";
|
||||
try {
|
||||
help = require("node:child_process").execFileSync(bin, ["--help"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch {
|
||||
/* no answer: leave the flag out, as before */
|
||||
}
|
||||
noDaemonCache.set(key, /--no-daemon\b/.test(help));
|
||||
}
|
||||
return noDaemonCache.get(key) ? ["--no-daemon"] : [];
|
||||
}
|
||||
|
||||
/** `{name, kind}` of the account a new Codex pane would get, or null. */
|
||||
function pickAccount(member = null, ownerId = null) {
|
||||
const a = pick(member, ownerId);
|
||||
@@ -449,7 +491,7 @@ function forSpawn(member = null, ownerId = null) {
|
||||
}
|
||||
return {
|
||||
name: a.name,
|
||||
argv: [],
|
||||
argv: noDaemonArgv(member),
|
||||
env: {},
|
||||
place: () => {
|
||||
syncHome(member.home); // a live pane may hold a newer login than ours
|
||||
|
||||
+60
-8
@@ -61,6 +61,19 @@ async function readCapped(dir, args, capChars) {
|
||||
const MAX_FILES = 300;
|
||||
/** Most patch bytes read for ONE file before its hunks are cut short. */
|
||||
const MAX_FILE_BYTES = 200_000;
|
||||
/** Characters of one file's raw patch read before its long lines are cut down
|
||||
* (`elideLongLines`) and `MAX_FILE_BYTES` applied. A page that embeds a video
|
||||
* or a font as base64 is a few lines of megabytes each: read at
|
||||
* `MAX_FILE_BYTES`, its first such line used the whole budget and every hunk
|
||||
* after it was lost. Past this the patch is still truncated. */
|
||||
const MAX_PATCH_READ_CHARS = 16 * 1024 * 1024;
|
||||
/** A diff row longer than this is shown cut down to `LONG_LINE_KEEP`
|
||||
* characters, with how many it hides (`elided` on the parsed line). */
|
||||
const LONG_LINE_CHARS = 4000;
|
||||
const LONG_LINE_KEEP = 1000;
|
||||
/** Ends a cut-down row in the raw patch: a private-use character, then the
|
||||
* count of characters hidden. `parseUnifiedDiff` turns it into `elided`. */
|
||||
const ELIDED_MARK = "\uE000";
|
||||
/** Most patch bytes across all files in a `full` (review-mode) response. */
|
||||
const MAX_TOTAL_BYTES = 1_000_000;
|
||||
/** An untracked file larger than this is reported without content. */
|
||||
@@ -259,15 +272,23 @@ function parseUnifiedDiff(patch) {
|
||||
// row of its own and carries no line number.
|
||||
if (raw.startsWith("\\")) continue;
|
||||
const marker = raw[0];
|
||||
const text = raw.slice(1);
|
||||
let text = raw.slice(1);
|
||||
// A row `elideLongLines` cut down: the text it kept, and how much it hid.
|
||||
let elided = 0;
|
||||
const cut = text.lastIndexOf(ELIDED_MARK);
|
||||
if (cut >= 0 && /^\d+$/.test(text.slice(cut + 1))) {
|
||||
elided = Number(text.slice(cut + 1));
|
||||
text = text.slice(0, cut);
|
||||
}
|
||||
const extra = elided ? { elided } : {};
|
||||
if (marker === "+") {
|
||||
current.lines.push({ type: "add", oldLine: null, newLine: newLine++, text });
|
||||
current.lines.push({ type: "add", oldLine: null, newLine: newLine++, text, ...extra });
|
||||
} else if (marker === "-") {
|
||||
current.lines.push({ type: "del", oldLine: oldLine++, newLine: null, text });
|
||||
current.lines.push({ type: "del", oldLine: oldLine++, newLine: null, text, ...extra });
|
||||
} else if (marker === " ") {
|
||||
// An unchanged EMPTY line is " " — one space, no text. A truly empty
|
||||
// string is the tail of the final "\n", not a row.
|
||||
current.lines.push({ type: "ctx", oldLine: oldLine++, newLine: newLine++, text });
|
||||
current.lines.push({ type: "ctx", oldLine: oldLine++, newLine: newLine++, text, ...extra });
|
||||
}
|
||||
}
|
||||
return hunks;
|
||||
@@ -532,7 +553,27 @@ async function patchFor(dir, { range, baseRef, sha, file, untracked, context })
|
||||
: range === "branch"
|
||||
? ["diff", u, `${baseRef}...HEAD`, "--", file]
|
||||
: ["diff", u, "HEAD", "--", file];
|
||||
return readCapped(dir, [...args, "--no-color", "--no-ext-diff"], MAX_FILE_BYTES).catch(() => "");
|
||||
return readCapped(dir, [...args, "--no-color", "--no-ext-diff"], MAX_PATCH_READ_CHARS).catch(
|
||||
() => ""
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The patch with every row longer than `LONG_LINE_CHARS` cut down to its first
|
||||
* `LONG_LINE_KEEP` characters plus `ELIDED_MARK` and the count it hides. Only
|
||||
* what the panel SHOWS is cut: the hunk actions (`hunkPatch`, `selectionPatch`)
|
||||
* re-read git's own diff and match hunks by header, which this never changes.
|
||||
*/
|
||||
function elideLongLines(patch) {
|
||||
if (patch.length <= LONG_LINE_CHARS) return patch;
|
||||
return patch
|
||||
.split("\n")
|
||||
.map((row) =>
|
||||
row.length > LONG_LINE_CHARS && !row.startsWith("@@")
|
||||
? `${row.slice(0, LONG_LINE_KEEP + 1)}${ELIDED_MARK}${row.length - LONG_LINE_KEEP - 1}`
|
||||
: row
|
||||
)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -648,7 +689,15 @@ async function collectChanges(
|
||||
untracked: entry.untracked,
|
||||
context: ctx,
|
||||
});
|
||||
// A read that hit its own ceiling came back partial: still cut short,
|
||||
// however small eliding its long rows makes it.
|
||||
const partial = patch.length >= MAX_PATCH_READ_CHARS;
|
||||
patch = elideLongLines(patch);
|
||||
const cap = Math.min(MAX_FILE_BYTES, budget);
|
||||
if (partial) {
|
||||
entry.truncated = true;
|
||||
truncated = true;
|
||||
}
|
||||
if (patch.length > cap) {
|
||||
// Cut on a line boundary so the last row is a whole line — but only
|
||||
// when that boundary is near the cap. A minified file is one enormous
|
||||
@@ -1192,16 +1241,18 @@ async function diffHunks(dir, file, context) {
|
||||
* in file order, to be applied FORWARD onto an index holding HEAD. Every
|
||||
* header is matched against a fresh diff like `hunkPatch`'s; null when one is
|
||||
* gone or names a block the hunk lacks. Each hunk's new-side start is left as
|
||||
* git wrote it — `git apply` locates a hunk by its old side.
|
||||
* git wrote it — `git apply` locates a hunk by its old side. `reverse` cuts
|
||||
* it for `apply -R` off the working tree instead (the partial discard, #87),
|
||||
* where the NEW side is the one checked and every start stays git's own.
|
||||
*/
|
||||
async function selectionPatch(dir, file, context, picks) {
|
||||
async function selectionPatch(dir, file, context, picks, reverse = false) {
|
||||
const diff = await diffHunks(dir, file, context);
|
||||
if (!diff || !picks.length) return null;
|
||||
const at = (header) => diff.hunks.findIndex((h) => h.slice(0, h.indexOf("\n")) === header);
|
||||
if (picks.some((p) => at(p.hunk) < 0)) return null;
|
||||
const bodies = [];
|
||||
for (const p of [...picks].sort((x, y) => at(x.hunk) - at(y.hunk))) {
|
||||
const body = onlyBlock(diff.hunks[at(p.hunk)], p.blocks, false);
|
||||
const body = onlyBlock(diff.hunks[at(p.hunk)], p.blocks, reverse);
|
||||
if (!body) return null;
|
||||
bodies.push(body);
|
||||
}
|
||||
@@ -1334,6 +1385,7 @@ async function plainTreeAll(dir) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
elideLongLines,
|
||||
collectChanges,
|
||||
CONFLICT_CODES,
|
||||
contentSha,
|
||||
|
||||
@@ -715,6 +715,42 @@ async function linkedKeyFile(account, url) {
|
||||
return row ? (currentKeys(account).find((k) => k.id === row.key)?.file ?? null) : null;
|
||||
}
|
||||
|
||||
// AWS CodeCommit's SSH key ID belongs to an IAM user, so it logs in to EVERY
|
||||
// region of that AWS account — but our login rules are per host, and a repo
|
||||
// in a region the user never saved stayed refused. Such a clone borrows the
|
||||
// logins saved for the other CodeCommit regions (not aliases' hosts only: an
|
||||
// alias row's user is as valid), each with its own key when it names one.
|
||||
const CODECOMMIT_RE = /^git-codecommit\.[a-z0-9-]+\.amazonaws\.com$/;
|
||||
|
||||
/** `[{url, keyFile}]`: `url` with each borrowable CodeCommit user in it. */
|
||||
async function borrowedLogins(account, url) {
|
||||
if (!url.startsWith("ssh://")) return [];
|
||||
let u;
|
||||
try {
|
||||
u = new URL(url);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const host = u.host.toLowerCase();
|
||||
if (u.username || !CODECOMMIT_RE.test(host)) return [];
|
||||
const rows = await listSshUsers(account);
|
||||
// The region has a login of its own: git's insteadOf already applies it.
|
||||
if (rows.some((r) => (r.alias ?? r.host) === host)) return [];
|
||||
const keys = currentKeys(account);
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const r of rows) {
|
||||
if (!CODECOMMIT_RE.test(r.host)) continue;
|
||||
const keyFile = r.key ? (keys.find((k) => k.id === r.key)?.file ?? null) : null;
|
||||
if (r.key && !keyFile) continue;
|
||||
const id = `${r.user}\0${keyFile ?? ""}`;
|
||||
if (seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
out.push({ url: `ssh://${r.user}@${host}${u.pathname}`, keyFile });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Network commands in an existing repo (git bar fetch/pull/push) ─────────
|
||||
|
||||
/**
|
||||
@@ -878,12 +914,35 @@ async function cloneNow({ url, parent, name, once = null, partial = false }, thr
|
||||
if (once) throw err("EBADCRED", "a typed login is for https only — SSH uses your key");
|
||||
// A login naming its key (another AWS account, a second GitHub user)
|
||||
// offers that key ONLY — another key could log in as the wrong account.
|
||||
const linked = await linkedKeyFile(account, url);
|
||||
let linked = await linkedKeyFile(account, url);
|
||||
const sshFor = (file) => {
|
||||
const k = file ? [file] : keyFiles(account);
|
||||
const b = k.length ? `ssh${identityArgs(k)} -o IdentitiesOnly=yes` : "ssh";
|
||||
// BatchMode: no terminal to answer a prompt; accept-new: first contact
|
||||
// records the host key, a CHANGED one still fails.
|
||||
return `core.sshCommand=${b} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`;
|
||||
};
|
||||
// A CodeCommit region with no login of its own: the first borrowed login
|
||||
// the remote accepts (one is taken as is). The clone's URL then names
|
||||
// that user, so the repo's `origin` keeps logging in the same way.
|
||||
const borrowed = await borrowedLogins(account, url);
|
||||
for (const b of borrowed) {
|
||||
const ok =
|
||||
borrowed.length === 1 ||
|
||||
(await git(parent, ["-c", sshFor(b.keyFile), "ls-remote", "--", b.url, "HEAD"], {
|
||||
timeout: 60_000,
|
||||
}).then(
|
||||
() => true,
|
||||
() => false
|
||||
));
|
||||
if (ok) {
|
||||
url = b.url;
|
||||
linked = b.keyFile;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const keys = linked ? [linked] : keyFiles(account);
|
||||
const base = keys.length ? `ssh${identityArgs(keys)} -o IdentitiesOnly=yes` : "ssh";
|
||||
// BatchMode: no terminal to answer a prompt; accept-new: first contact
|
||||
// records the host key, a CHANGED one still fails.
|
||||
pre.push("-c", `core.sshCommand=${base} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`);
|
||||
pre.push("-c", sshFor(linked));
|
||||
if (keys.length) {
|
||||
// Persisted by FILE name — both default types plus every named key:
|
||||
// a default key made later is offered too (ssh skips a missing
|
||||
|
||||
+56
-14
@@ -424,6 +424,13 @@ async function runGitAction(dir, action, body = {}) {
|
||||
|
||||
if (action === "discard") {
|
||||
if (body.confirm !== true) throw bad("ECONFIRM", "discard requires confirm: true");
|
||||
// Ticked change blocks of partly ticked files (#87) go first: each patch
|
||||
// is built before any is applied, so a stale one refuses before the
|
||||
// irreversible whole-file part below has run.
|
||||
const partial = hasHunks(body) ? await discardSelection(dir, body) : null;
|
||||
if (partial && !(Array.isArray(body.paths) && body.paths.length)) {
|
||||
return done(action, partial);
|
||||
}
|
||||
const paths = await resolvePaths(dir, body);
|
||||
const untracked = paths.filter((p) => p.code === "??").map((p) => p.path);
|
||||
// A rename's ORIGINAL path rides along: restoring only the new one would
|
||||
@@ -431,7 +438,7 @@ async function runGitAction(dir, action, body = {}) {
|
||||
const tracked = paths
|
||||
.filter((p) => p.code !== "??")
|
||||
.flatMap((p) => (p.from && p.code.includes("R") ? [p.path, p.from] : [p.path]));
|
||||
const out = [];
|
||||
const out = partial ? [partial] : [];
|
||||
// Untracked files are deleted (git has no copy to restore); tracked ones
|
||||
// go back to HEAD in both gutters, so a staged-then-edited file lands in
|
||||
// one state rather than half-reverted.
|
||||
@@ -825,18 +832,11 @@ function hasHunks(body) {
|
||||
const MAX_PARTIAL_FILES = 300;
|
||||
|
||||
/**
|
||||
* JetBrains' partial commit: whole files (`paths`) plus, per file in `hunks`,
|
||||
* only the ticked change blocks — `{"<path>": [{hunk: "@@ … @@", blocks: [0]}]}`,
|
||||
* the hunks named as `stage-hunk` names them, at `context`. Built in a
|
||||
* TEMPORARY index (HEAD + the whole files + one patch per partial file from
|
||||
* `selectionPatch`, git's own fresh text, never the request's) and committed
|
||||
* from it, so the real index and the working tree are never in the way; after
|
||||
* the commit the real index entries of exactly those paths are reset to the
|
||||
* new HEAD, the rest of each partial file left as an unstaged change. Same
|
||||
* path rules as `commitPaths`; a partial file must be tracked (EUNTRACKED)
|
||||
* and not a rename, and a hunk the tree no longer has is EHUNKGONE.
|
||||
* `body.hunks` checked for shape, and its files resolved as changed paths
|
||||
* that may be taken in part: tracked (EUNTRACKED), not a rename, not in
|
||||
* conflict, and not also named whole in `body.paths`.
|
||||
*/
|
||||
async function commitSelection(dir, args, body) {
|
||||
async function partialPicks(dir, body, verb) {
|
||||
const picks = Object.entries(body.hunks);
|
||||
if (picks.length > MAX_PARTIAL_FILES) throw bad("EBADPATH", "too many files");
|
||||
for (const [, list] of picks) {
|
||||
@@ -858,12 +858,54 @@ async function commitSelection(dir, args, body) {
|
||||
const conflicted = [...whole, ...part].find((p) => CONFLICT_CODES.has(p.code));
|
||||
if (conflicted) throw bad("ECONFLICTS", `${conflicted.path} is in conflict: resolve it first`);
|
||||
for (const p of part) {
|
||||
if (p.code === "??") throw bad("EUNTRACKED", `${p.path} is untracked: commit it whole`);
|
||||
if (p.code.includes("R")) throw bad("EBADPATH", `${p.path} is a rename: commit it whole`);
|
||||
if (p.code === "??") throw bad("EUNTRACKED", `${p.path} is untracked: ${verb} it whole`);
|
||||
if (p.code.includes("R")) throw bad("EBADPATH", `${p.path} is a rename: ${verb} it whole`);
|
||||
if (whole.some((w) => w.path === p.path)) {
|
||||
throw bad("EBADPATH", `${p.path} is named both whole and in part`);
|
||||
}
|
||||
}
|
||||
return { picks, whole, part };
|
||||
}
|
||||
|
||||
/**
|
||||
* The partial discard (#87): per file in `hunks`, only the ticked change
|
||||
* blocks are undone off the working tree — `selectionPatch` in reverse, git's
|
||||
* own fresh text, never the request's — exactly what one `discard-hunk` per
|
||||
* block would do, in one step. Every patch is built before the first is
|
||||
* applied, so a stale selection refuses (EHUNKGONE) with nothing undone.
|
||||
*/
|
||||
async function discardSelection(dir, body) {
|
||||
const { picks } = await partialPicks(dir, body, "discard");
|
||||
const patches = [];
|
||||
for (const [p, list] of picks) {
|
||||
const patch = await selectionPatch(dir, p, body.context, list, true);
|
||||
if (!patch)
|
||||
throw bad("EHUNKGONE", `${p}: that change is no longer in the diff; refresh and retry`);
|
||||
patches.push(patch);
|
||||
}
|
||||
// The patch names paths from the repo root, so it is applied there.
|
||||
const top = (await git(dir, ["rev-parse", "--show-toplevel"])).stdout.trim();
|
||||
const zero = Number(body.context) === 0 ? ["--unidiff-zero"] : [];
|
||||
const out = [];
|
||||
for (const patch of patches)
|
||||
out.push(await git(top, ["apply", "-R", ...zero, "-"], { input: patch }));
|
||||
return mergeResults(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* JetBrains' partial commit: whole files (`paths`) plus, per file in `hunks`,
|
||||
* only the ticked change blocks — `{"<path>": [{hunk: "@@ … @@", blocks: [0]}]}`,
|
||||
* the hunks named as `stage-hunk` names them, at `context`. Built in a
|
||||
* TEMPORARY index (HEAD + the whole files + one patch per partial file from
|
||||
* `selectionPatch`, git's own fresh text, never the request's) and committed
|
||||
* from it, so the real index and the working tree are never in the way; after
|
||||
* the commit the real index entries of exactly those paths are reset to the
|
||||
* new HEAD, the rest of each partial file left as an unstaged change. Same
|
||||
* path rules as `commitPaths`; a partial file must be tracked (EUNTRACKED)
|
||||
* and not a rename, and a hunk the tree no longer has is EHUNKGONE.
|
||||
*/
|
||||
async function commitSelection(dir, args, body) {
|
||||
const { picks, whole, part } = await partialPicks(dir, body, "commit");
|
||||
const wholePaths = whole.flatMap((p) =>
|
||||
p.from && p.code.includes("R") ? [p.path, p.from] : [p.path]
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
||||
*/
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { db } = require("../db");
|
||||
const aiTools = require("./ai-tools");
|
||||
@@ -749,6 +750,17 @@ function ownerNames(id) {
|
||||
};
|
||||
}
|
||||
|
||||
/** True only when the folder is GONE (ENOENT/ENOTDIR) — a folder this
|
||||
* process may not read is still there, so it never counts as deleted. */
|
||||
function folderMissing(cwd) {
|
||||
try {
|
||||
fs.statSync(cwd);
|
||||
return false;
|
||||
} catch (err) {
|
||||
return err.code === "ENOENT" || err.code === "ENOTDIR";
|
||||
}
|
||||
}
|
||||
|
||||
function lanePayload(lane, ageSec = null) {
|
||||
const pipeline = getPipeline(lane.pipeline);
|
||||
const since = lane.stage_since ? Date.parse(lane.stage_since) : NaN;
|
||||
@@ -775,6 +787,9 @@ function lanePayload(lane, ageSec = null) {
|
||||
: Math.max(0, Math.round((Date.now() - since) / 1000)),
|
||||
last_event_seconds: ageSec,
|
||||
liveness: classifyLiveness({ status: lane.status, stage: lane.stage, ageSec }, DEAD_SEC),
|
||||
// The folder was deleted under the workspace (from Files, a shell): the
|
||||
// record stays — its sessions are history — but nothing can open in it.
|
||||
folder_missing: folderMissing(lane.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ const paths = {
|
||||
summary: "Skills from files: a file, a folder, a .zip/.skill or several skills",
|
||||
operationId: "uploadArtifactSkills",
|
||||
description:
|
||||
"`paths` is a JSON array of each file's relative path. Zip sizes are read before inflating; nothing is stored if any skill fails.",
|
||||
"`paths` is a JSON array of each file's relative path. Zip sizes are read before inflating; nothing is stored if any skill fails. A skill whose name matches one the caller already has (not a workspace's) becomes that row's new version (`replaced: true`, `changed`) instead of a second row; `id` (Share again) puts the ONE uploaded skill onto that row, under the row's name.",
|
||||
requestBody: multipart(
|
||||
{
|
||||
files: { type: "array", items: { type: "string", format: "binary" } },
|
||||
@@ -246,6 +246,7 @@ const paths = {
|
||||
name: { type: "string" },
|
||||
title: { type: "string" },
|
||||
description: { type: "string" },
|
||||
id: { type: "string", description: "Share again: the skill row the upload replaces." },
|
||||
},
|
||||
["files"]
|
||||
),
|
||||
|
||||
@@ -1113,6 +1113,26 @@ const paths = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/artifacts/{id}/reshare": {
|
||||
post: {
|
||||
tags: ["Artifacts"],
|
||||
summary: "Share again: a skill's newest version from its owner's folder on this server",
|
||||
operationId: "reshareArtifact",
|
||||
description:
|
||||
"The owner's skill folder (the row's source folder, else the same-named skill of a plugin the owner installed at user scope) becomes the new snapshot, and the row is shared (server mode); installers are then offered Update. 409 ENOSOURCE when the server has no copy: upload the folder with `id` on /api/artifacts/skill/upload. Same-origin only.",
|
||||
parameters: [pathParam("id", "Artifact id.")],
|
||||
responses: {
|
||||
200: ok("Taken.", {
|
||||
item: { type: "object" },
|
||||
changed: { type: "boolean" },
|
||||
}),
|
||||
400: errs("EBADKIND."),
|
||||
403: errs("EFORBIDDEN."),
|
||||
404: errs("ENOTFOUND."),
|
||||
409: errs("ENOSOURCE."),
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/artifacts/{id}/claim": {
|
||||
post: {
|
||||
tags: ["Artifacts"],
|
||||
|
||||
@@ -39,6 +39,7 @@ const STATUS = {
|
||||
ENEEDLOGIN: 502,
|
||||
ETOOBIG: 413,
|
||||
EOWNED: 409,
|
||||
ENOSOURCE: 409,
|
||||
};
|
||||
|
||||
function sendError(res, err) {
|
||||
@@ -229,6 +230,7 @@ router.post(
|
||||
name: b.name,
|
||||
title: b.title,
|
||||
description: b.description,
|
||||
id: b.id,
|
||||
});
|
||||
for (const item of items) changed(item);
|
||||
res.status(201).json({ items });
|
||||
@@ -284,6 +286,19 @@ router.patch(
|
||||
})
|
||||
);
|
||||
|
||||
// Share again: the owner's skill folder on this server becomes the new
|
||||
// version (installers see Update); 409 ENOSOURCE when the server has none —
|
||||
// the client then uploads the folder onto this row (`/skill/upload` + `id`).
|
||||
router.post(
|
||||
"/:id/reshare",
|
||||
sameOriginGuard,
|
||||
wrap((req, res) => {
|
||||
const out = artifacts.reshareSkill(req, req.params.id);
|
||||
changed(out.item);
|
||||
res.json(out);
|
||||
})
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/:id",
|
||||
sameOriginGuard,
|
||||
|
||||
Reference in New Issue
Block a user