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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/upstream-fixes/cursor
Original file line number Diff line number Diff line change
@@ -1 +1 @@
ce36269560ad502cf6a5c44775fc4e648e829d2a
6ce5c5b4d4a3560bb9a5dbb1b6b2ecfaf21a67d9
15 changes: 15 additions & 0 deletions .github/upstream-fixes/manual
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,18 @@ ce56dfe956d1 # fix(notebook): keep the final frame across saved stream records (
2e2af395f626 # fix(web): EPUB previews keep SVG lighting filters (#44498): did not apply
af70189a8f6f # fix(web): remote localhost links in chat and terminal open through a port forward (#44452): did not apply
30e7a1f84822 # fix(shared): thread search by PR number keeps the PR title when a branch PR is also linked (#44495): adds an upstream runtime identifier; manual port needed to packages/client-runtime/src/threadPullRequests.test.ts
bf6c5dfd556b # failed CI as a single pick in #48 (https://github.com/Ryoku-dev/hyakki/actions/runs/46711414007); needs a manual port
93955ac9bd0d # fix(web): preserve ODT list marker styles (#44514): did not apply
1356a26ebad1 # fix(web): large CSV previews keep their end position (#44520): did not apply
13f9213cffc0 # fix(client-runtime): keep the scheme and port in fallback URLs for mounted Forgejo pull requests (#44521): did not apply
5f435d14570d # fix(server): detach idle threads from shared provider sessions (#44020): did not apply
2338c6f30583 # fix(shared): thread links work after list code blocks (#44527): did not apply
1060a7e151d8 # fix(server): avoid broken emoji in project search previews during indexing (#44531): did not apply
c0f45b67620c # fix(client-runtime): /reload-skills refreshes the composer skill menu (#31309): did not apply
d26bc688a5e9 # fix(server): resolve project favicons with encoded HTML rel tokens (#44537): did not apply
c49c99659427 # fix(mcp): include completed user input answers in thread reads (#44542): did not apply
cf4a35f7a7af # fix(web): /feedback no longer drops a pending reply (#44541): did not apply
1f6fe0afbf52 # fix(web): large logs keep their place when switching tabs (#44517): did not apply
ae8c3c8d6a03 # fix(web): diff panel shows images when their file row is expanded (#44556): did not apply
6ce5c5b4d4a3 # fix: show proposed plan titles once after code examples (#44518): did not apply
b89c25ffd9a7 # fix(web): keep sidebar search results when opening threads (#30278): adds an upstream runtime identifier; manual port needed to apps/web/src/components/Sidebar.search.browser.test.tsx
1 change: 1 addition & 0 deletions .github/upstream-fixes/skip
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# Upstream commits the fixes workflow must never pick, one sha per line.
# Add a commit here when it does not fit this fork; a short sha is enough.
270fb873f470 # Failed CI twice as a single pick in PR #13; needs a manual port.
bf6c5dfd556b # failed CI as a single pick in #48 (https://github.com/Ryoku-dev/hyakki/actions/runs/46711414007); needs a manual port
72 changes: 58 additions & 14 deletions apps/server/src/guest/GuestShareService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ChatAttachmentId,
CommandId,
EventId,
GUEST_SHARE_TTL_MS,
GuestShareId,
type GuestStreamEvent,
MessageId,
Expand Down Expand Up @@ -757,27 +758,70 @@ it.effect("pages the guest back through turns older than the stream's snapshot",
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);

it.effect("ends a running command's output once the owner stops sharing", () =>
it.effect.each(["thread.guest-share.close", "thread.archive", "thread.delete"] as const)(
"ends a running command's output on %s",
(type) =>
Effect.gen(function* () {
const { orchestrator, guestShares, credential } = yield* shareThread;
const commandOutputs = yield* CommandOutputHub.CommandOutputHub;
const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
const command = yield* writeItem("item:running", {
type: "command_execution",
status: "running",
input: "ls /work/src",
output: "before-close\n",
});
const opened = yield* Deferred.make<void>();
const collecting = yield* (yield* guestShares.commandOutput(session, command)).pipe(
Stream.tap(() => Deferred.succeed(opened, undefined)),
Stream.runCollect,
Effect.forkChild,
);
yield* Deferred.await(opened);
// Let the periodic revocation fiber finish its initial open-share check and enter its 30s wait.
yield* TestClock.adjust("1 second");
yield* orchestrator.dispatch({
type,
commandId: CommandId.make(`${type}-during-command`),
threadId,
});
yield* commandOutputs.append({ threadId, itemId: command, chunk: "SECRET_AFTER_CLOSE\n" });
yield* TestClock.adjust("1 second");
const endedBeforeRecheck = collecting.pollUnsafe() !== undefined;
// Advance past the fallback poll so an unpatched server finishes cleanly and fails on the leak assertion.
yield* TestClock.adjust("30 seconds");
const frames = Array.from(yield* Fiber.join(collecting));
assert.isFalse(frames.some((frame) => frame.text.includes("SECRET_AFTER_CLOSE")));
assert.isTrue(endedBeforeRecheck);
assert.isTrue(
Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command))),
);
}).pipe(Effect.provide(layerTest)),
);

it.effect("ends a running command's output when the link expires, before the next recheck", () =>
Effect.gen(function* () {
const { orchestrator, guestShares, credential } = yield* shareThread;
const { guestShares, credential } = yield* shareThread;
const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
const command = yield* writeItem("item:running", {
type: "command_execution",
status: "running",
input: "ls /work/src",
output: "before-expiry\n",
});
const collecting = yield* Stream.runCollect(
yield* guestShares.commandOutput(session, command),
).pipe(Effect.forkChild);
yield* orchestrator.dispatch({
type: "thread.guest-share.close",
commandId: CommandId.make("close-during-command"),
threadId,
});
yield* TestClock.adjust("30 seconds");
const frames = Array.from(yield* Fiber.join(collecting));
assert.isTrue(frames.every((frame) => frame.running));
assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command))));
// Opening 10s after the share puts the 30s rechecks at 10s past each half minute, off the expiry.
yield* TestClock.adjust("10 seconds");
const opened = yield* Deferred.make<void>();
const collecting = yield* (yield* guestShares.commandOutput(session, command)).pipe(
Stream.tap(() => Deferred.succeed(opened, undefined)),
Stream.runCollect,
Effect.forkChild,
);
yield* Deferred.await(opened);
yield* TestClock.adjust(GUEST_SHARE_TTL_MS - 10_000 - 1);
assert.isUndefined(collecting.pollUnsafe());
yield* TestClock.adjust(2);
assert.isDefined(collecting.pollUnsafe());
}).pipe(Effect.provide(layerTest)),
);

Expand Down
37 changes: 28 additions & 9 deletions apps/server/src/guest/GuestShareService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,12 @@ const make = Effect.gen(function* () {
});
});

const endsShareFor = (shareId: GuestShareId) => (event: OrchestrationV2DomainEvent) => {
if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
const updated = threadOf(event);
return updated !== null && updated.guestShare?.id !== shareId;
};

/** Completes once the session no longer opens its share, so open reads end with it. */
const untilRevoked = (session: string) =>
authorize(session, "session").pipe(
Expand Down Expand Up @@ -559,11 +565,7 @@ const make = Effect.gen(function* () {
if (initialView === null) return yield* inactive;

const ended: GuestStreamEvent = { type: "ended" };
const endsShare = (event: OrchestrationV2DomainEvent) => {
if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
const updated = threadOf(event);
return updated !== null && updated.guestShare?.id !== share.id;
};
const endsShare = endsShareFor(share.id);
const live = orchestrator
.streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })
.pipe(
Expand Down Expand Up @@ -655,7 +657,7 @@ const make = Effect.gen(function* () {
session: string,
itemId: string,
) {
const { thread } = yield* authorize(session, "session");
const { thread, share } = yield* authorize(session, "session");
const id = TurnItemId.make(itemId);
const item =
(yield* orchestrator
Expand All @@ -668,7 +670,7 @@ const make = Effect.gen(function* () {
Effect.map((page) => page.items[0]?.item ?? null),
Effect.mapError(() => unavailable),
));
return item === null ? yield* unavailable : { thread, item };
return item === null ? yield* unavailable : { thread, share, item };
});

const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {
Expand Down Expand Up @@ -708,12 +710,29 @@ const make = Effect.gen(function* () {
session: string,
itemId: string,
) {
const { item } = yield* threadItem(session, itemId);
const { thread, share, item } = yield* threadItem(session, itemId);
if (item.type !== "command_execution") return yield* unavailable;
const afterSequence = yield* orchestrator
.getThreadEventSequence(thread.id)
.pipe(Effect.mapError(() => unavailable));
// A share that ends before the cursor is read fails this check; one that ends after it ends
// `shareEnded`.
yield* authorize(session, "session");
const endsShare = endsShareFor(share.id);
const shareEnded = orchestrator
.streamStoredEventsFrom({ threadId: thread.id, afterSequence })
.pipe(
Stream.filter((stored) => endsShare(stored.event)),
Stream.runHead,
Effect.ignore,
);
const untilExpiry = Effect.sleep(
Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
);
return commandOutputs.subscribe({ threadId: item.threadId, itemId: item.id }).pipe(
// A lost hub stream ends the output; the row reloads it when reopened.
Stream.catchCause(() => Stream.empty),
Stream.interruptWhen(untilRevoked(session)),
Stream.interruptWhen(Effect.raceAll([shareEnded, untilExpiry, untilRevoked(session)])),
);
});

Expand Down
49 changes: 33 additions & 16 deletions apps/server/src/resourceTelemetry/ResourceTelemetryHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,27 +117,44 @@ function buildBuckets(input: {
}): ReadonlyArray<ResourceTelemetryHistoryBucket> {
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ResourceTelemetryHistoryBucket[] = [];
// Samples arrive sorted by sampledAtMs, so one cursor walks them across all buckets.
let index = 0;
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) {
const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs);
const samples = input.samples.filter(
(sample) =>
sample.sampledAtMs >= startedAtMs &&
(endedAtMs === input.nowMs
? sample.sampledAtMs <= endedAtMs
: sample.sampledAtMs < endedAtMs),
);
const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0);
const isLastBucket = endedAtMs === input.nowMs;
while (index < input.samples.length && input.samples[index]!.sampledAtMs < startedAtMs) {
index += 1;
}
let count = 0;
let cpuTotal = 0;
let maxCpuPercent = -Infinity;
let maxRssBytes = -Infinity;
let maxProcessCount = -Infinity;
let ioReadBytes = 0;
let ioWriteBytes = 0;
while (index < input.samples.length) {
const sample = input.samples[index]!;
if (isLastBucket ? sample.sampledAtMs > endedAtMs : sample.sampledAtMs >= endedAtMs) {
break;
}
count += 1;
cpuTotal += sample.cpuPercent;
maxCpuPercent = Math.max(maxCpuPercent, sample.cpuPercent);
maxRssBytes = Math.max(maxRssBytes, sample.rssBytes);
maxProcessCount = Math.max(maxProcessCount, sample.processCount);
ioReadBytes += sample.ioReadBytes;
ioWriteBytes += sample.ioWriteBytes;
index += 1;
}
buckets.push({
startedAt: DateTime.makeUnsafe(startedAtMs),
endedAt: DateTime.makeUnsafe(endedAtMs),
avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,
maxCpuPercent:
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),
maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),
ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),
ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),
maxProcessCount:
samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),
avgCpuPercent: count === 0 ? 0 : cpuTotal / count,
maxCpuPercent: count === 0 ? 0 : maxCpuPercent,
maxRssBytes: count === 0 ? 0 : maxRssBytes,
ioReadBytes,
ioWriteBytes,
maxProcessCount: count === 0 ? 0 : maxProcessCount,
});
}
return buckets;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ import { AsyncResult } from "effect/reactivity";
const scopes = vi.hoisted(() => ({
denied: undefined as string | undefined,
sourceControl: undefined as unknown,
isBrowsePending: false,
lookupRepository: vi.fn(),
}));
const setup = (deniedScope?: string, sourceControl?: unknown) => {
const setup = (deniedScope?: string, sourceControl?: unknown, isBrowsePending = false) => {
scopes.denied = deniedScope;
scopes.sourceControl = sourceControl;
scopes.isBrowsePending = isBrowsePending;
};
const githubAvailable = {
versionControlSystems: [],
Expand Down Expand Up @@ -131,7 +133,11 @@ vi.mock("../state/filesystem", async (original) => ({
}));
vi.mock("../state/query", async (original) => ({
...(await original<typeof import("../state/query")>()),
useEnvironmentQuery: () => ({ data: scopes.sourceControl, isLoading: false }),
useEnvironmentQuery: () => ({
data: scopes.sourceControl,
isLoading: false,
isPending: scopes.isBrowsePending,
}),
}));
vi.mock("./settings/useAvailableSettingsSearchItems", () => ({
useAvailableSettingsSearchItems: () => [],
Expand Down Expand Up @@ -173,6 +179,27 @@ describe.each(["repository", "folder", "destination"] as const)("add-project %s"
});
});

it.each([
{ isBrowsePending: false, leavesInput: true },
{ isBrowsePending: true, leavesInput: false },
])(
"Tab with nothing to complete in the folder path: %j",
async ({ isBrowsePending, leavesInput }) => {
setup(undefined, undefined, isBrowsePending);
await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
await act(() => openCommandPalette({ open: "add-project" }));
await page.getByText("Local folder", { exact: true }).click();
const input = page.getByRole("combobox");
await input.fill("/workspace/zzz");
await userEvent.keyboard("{Tab}");
if (leavesInput) {
await expect.element(input).not.toHaveFocus();
expect(page.getByRole("dialog").element().contains(document.activeElement)).toBe(true);
} else await expect.element(input).toHaveFocus();
await expect.element(input).toHaveValue("/workspace/zzz");
},
);

it.each([
{ step: "folder", source: "Local folder", keys: "", description: /^(?!.*(Ctrl|⌘)).*Add.*Enter/ },
{
Expand Down Expand Up @@ -228,6 +255,7 @@ it.each([
{ flow: "Git URL", value: "https://github.com/Ryoku-dev/hyakki.git", submit: "Continue (Enter)" },
{ flow: "New project", value: "demo-tab-order", submit: /^Create \(/ },
])("moves focus from the $flow input to its enabled submit button on Tab", async (step) => {
setup();
await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
await act(() => openCommandPalette({ open: "add-project" }));
await page.getByText(step.flow, { exact: true }).click();
Expand Down
24 changes: 20 additions & 4 deletions apps/web/src/components/CommandPalette.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,19 @@ describe("linked pull request thread navigation", () => {
});

describe("reduceCommandPaletteUiState", () => {
it("keeps the session on dismissal and advances it on keyboard reopen", () => {
const open: CommandPaletteUiState = {
open: true,
mode: "command",
openIntent: null,
session: 1,
};
const toggle = { _tag: "ToggleMode", mode: "command" } as const;
const closed = reduceCommandPaletteUiState(open, toggle);
expect(closed).toMatchObject({ open: false, session: 1 });
expect(reduceCommandPaletteUiState(closed, toggle)).toMatchObject({ open: true, session: 2 });
});

it("opens PR search from another overlay and replaces an earlier search", () => {
const first = reduceCommandPaletteUiState(
{ open: true, mode: "files", openIntent: null, session: 0 },
Expand Down Expand Up @@ -90,7 +103,7 @@ describe("reduceCommandPaletteUiState", () => {
).toBeNull();
});

it("keeps the session across mode switches so only intents start the palette over", () => {
it("starts a new session when a shortcut replaces the active mode", () => {
let state: CommandPaletteUiState = {
open: false,
mode: "command",
Expand All @@ -100,12 +113,12 @@ describe("reduceCommandPaletteUiState", () => {
state = reduceCommandPaletteUiState(state, { _tag: "OpenNewThreadIn" });
expect(state).toMatchObject({ open: true, openIntent: { kind: "new-thread-in" }, session: 1 });
state = reduceCommandPaletteUiState(state, { _tag: "ToggleMode", mode: "files" });
expect(state).toMatchObject({ mode: "files", openIntent: null, session: 1 });
expect(state).toMatchObject({ mode: "files", openIntent: null, session: 2 });
state = reduceCommandPaletteUiState(state, { _tag: "OpenAddProject" });
expect(state).toMatchObject({
mode: "command",
openIntent: { kind: "add-project" },
session: 2,
session: 3,
});
});
});
Expand Down Expand Up @@ -943,7 +956,10 @@ describe("returning from file and content search", () => {
const closed = reduceCommandPaletteUiState(child, { _tag: "SetOpen", open: false });
expect(closed).toEqual({ open: false, mode: "files", openIntent: null, session: 0 });
expect(reduceCommandPaletteUiState(closed, { _tag: "BackToCommand" })).toEqual(closed);
expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual(root);
expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual({
...root,
session: 1,
});
});
});

Expand Down
Loading
Loading