fix(runner): address review findings for output bounds, key rotation, defaults, and generated uploads

This commit is contained in:
yiling
2026-11-14 15:00:38 +08:00
parent c56ad79213
commit a01bcc42ed
13 changed files with 541 additions and 116 deletions
+17 -7
View File
@@ -1,5 +1,5 @@
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { runnerService, type RunnerSocket } from '@shumai/core/src/runner'
import { hashRunnerKey, runnerService, type RunnerSocket } from '@shumai/core/src/runner'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -58,10 +58,10 @@ describe('Concurrent Runner Sessions', () => {
const team = await prisma.team.create({
data: { name: 'Concurrent Runner Team' },
})
const { runner } = await runnerService.createRunner(team.id, { name: 'Shared Runner' })
const { runner, key } = await runnerService.createRunner(team.id, { name: 'Shared Runner' })
const conn = createMockWs()
await runnerService.registerConnection(
{ id: runner.id, teamId: team.id, name: runner.name },
{ id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
@@ -172,11 +172,11 @@ describe('Concurrent Runner Sessions', () => {
const team = await prisma.team.create({
data: { name: 'Multi Runner Team' },
})
const { runner: defaultRunner } = await runnerService.createRunner(team.id, {
const { runner: defaultRunner, key: defaultKey } = await runnerService.createRunner(team.id, {
name: 'Default Runner',
isDefault: true,
})
const { runner: gpuRunner } = await runnerService.createRunner(team.id, {
const { runner: gpuRunner, key: gpuKey } = await runnerService.createRunner(team.id, {
name: 'GPU Runner',
isDefault: false,
})
@@ -184,11 +184,21 @@ describe('Concurrent Runner Sessions', () => {
const defaultConn = createMockWs()
const gpuConn = createMockWs()
await runnerService.registerConnection(
{ id: defaultRunner.id, teamId: team.id, name: defaultRunner.name },
{
id: defaultRunner.id,
teamId: team.id,
name: defaultRunner.name,
keyHash: hashRunnerKey(defaultKey),
},
defaultConn.ws,
)
await runnerService.registerConnection(
{ id: gpuRunner.id, teamId: team.id, name: gpuRunner.name },
{
id: gpuRunner.id,
teamId: team.id,
name: gpuRunner.name,
keyHash: hashRunnerKey(gpuKey),
},
gpuConn.ws,
)
@@ -181,13 +181,17 @@ describe('create_file and create_version agent tools', () => {
})
})
it('creates a file directly from a server-staged .pi/generated/ path without using a runner', async () => {
it('falls back to temporary S3 storage when no runner is configured for .pi/generated/', async () => {
vi.mocked(runnerService.requireOnlineRunner).mockRejectedValueOnce(
new Error('No Runner is configured for this team.'),
)
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '.pi/generated/gen123/poster.png',
} as never)
expect(runnerService.requireOnlineRunner).not.toHaveBeenCalled()
expect(runnerService.statOnRunner).not.toHaveBeenCalled()
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/poster.png')
expect(s3Service.putObject).toHaveBeenCalled()
expect(assetService.createFile).toHaveBeenCalledWith(
@@ -198,6 +202,69 @@ describe('create_file and create_version agent tools', () => {
)
})
it('falls back to temporary S3 storage when .pi/generated/ file is not staged on the online runner', async () => {
vi.mocked(runnerService.statOnRunner).mockResolvedValueOnce({
type: 'file.stat.result',
executionId: 'exec-stat-missing',
ok: true,
exists: false,
})
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '.pi/generated/gen123/unstaged.png',
} as never)
expect(runnerService.statOnRunner).toHaveBeenCalledWith(
'runner-1',
'.pi/generated/gen123/unstaged.png',
)
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/unstaged.png')
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
})
it('prefers uploading edited or newly created .pi/generated/ files from the runner over S3', async () => {
vi.mocked(s3Service.headObject).mockImplementation(async (_bucket, key) => {
if (key === 'temp/generated/gen123/edited.png') {
throw new Error('NotFound')
}
return {
key,
size: 17,
lastModified: new Date(),
contentType: 'text/markdown',
eTag: '',
}
})
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: '.pi/generated/gen123/edited.png',
} as never)
expect(runnerService.statOnRunner).toHaveBeenCalledWith(
'runner-1',
'.pi/generated/gen123/edited.png',
)
expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', {
srcPath: '.pi/generated/gen123/edited.png',
url: 'https://storage.example/upload',
contentType: 'text/markdown',
})
expect(s3Service.getObject).not.toHaveBeenCalled()
})
it('reads explicit temp/generated/ paths directly from S3 without touching the runner', async () => {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
path: 'temp/generated/gen123/direct.png',
} as never)
expect(runnerService.requireOnlineRunner).not.toHaveBeenCalled()
expect(runnerService.statOnRunner).not.toHaveBeenCalled()
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/direct.png')
})
it('creates a text file from name and content', async () => {
await invokeTool(tool('create_file'), 'call-1', {
parent: 'folder-1',
@@ -32,16 +32,19 @@ function setCreationMetadata(schema: ToolParametersSchema, options: AgentToolOpt
}
}
function resolveGeneratedStorageKey(rawPath: string): string | null {
function resolveGeneratedStorageKey(rawPath: string): {
storageKey: string
explicitStorageRef: boolean
} | null {
const cleaned = rawPath.replace(/\\/g, '/').replace(/^\.\//, '')
if (cleaned.includes('..')) return null
if (cleaned.startsWith('.pi/generated/')) {
const rest = cleaned.slice('.pi/generated/'.length)
return rest ? `temp/generated/${rest}` : null
return rest ? { storageKey: `temp/generated/${rest}`, explicitStorageRef: false } : null
}
if (cleaned.startsWith('temp/generated/')) {
const rest = cleaned.slice('temp/generated/'.length)
return rest ? cleaned : null
return rest ? { storageKey: cleaned, explicitStorageRef: true } : null
}
return null
}
@@ -74,6 +77,24 @@ async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise<strin
return runner.id
}
async function resolveStorageGeneratedSource(storageKey: string): Promise<{
kind: 'generated'
storageKey: string
name: string
contentType: string
} | null> {
const head = await s3Service.headObject(storageBucket(), storageKey).catch(() => null)
if (!head) {
return null
}
const name = path.posix.basename(storageKey)
const contentType =
head.contentType && head.contentType !== 'application/octet-stream'
? head.contentType
: getFileMimeType(null, name)
return { kind: 'generated', storageKey, name, contentType }
}
async function resolvePathSource(
localPath: string,
ctx?: AgentOperationContext,
@@ -81,18 +102,13 @@ async function resolvePathSource(
| { kind: 'generated'; storageKey: string; name: string; contentType: string }
| { kind: 'runner'; runnerId: string; runnerPath: string; name: string; contentType: string }
> {
const generatedKey = resolveGeneratedStorageKey(localPath)
if (generatedKey) {
const head = await s3Service.headObject(storageBucket(), generatedKey).catch(() => null)
if (!head) {
const generatedRef = resolveGeneratedStorageKey(localPath)
if (generatedRef?.explicitStorageRef) {
const source = await resolveStorageGeneratedSource(generatedRef.storageKey)
if (!source) {
throw new Error(`Local file not found at path: ${localPath}`)
}
const name = path.posix.basename(generatedKey)
const contentType =
head.contentType && head.contentType !== 'application/octet-stream'
? head.contentType
: getFileMimeType(null, name)
return { kind: 'generated', storageKey: generatedKey, name, contentType }
return source
}
const runnerPath = normalizeRunnerPath(localPath)
@@ -100,17 +116,37 @@ async function resolvePathSource(
throw new Error(`Local file not found at path: ${localPath}`)
}
const runnerId = await resolveTargetRunnerId(ctx)
const stat = await runnerService.statOnRunner(runnerId, runnerPath)
if (!stat.ok || !stat.exists || stat.isFile === false) {
throw new Error(`Local file not found at path: ${localPath}`)
let runnerError: unknown
try {
const runnerId = await resolveTargetRunnerId(ctx)
const stat = await runnerService.statOnRunner(runnerId, runnerPath)
if (stat.ok && stat.exists && stat.isFile !== false) {
const name = path.posix.basename(runnerPath)
const contentType =
stat.mimeType && stat.mimeType !== 'application/octet-stream'
? stat.mimeType
: getFileMimeType(null, name)
return { kind: 'runner', runnerId, runnerPath, name, contentType }
}
} catch (err) {
if (!generatedRef) {
throw err
}
runnerError = err
}
const name = path.posix.basename(runnerPath)
const contentType =
stat.mimeType && stat.mimeType !== 'application/octet-stream'
? stat.mimeType
: getFileMimeType(null, name)
return { kind: 'runner', runnerId, runnerPath, name, contentType }
// Fallback for unstaged generated files stored in temporary S3
if (generatedRef) {
const source = await resolveStorageGeneratedSource(generatedRef.storageKey)
if (source) {
return source
}
if (runnerError) {
throw runnerError
}
}
throw new Error(`Local file not found at path: ${localPath}`)
}
/**
@@ -92,6 +92,7 @@ describe('createSandboxedBashTool', () => {
expect.objectContaining({
command: 'echo hello',
env: { TEST_ENV: 'test-value' },
collectOutput: false,
}),
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
@@ -184,6 +184,7 @@ export const createSandboxedBashTool = (
timeoutSec: timeout,
env: skillEnvs,
signal,
collectOutput: false,
onOutput: (chunk) => handleData(Buffer.from(chunk, 'utf-8')),
})
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest'
import { OutputAccumulator } from './output-accumulator'
describe('OutputAccumulator', () => {
it('does not accumulate rawChunks in memory when disableTempFile is true', () => {
const acc = new OutputAccumulator({
maxBytes: 1024,
maxLines: 50,
disableTempFile: true,
})
const chunk = Buffer.from(`${'x'.repeat(2047)}\n`, 'utf-8')
for (let i = 0; i < 256; i++) {
acc.append(chunk)
}
acc.finish()
const internal = acc as unknown as { rawChunks: Buffer[]; tailBytes: number }
expect(internal.rawChunks).toEqual([])
expect(internal.tailBytes).toBeLessThanOrEqual(1024 * 4)
const snapshot = acc.snapshot({ persistIfTruncated: false })
expect(snapshot.truncation.truncated).toBe(true)
expect(snapshot.fullOutputPath).toBeUndefined()
expect(Buffer.byteLength(snapshot.content, 'utf-8')).toBeLessThanOrEqual(1024)
})
})
@@ -73,7 +73,7 @@ export class OutputAccumulator {
if (this.tempFileStream || this.shouldUseTempFile()) {
this.ensureTempFile()
this.tempFileStream?.write(data)
} else if (data.length > 0) {
} else if (!this.disableTempFile && data.length > 0) {
this.rawChunks.push(data)
}
}