feat(pi): complete RPC parity, native steer, and history controls (#1353)

* feat(pi): complete RPC interaction parity

* feat(pi): integrate native conversation history

* fix(pi): harden RPC lifecycle boundaries

* fix(pi): address review lifecycle and upload boundaries

* fix(pi): release history transaction on rollback deadline

* fix(pi): isolate preflight and timed-out mutations

* fix(pi): preserve retry and editor boundaries

* fix(pi): disable unavailable history synchronization

* fix(pi): gate fallback readiness on history baseline

* fix(pi): bind uploads and retire extension requests

* fix(pi): preserve canceled and legacy stream boundaries

* fix(pi): preserve native fork runtime state

* fix(pi): persist dialogs and preserve select values

* fix(pi): keep upload authorization path-stable

* feat(pi): preserve native steer semantics

Route ordinary sends during an active Pi main turn through native steer while keeping explicit queue delivery on the existing composer gestures. Persist the delivery contract across Hub replay and Web retries, and guard stale steer dispatch with streaming generations and ordered prompt fallback.

* fix(pi): queue deferred steer deliveries

Keep native steer only for the initial live emit. Reconnect replay, CLI backfill, clear-gate release, and mature delivery now downgrade turn-scoped steer intent to the durable HAPI queue without mutating stored provenance.

* fix(pi): retain abort guard through preflight miss

Treat an immediate no-active abort rejection as a possible async-preflight race. Keep the existing abort boundary alive so a late agent_start receives the compensating abort before queued work is released.

* fix(pi): queue stale steer retries

A failed send no longer reuses turn-scoped steer intent after its original Pi generation is lost. Text restoration, attachment retry, and legacy retry provenance all enter the durable HAPI queue while fresh ordinary sends retain native steer behavior.

* fix(pi): invalidate rejected abort generation

After a no-active preflight abort waits through late-start compensation, mark the target stream idle while the runtime mutation lease is still held. Waiting native steers therefore fall back instead of entering the aborted generation.

* fix(pi): queue idempotent steer retries

Track whether a localId insert created a new row. Initial inserts may retain live Pi steer, while duplicate-localId retries deliver a queue-safe view of the stored row without overwriting its original provenance.

* fix(pi): sync command-only history before fallback

Read the Pi append log before retiring a successful prompt that produced no agent lifecycle. Preserve FIFO history associations across missing entry events, and fail the wrapper closed if that mandatory synchronization cannot be completed.
This commit is contained in:
KorenKrita
2026-08-04 11:01:00 +08:00
committed by GitHub
parent a03bad15e3
commit 021b5c194b
74 changed files with 8504 additions and 653 deletions
@@ -0,0 +1,54 @@
import { mkdtemp, mkdir, rm, truncate, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { MAX_UPLOAD_BYTES } from './attachmentLimits';
import { readBoundedAttachmentFile } from './attachmentFile';
describe('readBoundedAttachmentFile', () => {
const directories: string[] = [];
afterEach(async () => {
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })));
});
async function createTemporaryDirectory(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), 'hapi-attachment-file-'));
directories.push(directory);
return directory;
}
it('reads a small regular file', async () => {
const directory = await createTemporaryDirectory();
const path = join(directory, 'image.png');
await writeFile(path, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
await expect(readBoundedAttachmentFile(path)).resolves.toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47]));
});
it('rejects a directory', async () => {
const directory = await createTemporaryDirectory();
const path = join(directory, 'not-a-file');
await mkdir(path);
await expect(readBoundedAttachmentFile(path)).rejects.toThrow('Attachment must be a regular file');
});
it('rejects an oversized sparse file before loading it into memory', async () => {
const directory = await createTemporaryDirectory();
const path = join(directory, 'too-large-sparse.png');
await writeFile(path, '');
await truncate(path, MAX_UPLOAD_BYTES + 1);
await expect(readBoundedAttachmentFile(path)).rejects.toThrow('Attachment file too large (max 50MB)');
});
it('enforces a caller-provided remaining aggregate budget before reading', async () => {
const directory = await createTemporaryDirectory();
const path = join(directory, 'second-image.png');
await writeFile(path, Buffer.from([1, 2, 3, 4]));
await expect(readBoundedAttachmentFile(path, 3)).rejects.toThrow('remaining image budget');
await expect(readBoundedAttachmentFile(path, 0)).rejects.toThrow('remaining image budget');
});
});
+63
View File
@@ -0,0 +1,63 @@
import { constants } from 'node:fs';
import { open } from 'node:fs/promises';
import { MAX_UPLOAD_BYTES } from './attachmentLimits';
import type { UploadFileIdentity } from './handlers/uploads';
/**
* Reads a user attachment through one file handle with the upload byte limit.
*
* The caller is responsible for authorizing the attachment path for its
* session. This helper intentionally validates only that the opened target is
* a regular file and that its actual bytes fit the shared upload limit; it does
* not infer ownership from an arbitrary filesystem path.
*/
export async function readBoundedAttachmentFile(
path: string,
maxBytes: number = MAX_UPLOAD_BYTES,
authorizeOpenedFile?: (identity: UploadFileIdentity) => boolean,
): Promise<Buffer> {
const byteLimit = Math.min(MAX_UPLOAD_BYTES, Math.max(0, Math.floor(maxBytes)));
if (byteLimit === 0) {
throw new Error('Attachment exceeds the remaining image budget');
}
// The caller passes the exact registered upload path. O_NOFOLLOW closes the
// final replacement window on POSIX if it is swapped to a symlink
// before open; Windows falls back to its normal read-only flag.
const flags = process.platform === 'win32'
? 'r'
: constants.O_RDONLY | constants.O_NOFOLLOW;
const handle = await open(path, flags);
try {
// fstat and the subsequent read share this handle so a path replacement
// cannot change the object after its type/size check.
const stats = await handle.stat();
if (authorizeOpenedFile && !authorizeOpenedFile(stats)) {
throw new Error('invalid upload path');
}
if (!stats.isFile()) {
throw new Error('Attachment must be a regular file');
}
if (stats.size > byteLimit) {
throw new Error(byteLimit === MAX_UPLOAD_BYTES
? 'Attachment file too large (max 50MB)'
: 'Attachment exceeds the remaining image budget');
}
// Read into one bounded allocation. The extra sentinel byte detects a
// file that grows after fstat without retaining chunk buffers plus an
// equally large Buffer.concat copy at the 50 MiB boundary.
const buffer = Buffer.allocUnsafe(stats.size + 1);
let bytesRead = 0;
while (bytesRead < buffer.length) {
const result = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead);
if (result.bytesRead === 0) break;
bytesRead += result.bytesRead;
}
if (bytesRead > stats.size) {
throw new Error('Attachment changed while it was being read');
}
return buffer.subarray(0, bytesRead);
} finally {
await handle.close();
}
}
@@ -0,0 +1,2 @@
/** Maximum decoded bytes accepted for one HAPI upload or one Pi image batch. */
export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
@@ -0,0 +1,139 @@
import { basename, join } from 'node:path';
import { realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
import { describe, expect, it, vi } from 'vitest';
import { getHapiBlobsDir } from '@/constants/uploadPaths';
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
import { readBoundedAttachmentFile } from '../attachmentFile';
import { cleanupUploadDir, isAuthorizedUploadFile, isPathWithinUploadDir, registerUploadHandlers } from './uploads';
describe('isPathWithinUploadDir', () => {
it('accepts only paths under the matching session upload directory', () => {
const sessionId = 'session-allowed';
const ownUpload = join(getHapiBlobsDir(), `${sessionId}-random`, 'image.png');
const otherUpload = join(getHapiBlobsDir(), 'session-other-random', 'image.png');
expect(isPathWithinUploadDir(ownUpload, sessionId)).toBe(true);
expect(isPathWithinUploadDir(otherUpload, sessionId)).toBe(false);
expect(isPathWithinUploadDir('/etc/hosts', sessionId)).toBe(false);
});
it('binds authorization to the uploaded file identity, not only its path', async () => {
const handlers = new Map<string, (payload: any) => Promise<any>>();
registerUploadHandlers({
registerHandler: (method: string, handler: (payload: any) => Promise<any>) => handlers.set(method, handler),
} as never);
const sessionId = `session-identity-${Date.now()}`;
const upload = handlers.get(RPC_METHODS.UploadFile)!;
let path: string | null = null;
try {
const result = await upload({
sessionId,
filename: 'image.png',
mimeType: 'image/png',
content: Buffer.from([1, 2, 3, 4]).toString('base64'),
});
expect(result).toMatchObject({ success: true });
path = result.path;
const original = await stat(path!);
expect(isAuthorizedUploadFile(path!, sessionId, original)).toBe(true);
expect(isAuthorizedUploadFile(path!, 'another-session', original)).toBe(false);
// The lexical upload path can canonicalize differently (notably
// /var -> /private/var on Darwin). Authorization and opened-file
// identity deliberately use the exact registered path.
expect(await readBoundedAttachmentFile(
path!,
50 * 1024 * 1024,
(identity) => isAuthorizedUploadFile(path!, sessionId, identity),
)).toEqual(Buffer.from([1, 2, 3, 4]));
expect(typeof await realpath(path!)).toBe('string');
const replacementPath = `${path!}.replacement`;
await writeFile(replacementPath, Buffer.from([5, 6, 7, 8]));
const distinctReplacement = await stat(replacementPath);
expect(`${distinctReplacement.dev}:${distinctReplacement.ino}`).not.toBe(`${original.dev}:${original.ino}`);
await rm(path!, { force: true });
await rename(replacementPath, path!);
const replacement = await stat(path!);
expect(isAuthorizedUploadFile(path!, sessionId, replacement)).toBe(false);
} finally {
await cleanupUploadDir(sessionId);
}
});
it('supports concurrent uploads with the same filename using distinct exclusive paths', async () => {
const handlers = new Map<string, (payload: any) => Promise<any>>();
registerUploadHandlers({
registerHandler: (method: string, handler: (payload: any) => Promise<any>) => handlers.set(method, handler),
} as never);
const sessionId = `session-concurrent-${Date.now()}`;
const upload = handlers.get(RPC_METHODS.UploadFile)!;
try {
const payload = {
sessionId,
filename: 'screenshot.png',
mimeType: 'image/png',
content: Buffer.from([1, 2, 3, 4]).toString('base64'),
};
const [first, second] = await Promise.all([upload(payload), upload(payload)]);
expect(first).toMatchObject({ success: true });
expect(second).toMatchObject({ success: true });
expect(first.path).not.toBe(second.path);
expect(isAuthorizedUploadFile(first.path, sessionId, await stat(first.path))).toBe(true);
expect(isAuthorizedUploadFile(second.path, sessionId, await stat(second.path))).toBe(true);
} finally {
await cleanupUploadDir(sessionId);
}
});
it('keeps long ASCII and Unicode filename components within 255 UTF-8 bytes', async () => {
const handlers = new Map<string, (payload: any) => Promise<any>>();
registerUploadHandlers({
registerHandler: (method: string, handler: (payload: any) => Promise<any>) => handlers.set(method, handler),
} as never);
const sessionId = `session-long-name-${Date.now()}`;
const upload = handlers.get(RPC_METHODS.UploadFile)!;
try {
for (const filename of [`${'a'.repeat(300)}.png`, `${'😀'.repeat(300)}.png`]) {
const result = await upload({
sessionId,
filename,
mimeType: 'image/png',
content: Buffer.from([1]).toString('base64'),
});
expect(result).toMatchObject({ success: true });
expect(Buffer.byteLength(basename(result.path))).toBeLessThanOrEqual(255);
expect(basename(result.path)).toMatch(/\.png$/);
}
} finally {
await cleanupUploadDir(sessionId);
}
});
it('preserves an extension that exactly fills the remaining component budget', async () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const handlers = new Map<string, (payload: any) => Promise<any>>();
registerUploadHandlers({
registerHandler: (method: string, handler: (payload: any) => Promise<any>) => handlers.set(method, handler),
} as never);
const sessionId = 'session-exact-extension';
const upload = handlers.get(RPC_METHODS.UploadFile)!;
// At time 0 the prefix is `0-<36-byte UUID>-` (39 bytes), leaving 216.
const extension = `.${'e'.repeat(215)}`;
try {
const result = await upload({
sessionId,
filename: `x${extension}`,
mimeType: 'application/octet-stream',
content: Buffer.from([1]).toString('base64'),
});
expect(result).toMatchObject({ success: true });
expect(Buffer.byteLength(basename(result.path))).toBe(255);
expect(basename(result.path).endsWith(extension)).toBe(true);
} finally {
vi.useRealTimers();
await cleanupUploadDir(sessionId);
}
});
});
+76 -11
View File
@@ -1,12 +1,14 @@
import { logger } from '@/ui/logger'
import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises'
import { join, resolve, sep } from 'path'
import { randomUUID } from 'node:crypto'
import { mkdir, mkdtemp, open, rm } from 'fs/promises'
import { extname, join, resolve, sep } from 'path'
import { rmSync } from 'node:fs'
import type { DeleteUploadResponse, UploadFileResponse } from '@hapi/protocol/apiTypes'
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
import { getErrorMessage, rpcError } from '../rpcResponses'
import { getHapiBlobsDir } from '@/constants/uploadPaths'
import { MAX_UPLOAD_BYTES } from '../attachmentLimits'
interface UploadFileRequest {
sessionId?: string
@@ -21,23 +23,56 @@ interface DeleteUploadRequest {
}
const uploadDirs = new Map<string, string>()
const uploadFileIdentities = new Map<string, Map<string, string>>()
const uploadDirPromises = new Map<string, Promise<string>>()
const uploadDirCleanupRequested = new Set<string>()
let cleanupRegistered = false
const MAX_UPLOAD_BYTES = 50 * 1024 * 1024
const MAX_FILENAME_COMPONENT_BYTES = 255
export type UploadFileIdentity = { dev: number; ino: number }
function uploadIdentityKey(identity: UploadFileIdentity): string {
return `${identity.dev}:${identity.ino}`
}
export function isAuthorizedUploadFile(path: string, sessionId: string | undefined, identity: UploadFileIdentity): boolean {
return uploadFileIdentities.get(getSessionKey(sessionId))?.get(resolve(path)) === uploadIdentityKey(identity)
}
function sanitizeFilename(filename: string): string {
// Remove path separators and limit length
// Remove path separators; byte-safe length fitting happens after the
// unique prefix is known so the original extension can be preserved.
const sanitized = filename
.replace(/[/\\]/g, '_')
.replace(/\.\./g, '_')
.replace(/\s+/g, '_')
.slice(0, 255)
// If filename is empty after sanitization, use a default
return sanitized || 'upload'
}
function truncateUtf8(text: string, maxBytes: number): string {
let result = ''
let bytes = 0
for (const character of text) {
const characterBytes = Buffer.byteLength(character)
if (bytes + characterBytes > maxBytes) break
result += character
bytes += characterBytes
}
return result
}
function fitFilenameToBytes(filename: string, maxBytes: number): string {
const extension = extname(filename)
const extensionBytes = Buffer.byteLength(extension)
if (extension && extensionBytes <= maxBytes) {
const stem = filename.slice(0, -extension.length)
return `${truncateUtf8(stem, maxBytes - extensionBytes)}${extension}`
}
return truncateUtf8(filename, maxBytes) || 'upload'
}
function getSessionKey(sessionId?: string): string {
const trimmed = sessionId?.trim()
return trimmed ? trimmed : 'unknown'
@@ -62,7 +97,7 @@ async function getOrCreateUploadDir(sessionId?: string): Promise<string> {
return await inflight
}
const safeKey = sanitizeFilename(sessionKey)
const safeKey = fitFilenameToBytes(sanitizeFilename(sessionKey), 120)
const creation = (async () => {
try {
const blobsDir = getHapiBlobsDir()
@@ -102,6 +137,7 @@ export async function cleanupUploadDir(sessionId?: string): Promise<void> {
const dir = uploadDirs.get(sessionKey)
uploadDirs.delete(sessionKey)
uploadFileIdentities.delete(sessionKey)
uploadDirPromises.delete(sessionKey)
if (!dir) {
@@ -121,6 +157,7 @@ export async function cleanupUploadDir(sessionId?: string): Promise<void> {
function cleanupUploadDirsSync(): void {
const dirs = Array.from(uploadDirs.values())
uploadDirs.clear()
uploadFileIdentities.clear()
uploadDirPromises.clear()
uploadDirCleanupRequested.clear()
@@ -133,7 +170,7 @@ function cleanupUploadDirsSync(): void {
}
}
function isPathWithinUploadDir(path: string, sessionId?: string): boolean {
export function isPathWithinUploadDir(path: string, sessionId?: string): boolean {
const sessionKey = getSessionKey(sessionId)
const resolvedPath = resolve(path)
const activeDir = uploadDirs.get(sessionKey)
@@ -143,7 +180,7 @@ function isPathWithinUploadDir(path: string, sessionId?: string): boolean {
return resolvedPath.startsWith(dirPrefix)
}
const safeKey = sanitizeFilename(sessionKey)
const safeKey = fitFilenameToBytes(sanitizeFilename(sessionKey), 120)
const resolvedPrefix = resolve(getHapiBlobsDir(), `${safeKey}-`)
return resolvedPath.startsWith(resolvedPrefix)
}
@@ -174,9 +211,15 @@ export function registerUploadHandlers(rpcHandlerManager: RpcHandlerManager): vo
const dir = await getOrCreateUploadDir(data.sessionId)
const sanitizedFilename = sanitizeFilename(data.filename)
// Add timestamp to avoid collisions
// Combine a readable timestamp with a random suffix so concurrent
// uploads of the same filename remain compatible with exclusive create.
const timestamp = Date.now()
const uniqueFilename = `${timestamp}-${sanitizedFilename}`
const prefix = `${timestamp}-${randomUUID()}-`
const boundedFilename = fitFilenameToBytes(
sanitizedFilename,
MAX_FILENAME_COMPONENT_BYTES - Buffer.byteLength(prefix),
)
const uniqueFilename = `${prefix}${boundedFilename}`
const filePath = join(dir, uniqueFilename)
// Decode base64 content and write to file
@@ -184,7 +227,28 @@ export function registerUploadHandlers(rpcHandlerManager: RpcHandlerManager): vo
if (buffer.length > MAX_UPLOAD_BYTES) {
return rpcError('File too large (max 50MB)')
}
await writeFile(filePath, buffer)
const file = await open(filePath, 'wx', 0o600)
let operationError: unknown
try {
await file.writeFile(buffer)
const info = await file.stat()
const files = uploadFileIdentities.get(getSessionKey(data.sessionId)) ?? new Map<string, string>()
files.set(resolve(filePath), uploadIdentityKey(info))
uploadFileIdentities.set(getSessionKey(data.sessionId), files)
} catch (error) {
operationError = error
}
let closeError: unknown
try {
await file.close()
} catch (error) {
closeError = error
}
if (operationError || closeError) {
uploadFileIdentities.get(getSessionKey(data.sessionId))?.delete(resolve(filePath))
await rm(filePath, { force: true }).catch(() => {})
throw operationError ?? closeError
}
logger.debug('File uploaded successfully:', filePath)
return { success: true, path: filePath }
@@ -206,6 +270,7 @@ export function registerUploadHandlers(rpcHandlerManager: RpcHandlerManager): vo
try {
await rm(path, { force: true })
uploadFileIdentities.get(getSessionKey(data.sessionId))?.delete(resolve(path))
return { success: true }
} catch (error) {
logger.debug('Failed to delete upload file:', error)