Merge branch 'main' into task/pep-264
This commit is contained in:
commit
fee71742e7
@ -28,7 +28,7 @@
|
||||
- Диалог разрешений Claude меняется (3–4 пункта, «2» бывает «switch to auto mode»): поздний ответ PM — `permissionKey` читает номер с экрана; после «No» Claude прерывает ход без Stop — Пеппа печатает `PERMISSION_DENIED_NOTE` (PEP-3). `mcp__peppa` разрешён в run-settings
|
||||
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
|
||||
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
|
||||
- Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3 сверил остальное: хуки, statusLine, transcript, диалог разрешений — `packages/testkit/fixtures/claude-live/`, `claude-live.test.ts`; снять лимит — `PEPPA_HOOK_CAPTURE_DIR=<каталог>` в env раннера, хук кладёт туда сырые payload'ы)
|
||||
- Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. **Старая плашка (PEP-300)**: Claude Code сам ждёт сброса («set to continue automatically at 6:50pm», уведомление `quota_auto_resume_fired`) и продолжает, плашка остаётся на экране; время на ней уже прошло — это не новый лимит: `passedReset` (runner/limits.ts; окно 4 ч после названного времени, сегодня или вчера сразу после полуночи; полная дата в прошлом), вачдог подписку не помечает и агента не останавливает, событие `usage_limit_passed` раз на плашку (`watch_state.limitPassedAt`), `limitGen` не тратится; `parseResetTime` по-прежнему даёт ближайшее будущее — им читают только свежие сообщения (хук, «Проверить»). Время в сообщениях о лимите — в поясе платформы (`PEPPA_TZ`), а не сервера. В тестах время на плашке берите от текущего (`clock`/`ahead`), а не «5pm». Реальные строки лимита настоящего Claude ещё не сняты (PEP-3 сверил остальное: хуки, statusLine, transcript, диалог разрешений — `packages/testkit/fixtures/claude-live/`, `claude-live.test.ts`; снять лимит — `PEPPA_HOOK_CAPTURE_DIR=<каталог>` в env раннера, хук кладёт туда сырые payload'ы)
|
||||
- `peppa session resume <id>` → `claude --resume`
|
||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные пользователи (PEP-68), кроме отключённых; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
|
||||
|
||||
@ -175,7 +175,7 @@ export async function projectAgentWarning(db: Db, projectId: number, now = new D
|
||||
const why = subs.map((s) => {
|
||||
const v = { name: publicSubscriptionName(s), status: STATUS_RU[s.status] ?? s.status };
|
||||
if (s.status !== "limited" || !s.limitedUntil) return tr("{name} — {status}", v);
|
||||
return tr("{name} — {status} до {until}", { ...v, until: s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit" }) });
|
||||
return tr("{name} — {status} до {until}", { ...v, until: s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit", timeZone: process.env.PEPPA_TZ || undefined }) });
|
||||
});
|
||||
return tr("у проекта нет рабочей подписки: {why}", { why: why.join(", ") });
|
||||
}
|
||||
|
||||
@ -415,6 +415,8 @@ export type WatchState = {
|
||||
/** PEP-166: limit banners already on screen when this generation started (a resumed conversation shows its history). */
|
||||
limitBaseGen?: number;
|
||||
limitBase?: number;
|
||||
/** PEP-300: reset time (ms) of a banner read after that time — its limit was over; noted once. */
|
||||
limitPassedAt?: number;
|
||||
thresholdGen?: number;
|
||||
/** Times (ms) of automatic restarts — the limit counts those inside the window. */
|
||||
restarts?: number[];
|
||||
|
||||
@ -50,7 +50,7 @@ export async function limitDelay(db: Db, s: SessionView, text: string, o: { now?
|
||||
const [row] = await db.select({ task: tasks, project: projects }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, s.taskId));
|
||||
if (!row) return;
|
||||
const ref: TaskRef = { ...row, key: formatTaskKey(row.project.key, row.task.number) };
|
||||
const time = new Date(resumeAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
const time = new Date(resumeAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const q = await askPm(db, ref, {
|
||||
kind: "question",
|
||||
options: [LIMIT_ADD, LIMIT_REQUEST, LIMIT_WAIT],
|
||||
|
||||
@ -32,29 +32,26 @@ export function freshLimitLine(screen: string, base: number): string | null {
|
||||
|
||||
export const limitAutoResumeEnabled = () => process.env.PEPPA_LIMIT_AUTORESUME !== "off";
|
||||
|
||||
/**
|
||||
* Reset time from a limit message: "resets 5pm", "resets at 3:10 AM", "reset at 15:00",
|
||||
* "try again at 5:00 PM", "resets in 2h 15m", and Claude Code's newer banner
|
||||
* "Usage limit reached · continuing automatically at 6pm" (PEP-166). A clock time without a date is the nearest
|
||||
* future one (local time of this machine). Null when there is no time in the text.
|
||||
*/
|
||||
export function parseResetTime(text: string, now: Date): Date | null {
|
||||
const rel = /reset[s]?\s+in\s+(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?)?/i.exec(text);
|
||||
if (rel && (rel[1] || rel[2])) return new Date(now.getTime() + (Number(rel[1] ?? 0) * 60 + Number(rel[2] ?? 0)) * 60_000);
|
||||
// PEP-205: Codex names the day when the reset is not today — «try again at Nov 18th, 2026 9:13 PM».
|
||||
const dated = /(?:reset[s]?|try again)(?:\s+(?:at|on))?\s+([A-Z][a-z]{2})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})(?:,|\s+at)?\s+(\d{1,2}):(\d{2})\s*(am|pm)?/i.exec(text);
|
||||
if (dated) {
|
||||
const month = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].indexOf(dated[1]!.toLowerCase());
|
||||
let h = Number(dated[4]);
|
||||
const pm = dated[6]?.toLowerCase();
|
||||
if (pm === "pm" && h < 12) h += 12;
|
||||
if (pm === "am" && h === 12) h = 0;
|
||||
if (month >= 0 && h <= 23) {
|
||||
const t = new Date(Number(dated[3]), month, Number(dated[2]), h, Number(dated[5]), 0, 0);
|
||||
if (t.getTime() > now.getTime()) return t;
|
||||
}
|
||||
}
|
||||
const abs = /(?:reset[s]?|try again|continu(?:e|es|ing)(?:\s+automatically)?)(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i.exec(text);
|
||||
const REL_RE = /reset[s]?\s+in\s+(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?)?/i;
|
||||
// PEP-205: Codex names the day when the reset is not today — «try again at Nov 18th, 2026 9:13 PM».
|
||||
const DATED_RE = /(?:reset[s]?|try again)(?:\s+(?:at|on))?\s+([A-Z][a-z]{2})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})(?:,|\s+at)?\s+(\d{1,2}):(\d{2})\s*(am|pm)?/i;
|
||||
const CLOCK_RE = /(?:reset[s]?|try again|continu(?:e|es|ing)(?:\s+automatically)?)(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i;
|
||||
|
||||
/** «try again at Nov 18th, 2026 9:13 PM» — the full date and time (local), or null. */
|
||||
function datedTime(text: string): Date | null {
|
||||
const dated = DATED_RE.exec(text);
|
||||
if (!dated) return null;
|
||||
const month = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].indexOf(dated[1]!.toLowerCase());
|
||||
let h = Number(dated[4]);
|
||||
const pm = dated[6]?.toLowerCase();
|
||||
if (pm === "pm" && h < 12) h += 12;
|
||||
if (pm === "am" && h === 12) h = 0;
|
||||
return month >= 0 && h <= 23 ? new Date(Number(dated[3]), month, Number(dated[2]), h, Number(dated[5]), 0, 0) : null;
|
||||
}
|
||||
|
||||
/** A clock time without a date: «resets 5pm», «try again at 8:47 PM», «continuing automatically at 6pm». */
|
||||
function clockTime(text: string): { h: number; m: number } | null {
|
||||
const abs = CLOCK_RE.exec(text);
|
||||
if (!abs) return null;
|
||||
let h = Number(abs[1]);
|
||||
const m = Number(abs[2] ?? 0);
|
||||
@ -62,14 +59,57 @@ export function parseResetTime(text: string, now: Date): Date | null {
|
||||
if (!ampm && !abs[2]) return null; // a bare number isn't a time
|
||||
if (ampm === "pm" && h < 12) h += 12;
|
||||
if (ampm === "am" && h === 12) h = 0;
|
||||
if (h > 23 || m > 59) return null;
|
||||
return h > 23 || m > 59 ? null : { h, m };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset time from a limit message: "resets 5pm", "resets at 3:10 AM", "reset at 15:00",
|
||||
* "try again at 5:00 PM", "resets in 2h 15m", and Claude Code's newer banner
|
||||
* "Usage limit reached · continuing automatically at 6pm" (PEP-166). A clock time without a date is the nearest
|
||||
* future one (local time of this machine). Null when there is no time in the text.
|
||||
* For a banner read off a screen ask `passedReset` first: an old banner's time has passed, and here
|
||||
* it would come out as tomorrow's (PEP-300).
|
||||
*/
|
||||
export function parseResetTime(text: string, now: Date): Date | null {
|
||||
const rel = REL_RE.exec(text);
|
||||
if (rel && (rel[1] || rel[2])) return new Date(now.getTime() + (Number(rel[1] ?? 0) * 60 + Number(rel[2] ?? 0)) * 60_000);
|
||||
const dated = datedTime(text);
|
||||
if (dated && dated.getTime() > now.getTime()) return dated;
|
||||
const clock = clockTime(text);
|
||||
if (!clock) return null;
|
||||
const t = new Date(now);
|
||||
t.setHours(h, m, 0, 0);
|
||||
t.setHours(clock.h, clock.m, 0, 0);
|
||||
if (t.getTime() <= now.getTime()) t.setDate(t.getDate() + 1);
|
||||
return t;
|
||||
}
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
/** PEP-300: how long after its reset time a limit banner may still be on an agent's screen and count as old. */
|
||||
export const PASSED_RESET_WINDOW_MS = 4 * 60 * 60_000;
|
||||
|
||||
/**
|
||||
* PEP-300: the reset time a banner names when that time has already passed — the limit behind the
|
||||
* banner is over, the line only stays on the screen. Claude Code waits for the reset itself («set to
|
||||
* continue automatically at 6:50pm»), goes on, and the watchdog reads the banner when the turn has
|
||||
* ended: at 18:51 «6:50pm» is not tomorrow's reset (25.11.2026: three working subscriptions were
|
||||
* marked «лимит» for a day). Null when the time is still ahead or the text has none.
|
||||
* A clock time without a date counts as passed for PASSED_RESET_WINDOW_MS after it — today or, just
|
||||
* after midnight, yesterday; read later than that it is the next day's reset, as `parseResetTime` reads it.
|
||||
*/
|
||||
export function passedReset(text: string, now: Date): Date | null {
|
||||
const rel = REL_RE.exec(text);
|
||||
if (rel && (rel[1] || rel[2])) return null;
|
||||
const dated = datedTime(text);
|
||||
if (dated) return dated.getTime() <= now.getTime() ? dated : null;
|
||||
const clock = clockTime(text);
|
||||
if (!clock) return null;
|
||||
const prev = new Date(now);
|
||||
prev.setHours(clock.h, clock.m, 0, 0);
|
||||
if (prev.getTime() > now.getTime()) prev.setDate(prev.getDate() - 1);
|
||||
return now.getTime() - prev.getTime() <= PASSED_RESET_WINDOW_MS ? prev : null;
|
||||
}
|
||||
|
||||
// PEP-300: people read the time in the platform's zone (PEPPA_TZ), not in the server's (UTC in the containers).
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, local
|
||||
|
||||
/**
|
||||
|
||||
@ -57,7 +57,7 @@ export async function planRotation(db: Db, s: SessionView, reason: RotateReason,
|
||||
return rotationCandidate(db, s, { now, onlyIdle: reason === "threshold" });
|
||||
}
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
|
||||
/**
|
||||
* Relaunches the session on `target`: Claude Code and OpenCode continue the same
|
||||
|
||||
@ -35,7 +35,7 @@ import { projects, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { realpathSync } from "node:fs";
|
||||
import * as tmux from "./tmux.ts";
|
||||
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, LIMIT_SCREEN_RE, limitLines, recordLimit } from "./limits.ts";
|
||||
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, LIMIT_SCREEN_RE, limitLines, passedReset, recordLimit } from "./limits.ts";
|
||||
import { limitDelay, limitOver } from "./limit-delay.ts";
|
||||
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
|
||||
import { readyDigestTick } from "./ready-digest.ts";
|
||||
@ -265,7 +265,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
|
||||
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
|
||||
await killRunner(s).catch(() => {});
|
||||
if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() });
|
||||
else if (LIMIT_SCREEN_RE.test(tail)) {
|
||||
else if (LIMIT_SCREEN_RE.test(tail) && !passedReset(limitLines(tail).at(-1)!, nowDate)) {
|
||||
// PEP-205: the CLI gave up on a usage limit — that is a limit, not a crash: another subscription
|
||||
// or a pause until the reset, no automatic restart is spent.
|
||||
const line = limitLines(tail).at(-1)!;
|
||||
@ -355,8 +355,17 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
|
||||
s = { ...s, watchState: { ...s.watchState, limitBase: banners } };
|
||||
}
|
||||
const fresh = freshLimitLine(screen, s.watchState?.limitBase ?? 0);
|
||||
// PEP-300: the banner names a reset time that has passed — its limit is over: Claude Code waited
|
||||
// for the reset itself and went on, the line is still on the screen. Not a new limit: nothing is
|
||||
// stored, nobody is stopped, the generation's one fallback is not spent; the journal gets one line.
|
||||
const passed = fresh ? passedReset(fresh, new Date(now)) : null;
|
||||
if (passed && s.watchState?.limitPassedAt !== passed.getTime()) {
|
||||
await patchWatch(db, s, { limitPassedAt: passed.getTime() });
|
||||
s = { ...s, watchState: { ...s.watchState, limitPassedAt: passed.getTime() } };
|
||||
await logSessionEvent(db, s, "usage_limit_passed", { line: fresh });
|
||||
}
|
||||
// Fallback for limits that don't come through the StopFailure hook.
|
||||
if (fresh && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) {
|
||||
if (fresh && !passed && s.status !== "rate_limited" && s.watchState?.limitGen !== s.generation) {
|
||||
await patchWatch(db, s, { limitGen: s.generation });
|
||||
const line = fresh;
|
||||
log(`${label}: usage limit`);
|
||||
@ -473,7 +482,7 @@ async function rotateLimited(db: Db, s: SessionView, now: Date, log: (m: string)
|
||||
if (s.rotateReason) {
|
||||
await updateSession(db, s.id, { rotateReason: null });
|
||||
await logSessionEvent(db, s, "rotation_skipped", { reason: "limit", why: m("нет свободной подписки") });
|
||||
const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
await limitDelay(db, s, m("{who}: лимит, свободных подписок нет — продолжит в {time} сам.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), time: at }), { now, log });
|
||||
}
|
||||
return false;
|
||||
|
||||
@ -156,6 +156,99 @@ describe("Новая фраза Claude (PEP-166)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// PEP-300: 25.11.2026 three working subscriptions were marked «лимит» for a day. Claude Code waited
|
||||
// for the reset itself («set to continue automatically at 6:50pm»), went on at 18:50, and the
|
||||
// watchdog read the banner — still on the screen — at 18:51: «6:50pm» came out as tomorrow's reset.
|
||||
describe("PEP-300: плашка лимита, время на которой уже прошло", () => {
|
||||
const banner = "● Usage limit reached · set to continue automatically at 6:50pm";
|
||||
const codexDated = "You’ve hit your usage limit. Try again at Nov 18th, 2026 9:13 PM.";
|
||||
for (const [text, now, expected, why] of [
|
||||
[banner, "2026-11-25T18:51:36", "2026-11-25T18:50:00", "the live case: read 96 s after the reset"],
|
||||
[banner, "2026-11-25T18:30:00", null, "still ahead — a limit"],
|
||||
[banner, "2026-11-25T22:49:00", "2026-11-25T18:50:00", "inside the window"],
|
||||
[banner, "2026-11-25T22:51:00", null, "later than the window: the next day's reset, as before"],
|
||||
["You've hit your 5-hour limit · resets 11:50pm (UTC)", "2026-11-26T00:01:00", "2026-11-25T23:50:00", "just after midnight — yesterday's time"],
|
||||
["resets 1am", "2026-11-25T22:00:00", null, "across midnight, ahead"],
|
||||
[codexDated, "2026-11-19T10:00:00", "2026-11-18T21:13:00", "a full date in the past"],
|
||||
[codexDated, "2026-11-18T10:00:00", null, "a full date ahead"],
|
||||
["resets in 2h 15m", "2026-11-25T18:51:00", null, "a relative time is always ahead"],
|
||||
["limit reached", "2026-11-25T18:51:00", null, "no time in the text"],
|
||||
] as const) {
|
||||
test(`Прошло ли время сброса: «${text.slice(0, 48)}» в ${now.slice(11, 16)} — ${why}`, () => {
|
||||
assert.equal(runner.passedReset(text, at(now))?.getTime() ?? null, expected ? at(expected).getTime() : null);
|
||||
});
|
||||
}
|
||||
|
||||
/** «6:50pm» for a moment — the way Claude Code prints a clock time. */
|
||||
const clock = (d: Date) => d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }).replace(/\s/g, "").toLowerCase();
|
||||
const count = (sid: number, type: string) => (db.$client.prepare("SELECT count(*) AS n FROM events WHERE session_id = ? AND type = ?").get(sid, type) as { n: number }).n;
|
||||
const workingSub = async (name: string) => {
|
||||
const sub = await core.createSubscription(db, { provider: "claude", name, authKind: "oauth" });
|
||||
await core.updateSubscription(db, sub.id, { status: "active" });
|
||||
return sub;
|
||||
};
|
||||
/** A live agent of the mock with `text` on its screen, running on a subscription. */
|
||||
const agentWith = async (text: string, name: string) => {
|
||||
const p = await project({ turns: [[{ say: text }, { say: "Продолжил после сброса лимита." }]] });
|
||||
const sub = await workingSub(name);
|
||||
const sid = await p.start();
|
||||
db.$client.prepare("UPDATE sessions SET subscription_id = ? WHERE id = ?").run(sub.id, sid);
|
||||
await waitFor("banner on screen", async () => (await runner.tmux.capturePane((await sess(sid)).tmuxName)).includes("Usage limit reached"));
|
||||
return { p, sid, sub };
|
||||
};
|
||||
|
||||
test("Claude сам дождался сброса и продолжил: подписка не помечена, агент не остановлен", async () => {
|
||||
const sent = await superadmin();
|
||||
const reset = new Date(Date.now() - 60_000);
|
||||
reset.setSeconds(0, 0);
|
||||
const { sid, sub } = await agentWith(`● Usage limit reached · set to continue automatically at ${clock(reset)}`, "Claude — mock-300 прошло");
|
||||
await tick();
|
||||
const s = await sess(sid);
|
||||
assert.notEqual(s.status, "rate_limited", "the agent is not stopped");
|
||||
assert.equal(s.resumeAt, null, "nothing to continue later");
|
||||
const after = await core.getSubscription(db, sub.id);
|
||||
assert.equal(after.status, "active", "the subscription is not marked «лимит» for a day");
|
||||
assert.equal(after.limitedUntil, null);
|
||||
assert.equal(count(sid, "usage_limit"), 0, "not a limit");
|
||||
assert.equal(count(sid, "usage_limit_passed"), 1, "the journal says what was seen");
|
||||
assert.equal(s.watchState?.limitGen, undefined, "the generation's fallback is kept for a real limit");
|
||||
|
||||
await tick();
|
||||
assert.equal(count(sid, "usage_limit_passed"), 1, "noted once, not on every pass");
|
||||
assert.equal((await sent()).length, 0, "nobody is told about a limit that is over");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("Время на плашке ещё впереди — лимит записан до этого времени, как раньше", async () => {
|
||||
const reset = new Date(Date.now() + 2 * 3_600_000);
|
||||
reset.setSeconds(0, 0);
|
||||
const { sid, sub } = await agentWith(`● Usage limit reached · set to continue automatically at ${clock(reset)}`, "Claude — mock-300 впереди");
|
||||
await tick();
|
||||
assert.equal((await sess(sid)).status, "rate_limited");
|
||||
const after = await core.getSubscription(db, sub.id);
|
||||
assert.equal(after.status, "limited");
|
||||
assert.equal(after.limitedUntil?.getTime(), reset.getTime(), "until the time on the banner, not a day later");
|
||||
assert.equal(count(sid, "usage_limit"), 1);
|
||||
assert.equal(count(sid, "usage_limit_passed"), 0);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("Время в сообщении о лимите — в поясе платформы, а не сервера", async () => {
|
||||
const prev = process.env.PEPPA_TZ;
|
||||
process.env.PEPPA_TZ = "Pacific/Kiritimati"; // UTC+14, no DST: never the zone the tests run in
|
||||
try {
|
||||
const p = await project({ turns: [] });
|
||||
const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id })).id;
|
||||
const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached · continuing automatically at 6pm", at("2026-11-16T13:34:00"));
|
||||
const want = (await sess(sid)).resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: "Pacific/Kiritimati" });
|
||||
assert.match(text ?? "", new RegExp(`продолжит в ${want} сам`), "the people of the platform read their own time");
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.PEPPA_TZ;
|
||||
else process.env.PEPPA_TZ = prev;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Отключение", () => {
|
||||
test("Выключено", async () => {
|
||||
const p = await project({ turns: [] });
|
||||
|
||||
@ -244,7 +244,9 @@ describe("Уборка давних waiting_input", () => {
|
||||
|
||||
describe("Состояние вачдога в БД", () => {
|
||||
test("Рестарт вачдога не повторяет сообщение о лимите", async () => {
|
||||
const p = await project({ turns: [[{ say: "You've hit your limit · resets 5pm" }]] });
|
||||
// PEP-300: a time still ahead whenever the test runs — a banner whose time has passed is an old one, not a limit.
|
||||
const ahead = new Date(Date.now() + 2 * 3_600_000).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }).replace(/\s/g, "").toLowerCase();
|
||||
const p = await project({ turns: [[{ say: `You've hit your limit · resets ${ahead}` }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("turn 0", (e) => e.ev === "prompt");
|
||||
await waitFor("banner on screen", async () => (await runner.tmux.capturePane((await sess(sid)).tmuxName)).includes("hit your limit"));
|
||||
|
||||
Loading…
Reference in New Issue
Block a user