chore: test deploy snapshot

This commit is contained in:
2026-05-28 12:45:36 +09:00
parent 983887dc05
commit 82c46f4be4
21 changed files with 4163 additions and 449 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,18 @@
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { resolvePromptFollowupMode, resolveStaticContentType } from './chat.js';
import Fastify from 'fastify';
import { registerChatRoutes, resolvePromptFollowupMode, resolveStaticContentType } from './chat.js';
const repoRoot = path.resolve(process.cwd(), '../../..');
async function removeSessionUploads(sessionId: string) {
await fs.rm(path.join(repoRoot, 'public', '.codex_chat', sessionId), {
recursive: true,
force: true,
});
}
test('resolveStaticContentType returns html content type for chat resource html files', () => {
assert.equal(resolveStaticContentType('/tmp/sample.html'), 'text/html; charset=utf-8');
@@ -18,3 +30,66 @@ test('resolvePromptFollowupMode defaults to queue and preserves direct mode', ()
assert.equal(resolvePromptFollowupMode('queue'), 'queue');
assert.equal(resolvePromptFollowupMode('direct'), 'direct');
});
test('chat attachments accept binary octet-stream uploads without base64 expansion', async () => {
const app = Fastify();
await registerChatRoutes(app);
const sessionId = `binary-upload-${Date.now()}`;
const payload = Buffer.alloc(829_627, 1);
try {
const response = await app.inject({
method: 'POST',
url: '/api/chat/attachments',
headers: {
'content-type': 'application/octet-stream',
'x-chat-attachment-session-id': sessionId,
'x-chat-attachment-file-name': encodeURIComponent('image.png'),
'x-chat-attachment-mime-type': encodeURIComponent('image/png'),
},
payload,
});
assert.equal(response.statusCode, 200);
const body = response.json() as { ok: boolean; item: { path: string; size: number; mimeType: string } };
assert.equal(body.ok, true);
assert.equal(body.item.size, payload.byteLength);
assert.equal(body.item.mimeType, 'image/png');
assert.match(body.item.path, new RegExp(`^public/\\.codex_chat/${sessionId}/resource/uploads/.+image\\.png$`));
} finally {
await removeSessionUploads(sessionId);
await app.close();
}
});
test('chat attachments keep legacy JSON base64 uploads working', async () => {
const app = Fastify();
await registerChatRoutes(app);
const sessionId = `json-upload-${Date.now()}`;
try {
const response = await app.inject({
method: 'POST',
url: '/api/chat/attachments',
headers: {
'content-type': 'application/json',
},
payload: JSON.stringify({
sessionId,
fileName: 'note.txt',
mimeType: 'text/plain',
contentBase64: Buffer.from('hello', 'utf8').toString('base64'),
}),
});
assert.equal(response.statusCode, 200);
const body = response.json() as { ok: boolean; item: { size: number; mimeType: string; name: string } };
assert.equal(body.ok, true);
assert.equal(body.item.size, 5);
assert.equal(body.item.mimeType, 'text/plain');
assert.equal(body.item.name, 'note.txt');
} finally {
await removeSessionUploads(sessionId);
await app.close();
}
});

View File

@@ -55,6 +55,7 @@ import {
getChatShareTokenRoomMap,
resolveChatShareTokenRoomSessionIds,
upsertChatShareTokenRoomMap,
type ChatShareRoomLinkContext,
type ChatShareTokenRoomMapItem,
} from '../services/chat-share-room-map-service.js';
import { chatRuntimeService } from '../services/chat-runtime-service.js';
@@ -62,8 +63,8 @@ import { resolveMainProjectRoot } from '../services/main-project-root-service.js
import { openResourceManagerPreviewStream } from '../services/resource-manager-service.js';
import { getTokenSettingById, type TokenSettingRecord } from '../services/token-setting-config-service.js';
const CHAT_ATTACHMENT_ROUTE_BODY_LIMIT = 20 * 1024 * 1024;
const CHAT_ATTACHMENT_FILE_SIZE_LIMIT = 10 * 1024 * 1024;
const CHAT_ATTACHMENT_FILE_SIZE_LIMIT = 300 * 1024 * 1024;
const CHAT_ATTACHMENT_ROUTE_BODY_LIMIT = 450 * 1024 * 1024;
const CHAT_PUBLIC_ROUTE_PREFIX = '/.codex_chat/';
const CHAT_API_RESOURCE_ROUTE_PREFIX = '/api/chat/resources';
const CHAT_SHARE_ROUTE_PREFIX = '/api/chat/shares';
@@ -248,6 +249,7 @@ type ChatShareResolvedRoom = {
contextLabel: string | null;
contextDescription: string | null;
notifyOffline: boolean;
linkContext: ChatShareRoomLinkContext | null;
createdAt: string | null;
updatedAt: string | null;
};
@@ -265,6 +267,7 @@ function mapResolvedShareRoomItem(room: ChatShareTokenRoomMapItem): ChatShareRes
contextLabel: room.contextLabel,
contextDescription: room.contextDescription,
notifyOffline: room.notifyOffline,
linkContext: room.linkContext,
createdAt: room.createdAt,
updatedAt: room.conversationUpdatedAt ?? room.updatedAt,
};
@@ -292,6 +295,7 @@ async function resolveManagedShareRooms(args: {
contextLabel: null,
contextDescription: null,
notifyOffline: false,
linkContext: null,
createdAt: null,
updatedAt: null,
} satisfies ChatShareResolvedRoom,
@@ -319,6 +323,7 @@ async function resolveManagedShareRooms(args: {
contextLabel: null,
contextDescription: null,
notifyOffline: false,
linkContext: null,
createdAt: null,
updatedAt: null,
} satisfies ChatShareResolvedRoom,
@@ -370,6 +375,31 @@ function createManagedChatShareMessageIds() {
};
}
function normalizeShareRoomLinkContext(input: {
linkedSessionId?: string | null;
linkedRequestId?: string | null;
linkedTitle?: string | null;
linkedRequestPreview?: string | null;
linkedChatTypeLabel?: string | null;
}): ChatShareRoomLinkContext | null {
const sourceSessionId = input.linkedSessionId?.trim() || '';
const sourceRequestId = input.linkedRequestId?.trim() || '';
if (!sourceSessionId || !sourceRequestId) {
return null;
}
return {
kind: 'linked-session',
sourceSessionId,
sourceRequestId,
sourceTitle: input.linkedTitle?.trim() || null,
sourceRequestPreview: input.linkedRequestPreview?.trim() || null,
sourceChatTypeLabel: input.linkedChatTypeLabel?.trim() || null,
linkedAt: new Date().toISOString(),
};
}
function sortShareMessages(messages: ListedChatConversationMessage[]) {
return [...messages].sort((left, right) => {
if (left.id !== right.id) {
@@ -700,6 +730,21 @@ async function saveChatAttachmentFile(args: {
contentBase64: string;
}) {
const buffer = Buffer.from(args.contentBase64, 'base64');
return saveChatAttachmentBuffer({
sessionId: args.sessionId,
fileName: args.fileName,
mimeType: args.mimeType,
buffer,
});
}
async function saveChatAttachmentBuffer(args: {
sessionId: string;
fileName?: string;
mimeType?: string;
buffer: Buffer;
}) {
const buffer = args.buffer;
if (buffer.byteLength === 0) {
return {
@@ -713,7 +758,7 @@ async function saveChatAttachmentFile(args: {
return {
ok: false as const,
statusCode: 413,
message: '첨부 파일은 10MB 이하만 업로드할 수 있습니다.',
message: '첨부 파일은 300MB 이하만 업로드할 수 있습니다.',
};
}
@@ -746,6 +791,62 @@ async function saveChatAttachmentFile(args: {
};
}
const chatAttachmentJsonBodySchema = z.object({
sessionId: z.string().trim().min(1).max(120).regex(/^[A-Za-z0-9._:-]+$/),
fileName: z.string().trim().max(255).optional(),
mimeType: z.string().trim().max(200).optional(),
contentBase64: z.string().trim().min(1).max(CHAT_ATTACHMENT_ROUTE_BODY_LIMIT * 2),
});
const chatAttachmentShareJsonBodySchema = z.object({
sessionId: z.string().trim().min(1).max(120).optional().nullable(),
fileName: z.string().trim().max(255).optional(),
mimeType: z.string().trim().max(200).optional(),
contentBase64: z.string().trim().min(1).max(CHAT_ATTACHMENT_ROUTE_BODY_LIMIT * 2),
});
function decodeChatAttachmentHeaderValue(value: unknown) {
const normalized = String(Array.isArray(value) ? value[0] ?? '' : value ?? '').trim();
if (!normalized) {
return '';
}
try {
return decodeURIComponent(normalized);
} catch {
return normalized;
}
}
function parseChatAttachmentBinaryHeaders(headers: Record<string, unknown>, options?: { allowOptionalSessionId?: boolean }) {
const sessionId = decodeChatAttachmentHeaderValue(headers['x-chat-attachment-session-id']);
const fileName = decodeChatAttachmentHeaderValue(headers['x-chat-attachment-file-name']);
const mimeType = decodeChatAttachmentHeaderValue(headers['x-chat-attachment-mime-type']);
const schema = options?.allowOptionalSessionId
? z.object({
sessionId: z.string().trim().max(120).regex(/^[A-Za-z0-9._:-]+$/).optional().nullable(),
fileName: z.string().trim().max(255).optional(),
mimeType: z.string().trim().max(200).optional(),
})
: z.object({
sessionId: z.string().trim().min(1).max(120).regex(/^[A-Za-z0-9._:-]+$/),
fileName: z.string().trim().max(255).optional(),
mimeType: z.string().trim().max(200).optional(),
});
return schema.parse({
sessionId: sessionId || (options?.allowOptionalSessionId ? null : ''),
fileName: fileName || undefined,
mimeType: mimeType || undefined,
});
}
function isOctetStreamRequest(contentTypeHeader: unknown) {
const contentType = String(Array.isArray(contentTypeHeader) ? contentTypeHeader[0] ?? '' : contentTypeHeader ?? '').toLowerCase();
return contentType.startsWith('application/octet-stream');
}
function getClientIdHeader(request: { headers: Record<string, unknown> }) {
const raw = request.headers['x-client-id'];
return Array.isArray(raw) ? String(raw[0] ?? '').trim() : String(raw ?? '').trim();
@@ -1119,22 +1220,32 @@ async function buildChatShareSnapshot(
options?: {
sessionId?: string | null;
requestId?: string | null;
detailLevel?: 'full' | 'initial';
},
) {
const normalizedSessionId = options?.sessionId?.trim() || tokenPayload.sessionId.trim();
const detailLevel = options?.detailLevel === 'initial' ? 'initial' : 'full';
const conversation = await getChatConversation(normalizedSessionId, null);
if (!conversation) {
return null;
}
const [requests, messages] = await Promise.all([
listChatConversationRequests(normalizedSessionId, 1000),
listChatConversationMessages(normalizedSessionId, { limit: 1000 }),
]);
const isManagedShareRoomSession =
tokenPayload.kind === 'request-bundle' && normalizedSessionId.startsWith(MANAGED_CHAT_SHARE_SESSION_PREFIX);
const useInitialManagedShareRoomView = isManagedShareRoomSession && detailLevel === 'initial';
const detailPage = useInitialManagedShareRoomView
? await listChatConversationDetailPage(normalizedSessionId, { limit: 12 })
: null;
const [requests, messages] = detailPage
? [detailPage.requests, detailPage.messages]
: await Promise.all([
listChatConversationRequests(normalizedSessionId, 1000),
listChatConversationMessages(normalizedSessionId, { limit: 1000 }),
]);
const requestMap = new Map(requests.map((request) => [request.requestId.trim(), request] as const));
const targetRequestId = options?.requestId?.trim() || tokenPayload.requestId.trim();
const targetRequestFromStore = requestMap.get(targetRequestId) ?? null;
const targetRequestFromStore = requestMap.get(targetRequestId) ?? await getChatConversationRequest(normalizedSessionId, targetRequestId);
const placeholderTargetRequest = targetRequestFromStore ? null : buildManagedSharePlaceholderRequest(tokenPayload, conversation);
const targetRequest = targetRequestFromStore ?? placeholderTargetRequest;
@@ -1143,13 +1254,13 @@ async function buildChatShareSnapshot(
}
const childRequestIdsByParentRequestId = buildChildRequestIdsByParentRequestId(requests);
const isManagedShareRoomSession =
tokenPayload.kind === 'request-bundle' && normalizedSessionId.startsWith(MANAGED_CHAT_SHARE_SESSION_PREFIX);
const isManagedShareRoomPlaceholder = isManagedShareRoomSession && !targetRequestFromStore;
const rootRequestId = isManagedShareRoomPlaceholder
? targetRequestId
: resolveShareRootRequestId(targetRequestId, requestMap, tokenPayload.kind);
const scopeRequestIds = isManagedShareRoomSession
const scopeRequestIds = useInitialManagedShareRoomView
? requests.map((request) => request.requestId.trim()).filter(Boolean)
: isManagedShareRoomSession
? requests.map((request) => request.requestId.trim()).filter(Boolean)
: collectShareScopeRequestIds(rootRequestId, childRequestIdsByParentRequestId);
const scopeRequestIdSet = new Set(scopeRequestIds);
@@ -1158,9 +1269,11 @@ async function buildChatShareSnapshot(
const linkedRequestId = message.clientRequestId?.trim() || '';
return linkedRequestId ? scopeRequestIdSet.has(linkedRequestId) : false;
});
const activityLogs = await listChatConversationActivityLogsByRequestIds(normalizedSessionId, scopeRequestIds);
const activityLogs = useInitialManagedShareRoomView
? []
: await listChatConversationActivityLogsByRequestIds(normalizedSessionId, scopeRequestIds);
const promptTarget = tokenPayload.kind === 'prompt' ? resolvePromptTarget(scopedMessages, tokenPayload) : null;
const roomRequestCounts = buildRoomRequestCounts(requests, messages);
const roomRequestCounts = useInitialManagedShareRoomView ? undefined : buildRoomRequestCounts(requests, messages);
if (tokenPayload.kind === 'prompt' && !promptTarget) {
return null;
@@ -1176,6 +1289,7 @@ async function buildChatShareSnapshot(
activityLogs,
roomRequestCounts,
promptTarget,
detailLevel,
} satisfies {
conversation: Awaited<ReturnType<typeof getChatConversation>>;
rootRequestId: string;
@@ -1187,7 +1301,7 @@ async function buildChatShareSnapshot(
roomRequestCounts: {
processingCount: number;
unansweredCount: number;
};
} | undefined;
promptTarget:
| {
sourceMessageId: number;
@@ -1195,6 +1309,7 @@ async function buildChatShareSnapshot(
prompt: Extract<ListedChatConversationMessage['parts'][number], { type: 'prompt' }>;
}
| null;
detailLevel: 'full' | 'initial';
};
}
@@ -1509,6 +1624,10 @@ function hasManagedShareAllowedApp(
}
export async function registerChatRoutes(app: FastifyInstance) {
app.addContentTypeParser('application/octet-stream', { parseAs: 'buffer' }, (request, body, done) => {
done(null, body);
});
app.addHook('onSend', async (request, reply, payload) => {
if (request.method.toUpperCase() === 'GET' && request.url.startsWith('/api/chat')) {
applyChatApiNoStoreHeaders(reply);
@@ -1756,6 +1875,11 @@ export async function registerChatRoutes(app: FastifyInstance) {
title: z.string().trim().min(1).max(200),
requestBadgeLabel: z.string().trim().max(120).optional().nullable(),
seedMessage: z.string().trim().min(1).max(20000),
linkedSessionId: z.string().trim().min(1).max(120).optional().nullable(),
linkedRequestId: z.string().trim().min(1).max(120).optional().nullable(),
linkedTitle: z.string().trim().max(200).optional().nullable(),
linkedRequestPreview: z.string().trim().max(1000).optional().nullable(),
linkedChatTypeLabel: z.string().trim().max(200).optional().nullable(),
}).parse(request.body ?? {});
const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(params.token);
@@ -1852,6 +1976,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
rootRequestId: requestId,
isDefault: false,
createdByClientId: clientId || null,
linkContext: normalizeShareRoomLinkContext(payload),
});
const room = await getChatShareTokenRoomMap(currentToken.id, sessionId);
@@ -1872,6 +1997,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
contextLabel: payload.chatTypeLabel,
contextDescription: null,
notifyOffline: true,
linkContext: normalizeShareRoomLinkContext(payload),
createdAt,
updatedAt: createdAt,
},
@@ -2322,6 +2448,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
}).parse(request.params ?? {});
const query = z.object({
sessionId: z.string().trim().min(1).max(120).optional(),
view: z.enum(['full', 'initial']).optional(),
}).parse(request.query ?? {});
const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(params.token);
@@ -2361,6 +2488,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
const shareSnapshot = await buildChatShareSnapshot(tokenPayload, {
sessionId: activeRoom.sessionId,
requestId: activeRoom.requestId,
detailLevel: query.view === 'initial' ? 'initial' : 'full',
});
if (!shareSnapshot) {
@@ -2433,6 +2561,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
rooms: resolvedRoomContext.rooms,
activeSessionId: activeRoom.sessionId,
promptTarget: shareSnapshot.promptTarget,
detailLevel: shareSnapshot.detailLevel,
refreshedAt: new Date().toISOString(),
};
});
@@ -2750,15 +2879,16 @@ export async function registerChatRoutes(app: FastifyInstance) {
};
});
app.post(`${CHAT_SHARE_ROUTE_PREFIX}/:token/attachments`, { bodyLimit: CHAT_ATTACHMENT_ROUTE_BODY_LIMIT }, async (request, reply) => {
app.post(`${CHAT_SHARE_ROUTE_PREFIX}/:token/origin-reply`, async (request, reply) => {
const params = z.object({
token: z.string().trim().min(1).max(16000),
}).parse(request.params ?? {});
const payload = z.object({
sessionId: z.string().trim().min(1).max(120).optional().nullable(),
fileName: z.string().trim().max(255).optional(),
mimeType: z.string().trim().max(200).optional(),
contentBase64: z.string().trim().min(1).max(CHAT_ATTACHMENT_ROUTE_BODY_LIMIT * 2),
sourceSessionId: z.string().trim().min(1).max(120),
sourceRequestId: z.string().trim().min(1).max(120),
text: z.string().trim().min(1).max(20000),
mode: z.enum(['queue', 'direct']).optional(),
}).parse(request.body ?? {});
const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(params.token);
@@ -2781,6 +2911,109 @@ export async function registerChatRoutes(app: FastifyInstance) {
});
}
const unavailableMessage = resolveManagedShareUnavailableMessage(managedContext.managedResource);
if (unavailableMessage) {
return reply.code(403).send({
message: unavailableMessage,
});
}
if (!(await ensureManagedShareAccessPin(request, reply, managedContext.sharePath))) {
return;
}
if (managedContext.managedResource?.token.permissions && !managedContext.managedResource.token.permissions.includes('comment')) {
return reply.code(403).send({
message: '이 공유 링크에는 원 세션 답변 전송 권한이 없습니다.',
});
}
const normalizedSourceSessionId = payload.sourceSessionId.trim();
const normalizedSourceRequestId = payload.sourceRequestId.trim();
const allowedLinkTargets = resolvedRoomContext.rooms
.map((room) => room.linkContext)
.filter((item): item is ChatShareRoomLinkContext => item?.kind === 'linked-session');
const matchedLinkTarget = allowedLinkTargets.find((item) =>
item.sourceSessionId === normalizedSourceSessionId && item.sourceRequestId === normalizedSourceRequestId,
);
if (!matchedLinkTarget) {
return reply.code(403).send({
message: '현재 공유채팅에 연결된 원 세션만 답변 전송할 수 있습니다.',
});
}
const targetRequest = await getChatConversationRequest(normalizedSourceSessionId, normalizedSourceRequestId);
if (!targetRequest) {
return reply.code(404).send({
message: '원 세션 요청을 찾지 못했습니다.',
});
}
const targetConversation = await getChatConversation(normalizedSourceSessionId, null);
const queuedRequestId = await getActiveChatService()?.submitExternalMessage(
normalizedSourceSessionId,
payload.text,
{
mode: payload.mode === 'direct' ? 'direct' : 'queue',
requestOrigin: 'composer',
sharedResourceTokenId: managedContext.managedResource?.token.id ?? tokenPayload.managedResourceTokenId ?? null,
parentRequestId: normalizedSourceRequestId,
clientId: targetRequest.requesterClientId ?? targetConversation?.clientId ?? null,
},
);
if (!queuedRequestId) {
return reply.code(503).send({
message: '원 세션 답변 전송을 시작하지 못했습니다.',
});
}
if (managedContext.managedResource) {
await recordSharedResourceTokenUsage(managedContext.managedResource.token.id, {
actorLabel: 'share-viewer',
summary: '공유채팅에서 원 세션으로 답변을 전송했습니다.',
detail: `${normalizedSourceSessionId}:${normalizedSourceRequestId}`,
});
}
return {
ok: true,
queuedRequestId,
};
});
app.post(`${CHAT_SHARE_ROUTE_PREFIX}/:token/attachments`, { bodyLimit: CHAT_ATTACHMENT_ROUTE_BODY_LIMIT }, async (request, reply) => {
const params = z.object({
token: z.string().trim().min(1).max(16000),
}).parse(request.params ?? {});
const isBinaryRequest = isOctetStreamRequest(request.headers['content-type']);
const payload = isBinaryRequest
? parseChatAttachmentBinaryHeaders(request.headers, { allowOptionalSessionId: true })
: chatAttachmentShareJsonBodySchema.parse(request.body ?? {});
const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(params.token);
if (!tokenPayload) {
return reply.code(404).send({
message: '공유 링크가 유효하지 않습니다.',
});
}
const resolvedRoomContext = await resolveActiveManagedShareRoom({
managedResource: managedContext.managedResource,
tokenPayload,
requestedSessionId: payload.sessionId ?? null,
});
if (!resolvedRoomContext.requestedRoomMatched || !resolvedRoomContext.activeRoom) {
return reply.code(403).send({
message: '이 공유 링크에서 접근할 수 없는 채팅방입니다.',
});
}
const shareSnapshot = await buildChatShareSnapshot(tokenPayload, {
sessionId: resolvedRoomContext.activeRoom.sessionId,
requestId: resolvedRoomContext.activeRoom.requestId,
@@ -2823,12 +3056,19 @@ export async function registerChatRoutes(app: FastifyInstance) {
});
}
const saved = await saveChatAttachmentFile({
sessionId: resolvedRoomContext.activeRoom.sessionId,
fileName: payload.fileName,
mimeType: payload.mimeType,
contentBase64: payload.contentBase64,
});
const saved = isBinaryRequest
? await saveChatAttachmentBuffer({
sessionId: resolvedRoomContext.activeRoom.sessionId,
fileName: payload.fileName,
mimeType: payload.mimeType,
buffer: Buffer.isBuffer(request.body) ? request.body : Buffer.alloc(0),
})
: await saveChatAttachmentFile({
sessionId: resolvedRoomContext.activeRoom.sessionId,
fileName: payload.fileName,
mimeType: payload.mimeType,
contentBase64: chatAttachmentShareJsonBodySchema.parse(request.body ?? {}).contentBase64,
});
if (!saved.ok) {
return reply.code(saved.statusCode).send({
@@ -3437,13 +3677,18 @@ export async function registerChatRoutes(app: FastifyInstance) {
});
app.post('/api/chat/attachments', { bodyLimit: CHAT_ATTACHMENT_ROUTE_BODY_LIMIT }, async (request, reply) => {
const payload = z.object({
sessionId: z.string().trim().min(1).max(120).regex(/^[A-Za-z0-9._:-]+$/),
fileName: z.string().trim().max(255).optional(),
mimeType: z.string().trim().max(200).optional(),
contentBase64: z.string().trim().min(1).max(CHAT_ATTACHMENT_ROUTE_BODY_LIMIT * 2),
}).parse(request.body ?? {});
const saved = await saveChatAttachmentFile(payload);
const isBinaryRequest = isOctetStreamRequest(request.headers['content-type']);
const saved = isBinaryRequest
? await (() => {
const binaryPayload = parseChatAttachmentBinaryHeaders(request.headers);
return saveChatAttachmentBuffer({
sessionId: binaryPayload.sessionId ?? '',
fileName: binaryPayload.fileName,
mimeType: binaryPayload.mimeType,
buffer: Buffer.isBuffer(request.body) ? request.body : Buffer.alloc(0),
});
})()
: await saveChatAttachmentFile(chatAttachmentJsonBodySchema.parse(request.body ?? {}));
if (!saved.ok) {
return reply.code(saved.statusCode).send({

View File

@@ -20,11 +20,22 @@ export type ChatShareTokenRoomMapItem = {
contextLabel: string | null;
contextDescription: string | null;
notifyOffline: boolean;
linkContext: ChatShareRoomLinkContext | null;
createdAt: string | null;
updatedAt: string | null;
conversationUpdatedAt: string | null;
};
export type ChatShareRoomLinkContext = {
kind: 'linked-session';
sourceSessionId: string;
sourceRequestId: string;
sourceTitle: string | null;
sourceRequestPreview: string | null;
sourceChatTypeLabel: string | null;
linkedAt: string | null;
};
function normalizeOptionalText(value: unknown) {
if (typeof value !== 'string') {
return null;
@@ -72,6 +83,72 @@ function normalizeDateTime(value: unknown) {
return null;
}
function parseChatShareRoomLinkContext(value: unknown) {
if (typeof value !== 'string') {
return null;
}
const normalized = value.trim();
if (!normalized) {
return null;
}
try {
const parsed = JSON.parse(normalized) as Record<string, unknown>;
if (parsed.kind !== 'linked-session') {
return null;
}
const sourceSessionId = normalizeRequiredText(parsed.sourceSessionId);
const sourceRequestId = normalizeRequiredText(parsed.sourceRequestId);
if (!sourceSessionId || !sourceRequestId) {
return null;
}
return {
kind: 'linked-session',
sourceSessionId,
sourceRequestId,
sourceTitle: normalizeOptionalText(parsed.sourceTitle),
sourceRequestPreview: normalizeOptionalText(parsed.sourceRequestPreview),
sourceChatTypeLabel: normalizeOptionalText(parsed.sourceChatTypeLabel),
linkedAt: normalizeDateTime(parsed.linkedAt),
} satisfies ChatShareRoomLinkContext;
} catch {
return null;
}
}
function stringifyChatShareRoomLinkContext(value: ChatShareRoomLinkContext | null | undefined) {
if (!value) {
return null;
}
if (value.kind !== 'linked-session') {
return null;
}
const sourceSessionId = normalizeRequiredText(value.sourceSessionId);
const sourceRequestId = normalizeRequiredText(value.sourceRequestId);
if (!sourceSessionId || !sourceRequestId) {
return null;
}
return JSON.stringify({
kind: 'linked-session',
sourceSessionId,
sourceRequestId,
sourceTitle: normalizeOptionalText(value.sourceTitle),
sourceRequestPreview: normalizeOptionalText(value.sourceRequestPreview),
sourceChatTypeLabel: normalizeOptionalText(value.sourceChatTypeLabel),
linkedAt: normalizeDateTime(value.linkedAt),
});
}
function mapChatShareTokenRoomRow(row: Record<string, unknown>): ChatShareTokenRoomMapItem {
return {
tokenId: normalizeRequiredText(row.shared_resource_token_id),
@@ -87,6 +164,7 @@ function mapChatShareTokenRoomRow(row: Record<string, unknown>): ChatShareTokenR
contextLabel: normalizeOptionalText(row.context_label),
contextDescription: normalizeOptionalText(row.context_description),
notifyOffline: normalizeBoolean(row.notify_offline),
linkContext: parseChatShareRoomLinkContext(row.link_context_json),
createdAt: normalizeDateTime(row.created_at),
updatedAt: normalizeDateTime(row.updated_at),
conversationUpdatedAt: normalizeDateTime(row.conversation_updated_at),
@@ -121,6 +199,7 @@ export async function ensureChatShareTokenRoomMapTable() {
['is_default', (table) => table.boolean('is_default').notNullable().defaultTo(false)],
['sort_order', (table) => table.integer('sort_order').notNullable().defaultTo(0)],
['created_by_client_id', (table) => table.string('created_by_client_id', 120).nullable()],
['link_context_json', (table) => table.text('link_context_json').nullable()],
['archived_at', (table) => table.timestamp('archived_at', { useTz: true }).nullable().index()],
['created_at', (table) => table.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now())],
['updated_at', (table) => table.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(db.fn.now())],
@@ -164,6 +243,7 @@ export async function listChatShareTokenRoomMaps(tokenId: string) {
'conversation.context_label',
'conversation.context_description',
'conversation.notify_offline',
'room_map.link_context_json',
'conversation.updated_at as conversation_updated_at',
)
.where({ 'room_map.shared_resource_token_id': normalizedTokenId })
@@ -194,6 +274,7 @@ export async function upsertChatShareTokenRoomMap(args: {
isDefault?: boolean;
sortOrder?: number | null;
createdByClientId?: string | null;
linkContext?: ChatShareRoomLinkContext | null;
}) {
const normalizedTokenId = args.tokenId.trim();
const normalizedSessionId = args.sessionId.trim();
@@ -240,6 +321,10 @@ export async function upsertChatShareTokenRoomMap(args: {
is_default: args.isDefault === true,
sort_order: nextSortOrder,
created_by_client_id: normalizeOptionalText(args.createdByClientId),
link_context_json:
args.linkContext === undefined
? (current?.link_context_json ?? null)
: stringifyChatShareRoomLinkContext(args.linkContext),
archived_at: null,
updated_at: db.fn.now(),
};

View File

@@ -25,6 +25,7 @@ import {
import { getKstNowParts } from './worklog-automation-utils.js';
export const PLAN_SCHEDULED_TASK_TABLE = 'plan_scheduled_tasks';
const PLAN_SCHEDULE_REGISTRATION_ADVISORY_LOCK_NAMESPACE = 741_205_262;
const scheduleModes = ['interval', 'daily'] as const;
const repeatIntervalUnits = ['second', 'minute', 'hour', 'day', 'week', 'month'] as const;
const scheduleExecutionModes = ['codex', 'managed-service'] as const;
@@ -515,6 +516,39 @@ function normalizeBoolean(value: unknown, fallback: boolean) {
return fallback;
}
function readBooleanLikeValue(value: unknown) {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value !== 0;
}
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
return normalized === 'true' || normalized === 't' || normalized === '1';
}
return false;
}
async function tryAcquirePlanScheduleRegistrationLock(scheduleId: number) {
const result = (await db.raw('select pg_try_advisory_lock(?, ?) as locked', [
PLAN_SCHEDULE_REGISTRATION_ADVISORY_LOCK_NAMESPACE,
scheduleId,
])) as { rows?: Array<{ locked?: unknown }> };
return readBooleanLikeValue(result.rows?.[0]?.locked);
}
async function releasePlanScheduleRegistrationLock(scheduleId: number) {
await db.raw('select pg_advisory_unlock(?, ?)', [
PLAN_SCHEDULE_REGISTRATION_ADVISORY_LOCK_NAMESPACE,
scheduleId,
]);
}
function buildManagedServiceFailureSummary(result: {
title?: string;
skipped?: boolean;
@@ -1510,162 +1544,179 @@ export async function registerDuePlanScheduledTasks(now = new Date()) {
}
async function registerPlanScheduledTaskRow(row: Record<string, unknown>, now: Date) {
const executionMode = normalizeScheduleExecutionMode(row.execution_mode);
const automationContextIds = parseAutomationContextIds(row.automation_context_ids_json);
const shouldRefreshSnapshot =
!row.context_snapshot_generated_at || normalizeBoolean(row.context_snapshot_refresh_requested, false);
const scheduleSnapshot = shouldRefreshSnapshot
? await ensureSchedulePromptSnapshot({
scheduleId: Number(row.id),
workId: buildScheduledPlanWorkIdBase(row),
note: String(row.note ?? ''),
forceRefresh: true,
})
: {
directory: `.auto_codex/schedule/${row.id}`,
requestPath: `.auto_codex/schedule/${row.id}/request.md`,
contextPath: `.auto_codex/schedule/${row.id}/context.md`,
manifestPath: `.auto_codex/schedule/${row.id}/manifest.json`,
};
const managedServiceReady = await ensureManagedServiceExecutionReady({
row,
scheduleSnapshot,
automationContextIds,
});
const effectiveRow = managedServiceReady.row;
const scheduleNote = [
String(effectiveRow.note ?? '').trim(),
'',
'## 스케줄 전용 참조 문서',
`- ${scheduleSnapshot.requestPath}`,
`- ${scheduleSnapshot.contextPath}`,
'',
'위 경로의 Markdown 문서를 먼저 읽고 처리하세요. 원본 소스/문서 재탐색은 꼭 필요한 경우에만 제한적으로 수행하세요.',
executionMode === 'managed-service'
? [
'',
'## 스케줄 관리 서비스',
`- 서비스 키: ${String(effectiveRow.managed_service_key ?? `schedule-${effectiveRow.id}-service`)}`,
`- 서비스 경로: ${String(effectiveRow.managed_service_directory ?? `.auto_codex/schedule/${effectiveRow.id}`)}`,
managedServiceReady.ready
? '- 현재 생성된 스케줄 전용 서비스 파일을 직접 실행합니다.'
: `- 현재 서비스 패키지 생성 Plan을 ${managedServiceReady.generationTriggered ? '자동 접수했으며' : '이미 접수해 두었으며'} 생성 완료 전까지 실제 서비스 실행은 보류합니다.`,
managedServiceReady.reason
? `- 생성 사유: ${managedServiceReady.reason === 'missing' ? '패키지 누락 감지' : '패키지 재생성 요청'}`
: null,
'- 서비스 구현은 Codex CLI가 `.auto_codex/schedule/{id}` 아래 파일을 생성한 결과물을 사용합니다.',
].join('\n')
: null,
]
.filter((value): value is string => Boolean(value))
.join('\n')
.trim();
const scheduleId = Number(row.id);
if (executionMode === 'managed-service') {
if (!managedServiceReady.ready) {
return {
createdPlan: managedServiceReady.createdPlan,
createdBoardPosts: managedServiceReady.createdBoardPosts,
};
}
const managedServiceDirectory = String(
effectiveRow.managed_service_directory ?? `.auto_codex/schedule/${effectiveRow.id}`,
);
const managedServiceResult = await runManagedScheduleService(managedServiceDirectory);
if (!managedServiceResult.ok) {
throw new Error(
`스케줄 서비스 실행 실패: ${buildManagedServiceFailureSummary(managedServiceResult)}`,
);
}
const createdPlan = await createCompletedPlanExecutionLogItem({
workId: buildScheduledPlanWorkIdBase(effectiveRow),
note: scheduleNote,
automationType: String(effectiveRow.automation_type_id ?? effectiveRow.automation_type ?? 'none'),
automationContextIds,
releaseTarget: String(effectiveRow.release_target ?? 'release'),
jangsingProcessingRequired: Boolean(effectiveRow.jangsing_processing_required ?? true),
autoDeployToMain: Boolean(effectiveRow.auto_deploy_to_main ?? true),
suppressWebPush: Boolean(effectiveRow.suppress_web_push ?? false),
repeatRequestEnabled: false,
repeatIntervalMinutes: 60,
});
const managedServiceChangedFiles = [
`${managedServiceDirectory}/README.md`,
`${managedServiceDirectory}/service.ts`,
`${managedServiceDirectory}/service.mjs`,
`${managedServiceDirectory}/service-manifest.json`,
];
await createPlanSourceWorkHistory(Number(createdPlan.id), {
summary: [
`스케줄 서비스 실행: schedule #${effectiveRow.id}`,
`서비스 키: ${String(effectiveRow.managed_service_key ?? `schedule-${effectiveRow.id}-service`)}`,
`결과: ${
managedServiceResult.skipped
? `스킵 (${managedServiceResult.web.reason ?? managedServiceResult.ios.reason ?? '사유 없음'})`
: `${managedServiceResult.itemCount}건 전송 시도`
}`,
].join('\n'),
branchName: String(createdPlan.releaseTarget ?? createdPlan.assignedBranch ?? 'main'),
commitHash: null,
changedFiles: managedServiceChangedFiles,
commandLog: [
`schedule-managed-service run scheduleId=${String(effectiveRow.id)}`,
`servicePath=${managedServiceDirectory}/service.mjs`,
`itemCount=${managedServiceResult.itemCount}`,
`webSent=${managedServiceResult.web.sentCount}`,
`webFailed=${managedServiceResult.web.failedCount}`,
`skipped=${managedServiceResult.skipped ? 'true' : 'false'}`,
`reason=${managedServiceResult.web.reason ?? managedServiceResult.ios.reason ?? ''}`,
].join('\n'),
diffText: null,
sourceFiles: [],
});
await createPlanActionHistory(
Number(createdPlan.id),
'스케줄서비스실행',
`Plan 스케줄 #${effectiveRow.id} 전용 서비스 파일을 직접 실행했습니다.`,
);
await db(PLAN_SCHEDULED_TASK_TABLE)
.where({ id: effectiveRow.id })
.update({
last_registered_at: now,
context_snapshot_generated_at: now,
context_snapshot_refresh_requested: false,
managed_service_generated_at: db.fn.now(),
updated_at: db.fn.now(),
});
if (!Number.isInteger(scheduleId) || scheduleId <= 0) {
throw new Error('유효하지 않은 스케줄 ID입니다.');
}
if (!(await tryAcquirePlanScheduleRegistrationLock(scheduleId))) {
return {
createdPlan,
createdPlan: null,
createdBoardPosts: [],
};
}
const boardPost = await createBoardPost({
title: buildScheduledBoardPostTitle(effectiveRow),
content: scheduleNote,
attachments: [],
automationType: String(effectiveRow.automation_type_id ?? effectiveRow.automation_type ?? 'none'),
automationContextIds,
requestExecutionMode: 'all_at_once',
requestItems: [],
});
await db(PLAN_SCHEDULED_TASK_TABLE)
.where({ id: effectiveRow.id })
.update({
last_registered_at: now,
context_snapshot_generated_at: now,
context_snapshot_refresh_requested: false,
updated_at: db.fn.now(),
try {
const executionMode = normalizeScheduleExecutionMode(row.execution_mode);
const automationContextIds = parseAutomationContextIds(row.automation_context_ids_json);
const shouldRefreshSnapshot =
!row.context_snapshot_generated_at || normalizeBoolean(row.context_snapshot_refresh_requested, false);
const scheduleSnapshot = shouldRefreshSnapshot
? await ensureSchedulePromptSnapshot({
scheduleId: Number(row.id),
workId: buildScheduledPlanWorkIdBase(row),
note: String(row.note ?? ''),
forceRefresh: true,
})
: {
directory: `.auto_codex/schedule/${row.id}`,
requestPath: `.auto_codex/schedule/${row.id}/request.md`,
contextPath: `.auto_codex/schedule/${row.id}/context.md`,
manifestPath: `.auto_codex/schedule/${row.id}/manifest.json`,
};
const managedServiceReady = await ensureManagedServiceExecutionReady({
row,
scheduleSnapshot,
automationContextIds,
});
return {
createdPlan: null,
createdBoardPosts: [boardPost],
};
const effectiveRow = managedServiceReady.row;
const scheduleNote = [
String(effectiveRow.note ?? '').trim(),
'',
'## 스케줄 전용 참조 문서',
`- ${scheduleSnapshot.requestPath}`,
`- ${scheduleSnapshot.contextPath}`,
'',
'위 경로의 Markdown 문서를 먼저 읽고 처리하세요. 원본 소스/문서 재탐색은 꼭 필요한 경우에만 제한적으로 수행하세요.',
executionMode === 'managed-service'
? [
'',
'## 스케줄 관리 서비스',
`- 서비스 키: ${String(effectiveRow.managed_service_key ?? `schedule-${scheduleId}-service`)}`,
`- 서비스 경로: ${String(effectiveRow.managed_service_directory ?? `.auto_codex/schedule/${scheduleId}`)}`,
managedServiceReady.ready
? '- 현재 생성된 스케줄 전용 서비스 파일을 직접 실행합니다.'
: `- 현재 서비스 패키지 생성 Plan을 ${managedServiceReady.generationTriggered ? '자동 접수했으며' : '이미 접수해 두었으며'} 생성 완료 전까지 실제 서비스 실행은 보류합니다.`,
managedServiceReady.reason
? `- 생성 사유: ${managedServiceReady.reason === 'missing' ? '패키지 누락 감지' : '패키지 재생성 요청'}`
: null,
'- 서비스 구현은 Codex CLI가 `.auto_codex/schedule/{id}` 아래 파일을 생성한 결과물을 사용합니다.',
].join('\n')
: null,
]
.filter((value): value is string => Boolean(value))
.join('\n')
.trim();
if (executionMode === 'managed-service') {
if (!managedServiceReady.ready) {
return {
createdPlan: managedServiceReady.createdPlan,
createdBoardPosts: managedServiceReady.createdBoardPosts,
};
}
const managedServiceDirectory = String(
effectiveRow.managed_service_directory ?? `.auto_codex/schedule/${scheduleId}`,
);
const managedServiceResult = await runManagedScheduleService(managedServiceDirectory);
if (!managedServiceResult.ok) {
throw new Error(
`스케줄 서비스 실행 실패: ${buildManagedServiceFailureSummary(managedServiceResult)}`,
);
}
const createdPlan = await createCompletedPlanExecutionLogItem({
workId: buildScheduledPlanWorkIdBase(effectiveRow),
note: scheduleNote,
automationType: String(effectiveRow.automation_type_id ?? effectiveRow.automation_type ?? 'none'),
automationContextIds,
releaseTarget: String(effectiveRow.release_target ?? 'release'),
jangsingProcessingRequired: Boolean(effectiveRow.jangsing_processing_required ?? true),
autoDeployToMain: Boolean(effectiveRow.auto_deploy_to_main ?? true),
suppressWebPush: Boolean(effectiveRow.suppress_web_push ?? false),
repeatRequestEnabled: false,
repeatIntervalMinutes: 60,
});
const managedServiceChangedFiles = [
`${managedServiceDirectory}/README.md`,
`${managedServiceDirectory}/service.ts`,
`${managedServiceDirectory}/service.mjs`,
`${managedServiceDirectory}/service-manifest.json`,
];
await createPlanSourceWorkHistory(Number(createdPlan.id), {
summary: [
`스케줄 서비스 실행: schedule #${scheduleId}`,
`서비스 키: ${String(effectiveRow.managed_service_key ?? `schedule-${scheduleId}-service`)}`,
`결과: ${
managedServiceResult.skipped
? `스킵 (${managedServiceResult.web.reason ?? managedServiceResult.ios.reason ?? '사유 없음'})`
: `${managedServiceResult.itemCount}건 전송 시도`
}`,
].join('\n'),
branchName: String(createdPlan.releaseTarget ?? createdPlan.assignedBranch ?? 'main'),
commitHash: null,
changedFiles: managedServiceChangedFiles,
commandLog: [
`schedule-managed-service run scheduleId=${String(effectiveRow.id)}`,
`servicePath=${managedServiceDirectory}/service.mjs`,
`itemCount=${managedServiceResult.itemCount}`,
`webSent=${managedServiceResult.web.sentCount}`,
`webFailed=${managedServiceResult.web.failedCount}`,
`skipped=${managedServiceResult.skipped ? 'true' : 'false'}`,
`reason=${managedServiceResult.web.reason ?? managedServiceResult.ios.reason ?? ''}`,
].join('\n'),
diffText: null,
sourceFiles: [],
});
await createPlanActionHistory(
Number(createdPlan.id),
'스케줄서비스실행',
`Plan 스케줄 #${scheduleId} 전용 서비스 파일을 직접 실행했습니다.`,
);
await db(PLAN_SCHEDULED_TASK_TABLE)
.where({ id: scheduleId })
.update({
last_registered_at: now,
context_snapshot_generated_at: now,
context_snapshot_refresh_requested: false,
managed_service_generated_at: db.fn.now(),
updated_at: db.fn.now(),
});
return {
createdPlan,
createdBoardPosts: [],
};
}
const boardPost = await createBoardPost({
title: buildScheduledBoardPostTitle(effectiveRow),
content: scheduleNote,
attachments: [],
automationType: String(effectiveRow.automation_type_id ?? effectiveRow.automation_type ?? 'none'),
automationContextIds,
requestExecutionMode: 'all_at_once',
requestItems: [],
});
await db(PLAN_SCHEDULED_TASK_TABLE)
.where({ id: scheduleId })
.update({
last_registered_at: now,
context_snapshot_generated_at: now,
context_snapshot_refresh_requested: false,
updated_at: db.fn.now(),
});
return {
createdPlan: null,
createdBoardPosts: [boardPost],
};
} finally {
await releasePlanScheduleRegistrationLock(scheduleId);
}
}
export async function registerPlanScheduledTaskNow(

View File

@@ -13,6 +13,7 @@ import {
listServerCommands,
resolveDockerSocketPath,
restartServerCommand,
readWorkServerDeploymentState,
} from './server-command-service.js';
test('buildRestartFailureMessage includes exit info and stderr output', () => {
@@ -115,6 +116,12 @@ test('test, release and prod restart scripts fall back to Docker socket when doc
);
assert.match(workServerScript, /recover_interrupted_chat_requests "\$TARGET_CONTAINER"/);
assert.match(workServerScript, /docker exec "\$PROXY_CONTAINER" nginx -s reload/);
assert.match(workServerScript, /wait_for_container_runtime_ready "\$TARGET_CONTAINER" "\$TARGET_SLOT"/);
assert.match(workServerScript, /wait_for_proxy_slot_health "\$TARGET_SLOT"/);
assert.match(workServerScript, /Promise.all\(\[fetch\(process.argv\[1\]\), fetch\(process.argv\[2\]\)\]\)/);
assert.match(workServerScript, /payload\?\.slot !== expectedSlot/);
assert.match(workServerScript, /runtime readiness check failed/);
assert.match(workServerScript, /STABLE_SUCCESS_COUNT=\$\(\(STABLE_SUCCESS_COUNT \+ 1\)\)/);
assert.match(workServerScript, /work-server zero-downtime switch completed/);
assert.match(socketRestartScript, /\/containers\/\$\{encodeURIComponent\(containerName\)\}\/restart\?t=30/);
});
@@ -479,3 +486,105 @@ test('listServerCommands keeps work-server updateAvailable false when only a sta
await rm(tempRoot, { recursive: true, force: true });
}
});
test('readWorkServerDeploymentState transitions stale running deployment to failed when the lock is gone', async () => {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'ai-code-work-server-deployment-'));
const originalMainRoot = env.SERVER_COMMAND_MAIN_PROJECT_ROOT;
const originalProjectRoot = env.SERVER_COMMAND_PROJECT_ROOT;
try {
env.SERVER_COMMAND_MAIN_PROJECT_ROOT = tempRoot;
env.SERVER_COMMAND_PROJECT_ROOT = tempRoot;
await writeFile(path.join(tempRoot, 'AGENTS.md'), '# temp root\n', 'utf8');
await writeFile(path.join(tempRoot, 'package.json'), '{"name":"temp-root"}\n', 'utf8');
const runtimeDir = path.join(tempRoot, 'etc', 'servers', 'work-server', '.docker', 'runtime');
await mkdir(runtimeDir, { recursive: true });
await writeFile(
path.join(runtimeDir, 'deployment-state.json'),
JSON.stringify({
status: 'running',
phase: 'drain-previous-slot',
summary: '이전 슬롯 요청을 새 슬롯으로 이관하는 중입니다.',
startedAt: '2026-05-28T01:45:37.000Z',
updatedAt: '2026-05-28T01:54:20.000Z',
activeSlot: 'blue',
targetSlot: 'blue',
previousSlot: 'green',
steps: [
{ key: 'build-target-slot', status: 'completed', detail: null, updatedAt: '2026-05-28T01:45:37.000Z' },
{ key: 'verify-target-health', status: 'completed', detail: null, updatedAt: '2026-05-28T01:45:53.000Z' },
{ key: 'switch-proxy', status: 'completed', detail: null, updatedAt: '2026-05-28T01:45:57.000Z' },
{ key: 'drain-previous-slot', status: 'running', detail: 'active 2 · queued 0', updatedAt: '2026-05-28T01:54:20.000Z' },
{ key: 'rebuild-previous-slot', status: 'pending', detail: null, updatedAt: null },
{ key: 'recover-interrupted-chat', status: 'pending', detail: null, updatedAt: null },
],
}) + '\n',
'utf8',
);
const snapshot = await readWorkServerDeploymentState();
assert.ok(snapshot);
assert.equal(snapshot.status, 'failed');
assert.equal(snapshot.phase, 'failed');
assert.equal(snapshot.steps.find((item) => item.key === 'drain-previous-slot')?.status, 'failed');
assert.match(String(snapshot.lastError ?? ''), /lock 파일이 없어서/);
} finally {
env.SERVER_COMMAND_MAIN_PROJECT_ROOT = originalMainRoot;
env.SERVER_COMMAND_PROJECT_ROOT = originalProjectRoot;
await rm(tempRoot, { recursive: true, force: true });
}
});
test('readWorkServerDeploymentState keeps running deployment when the lock is active', async () => {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'ai-code-work-server-deployment-lock-'));
const originalMainRoot = env.SERVER_COMMAND_MAIN_PROJECT_ROOT;
const originalProjectRoot = env.SERVER_COMMAND_PROJECT_ROOT;
try {
env.SERVER_COMMAND_MAIN_PROJECT_ROOT = tempRoot;
env.SERVER_COMMAND_PROJECT_ROOT = tempRoot;
await writeFile(path.join(tempRoot, 'AGENTS.md'), '# temp root\n', 'utf8');
await writeFile(path.join(tempRoot, 'package.json'), '{"name":"temp-root"}\n', 'utf8');
const runtimeDir = path.join(tempRoot, 'etc', 'servers', 'work-server', '.docker', 'runtime');
await mkdir(runtimeDir, { recursive: true });
await writeFile(
path.join(runtimeDir, 'deployment-state.json'),
JSON.stringify({
status: 'running',
phase: 'drain-previous-slot',
summary: '이전 슬롯 요청을 새 슬롯으로 이관하는 중입니다.',
startedAt: '2026-05-28T01:45:37.000Z',
updatedAt: '2026-05-28T01:54:20.000Z',
steps: [
{ key: 'build-target-slot', status: 'completed', detail: null, updatedAt: '2026-05-28T01:45:37.000Z' },
{ key: 'verify-target-health', status: 'completed', detail: null, updatedAt: '2026-05-28T01:45:53.000Z' },
{ key: 'switch-proxy', status: 'completed', detail: null, updatedAt: '2026-05-28T01:45:57.000Z' },
{ key: 'drain-previous-slot', status: 'running', detail: 'active 2 · queued 0', updatedAt: '2026-05-28T01:54:20.000Z' },
{ key: 'rebuild-previous-slot', status: 'pending', detail: null, updatedAt: null },
{ key: 'recover-interrupted-chat', status: 'pending', detail: null, updatedAt: null },
],
}) + '\n',
'utf8',
);
await writeFile(
path.join(runtimeDir, 'restart-in-progress.json'),
JSON.stringify({ startedAt: new Date().toISOString(), key: 'work-server', pid: 1234 }) + '\n',
'utf8',
);
const snapshot = await readWorkServerDeploymentState();
assert.ok(snapshot);
assert.equal(snapshot.status, 'running');
assert.equal(snapshot.phase, 'drain-previous-slot');
assert.equal(snapshot.steps.find((item) => item.key === 'drain-previous-slot')?.status, 'running');
} finally {
env.SERVER_COMMAND_MAIN_PROJECT_ROOT = originalMainRoot;
env.SERVER_COMMAND_PROJECT_ROOT = originalProjectRoot;
await rm(tempRoot, { recursive: true, force: true });
}
});

View File

@@ -1,7 +1,7 @@
import { execFile, spawn } from 'node:child_process';
import fs from 'node:fs';
import http from 'node:http';
import { mkdir, open, readFile, rm, stat } from 'node:fs/promises';
import { mkdir, open, readFile, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
import { env } from '../config/env.js';
@@ -1031,10 +1031,97 @@ function normalizeWorkServerDeploymentSnapshot(value: unknown): WorkServerDeploy
};
}
function isWorkServerDeploymentCompleted(snapshot: WorkServerDeploymentSnapshot) {
return snapshot.steps.every((step) => step.status === 'completed');
}
function reconcileStaleWorkServerDeploymentState(snapshot: WorkServerDeploymentSnapshot): WorkServerDeploymentSnapshot {
if (snapshot.status !== 'running') {
return snapshot;
}
const now = new Date().toISOString();
if (isWorkServerDeploymentCompleted(snapshot)) {
return {
...snapshot,
status: 'completed',
phase: 'completed',
summary: snapshot.summary || 'WORK-SERVER 무중단 배포를 완료했습니다.',
updatedAt: now,
completedAt: snapshot.completedAt ?? now,
lastError: null,
};
}
return {
...snapshot,
status: 'failed',
phase: 'failed',
summary: 'WORK-SERVER 배포 상태가 중간 단계에서 종료되었습니다.',
updatedAt: now,
completedAt: snapshot.completedAt ?? now,
lastError:
snapshot.lastError
|| '배포 lock 파일이 없어서 진행 중 상태를 종료된 상태로 보정했습니다.',
steps: snapshot.steps.map((step) => (
step.status === 'running'
? {
...step,
status: 'failed',
updatedAt: now,
}
: step
)),
};
}
async function hasActiveWorkServerRestartLock() {
const lockPath = getWorkServerRestartLockPath();
try {
const [raw, lockStat] = await Promise.all([
readFile(lockPath, 'utf8').catch(() => ''),
stat(lockPath),
]);
const parsed = raw ? (JSON.parse(raw) as Partial<WorkServerRestartLockPayload>) : null;
const freshnessSource =
normalizeDateTimeValue(typeof parsed?.startedAt === 'string' ? parsed.startedAt : null)
?? normalizeDateTimeValue(lockStat.mtime.toISOString());
if (!freshnessSource || Date.now() - Date.parse(freshnessSource) > WORK_SERVER_RESTART_LOCK_STALE_MS) {
await rm(lockPath, { force: true }).catch(() => undefined);
return false;
}
return true;
} catch {
return false;
}
}
async function persistWorkServerDeploymentState(snapshot: WorkServerDeploymentSnapshot) {
const targetPath = getWorkServerDeploymentStatePath();
await mkdir(path.dirname(targetPath), { recursive: true });
await writeFile(targetPath, JSON.stringify(snapshot) + '\n', 'utf8');
}
export async function readWorkServerDeploymentState(): Promise<WorkServerDeploymentSnapshot | null> {
try {
const raw = await readFile(getWorkServerDeploymentStatePath(), 'utf8');
return normalizeWorkServerDeploymentSnapshot(JSON.parse(raw));
const snapshot = normalizeWorkServerDeploymentSnapshot(JSON.parse(raw));
if (snapshot.status !== 'running' || await hasActiveWorkServerRestartLock()) {
return snapshot;
}
const reconciled = reconcileStaleWorkServerDeploymentState(snapshot);
if (JSON.stringify(reconciled) !== JSON.stringify(snapshot)) {
await persistWorkServerDeploymentState(reconciled).catch(() => undefined);
}
return reconciled;
} catch {
return null;
}

View File

@@ -16,6 +16,7 @@ import {
} from './server-command-service.js';
import { ensureVisitorHistoryTables, listVisitorClients } from './visitor-history-service.js';
import { syncMainProjectBranchForReservedRestart } from './git-service.js';
import { isCurrentWorkServerSlotActive } from './work-server-slot-service.js';
const SERVER_RESTART_RESERVATION_TABLE = 'server_restart_reservations';
const SERVER_RESTART_RESERVATION_ROW_ID = 1;
@@ -1353,6 +1354,10 @@ export class ServerRestartReservationWorker {
this.running = true;
try {
if (!(await isCurrentWorkServerSlotActive())) {
return;
}
const row = await readReservationRow();
if (!row?.enabled) {

View File

@@ -44,6 +44,7 @@ import {
} from '../services/git-service.js';
import { progressBoardPostAutomationByPlanResult } from '../services/board-service.js';
import { registerDuePlanScheduledTasks } from '../services/plan-schedule-service.js';
import { isCurrentWorkServerSlotActive } from '../services/work-server-slot-service.js';
const STREAM_CAPTURE_LIMIT = 256 * 1024;
const FIRST_PROGRESS_NOTIFICATION_MS = 60_000;
@@ -857,6 +858,11 @@ export class PlanWorker {
this.running = true;
try {
if (!(await isCurrentWorkServerSlotActive())) {
this.logger.info({ workerId: this.workerId }, 'Plan worker skipped on inactive work-server slot');
return;
}
const env = getEnv();
const appConfig = await getAppConfigSnapshot();
const autoRefreshEnabled = appConfig.automation?.autoRefreshEnabled ?? true;