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

View File

@@ -180,8 +180,14 @@ const payload = {
recoveredRequeuedCount: recoveredRequeuedCount:
parseCount(env.DEPLOY_RECOVERED_REQUEUED_COUNT_VALUE) parseCount(env.DEPLOY_RECOVERED_REQUEUED_COUNT_VALUE)
?? (!shouldResetForNewRun ? parseCount(current.recoveredRequeuedCount) : null), ?? (!shouldResetForNewRun ? parseCount(current.recoveredRequeuedCount) : null),
lastError: env.DEPLOY_LAST_ERROR || (!shouldResetForNewRun ? current.lastError : null) || null, lastError:
logExcerpt: env.DEPLOY_LOG_EXCERPT || (!shouldResetForNewRun ? current.logExcerpt : null) || null, env.DEPLOY_STATUS === 'completed'
? null
: env.DEPLOY_LAST_ERROR || (!shouldResetForNewRun ? current.lastError : null) || null,
logExcerpt:
env.DEPLOY_STATUS === 'completed'
? null
: env.DEPLOY_LOG_EXCERPT || (!shouldResetForNewRun ? current.logExcerpt : null) || null,
steps: stepKeys.map((stepKey) => stepsByKey.get(stepKey)), steps: stepKeys.map((stepKey) => stepsByKey.get(stepKey)),
}; };
fs.writeFileSync(filePath, JSON.stringify(payload) + '\n', 'utf8'); fs.writeFileSync(filePath, JSON.stringify(payload) + '\n', 'utf8');
@@ -278,20 +284,50 @@ server {
EOF2 EOF2
} }
wait_for_container_health() { wait_for_container_runtime_ready() {
TARGET_CONTAINER="$1" TARGET_CONTAINER="$1"
TARGET_SLOT="$2"
ATTEMPT=0 ATTEMPT=0
STABLE_SUCCESS_COUNT=0
while [ "$ATTEMPT" -lt 60 ]; do while [ "$ATTEMPT" -lt 90 ]; do
if docker exec "$TARGET_CONTAINER" node -e "fetch(process.argv[1]).then(async (response) => { if (!response.ok) process.exit(1); process.stdout.write(await response.text()); }).catch(() => process.exit(1));" "$HEALTH_ENDPOINT" >/dev/null 2>&1; then if docker exec "$TARGET_CONTAINER" node -e "const validatePayload = (payload, expectedSlot, requireSlot) => { if (payload?.ok !== true) process.exit(1); if (requireSlot && payload?.slot !== expectedSlot) process.exit(1); if (payload?.draining === true || payload?.canAcceptNewChatRequests === false) process.exit(1); }; Promise.all([fetch(process.argv[1]), fetch(process.argv[2])]).then(async ([healthResponse, runtimeResponse]) => { if (!healthResponse.ok || !runtimeResponse.ok) process.exit(1); const healthPayload = await healthResponse.json(); const runtimePayload = await runtimeResponse.json(); validatePayload(healthPayload, process.argv[3], true); validatePayload(runtimePayload, process.argv[3], false); }).catch(() => process.exit(1));" "$HEALTH_ENDPOINT" "$RUNTIME_ENDPOINT" "$TARGET_SLOT" >/dev/null 2>&1; then
return 0 STABLE_SUCCESS_COUNT=$((STABLE_SUCCESS_COUNT + 1))
if [ "$STABLE_SUCCESS_COUNT" -ge 3 ]; then
return 0
fi
else
STABLE_SUCCESS_COUNT=0
fi fi
ATTEMPT=$((ATTEMPT + 1)) ATTEMPT=$((ATTEMPT + 1))
sleep 2 sleep 1
done done
echo "health check failed for $TARGET_CONTAINER" >&2 echo "runtime readiness check failed for $TARGET_CONTAINER slot $TARGET_SLOT" >&2
return 1
}
wait_for_proxy_slot_health() {
TARGET_SLOT="$1"
ATTEMPT=0
STABLE_SUCCESS_COUNT=0
while [ "$ATTEMPT" -lt 90 ]; do
if node -e "const validatePayload = (payload, expectedSlot, requireSlot) => { if (payload?.ok !== true) process.exit(1); if (requireSlot && payload?.slot !== expectedSlot) process.exit(1); if (payload?.draining === true || payload?.canAcceptNewChatRequests === false) process.exit(1); }; Promise.all([fetch(process.argv[1]), fetch(process.argv[2])]).then(async ([healthResponse, runtimeResponse]) => { if (!healthResponse.ok || !runtimeResponse.ok) process.exit(1); const healthPayload = await healthResponse.json(); const runtimePayload = await runtimeResponse.json(); validatePayload(healthPayload, process.argv[3], true); validatePayload(runtimePayload, process.argv[3], false); }).catch(() => process.exit(1));" "$HEALTH_ENDPOINT" "$RUNTIME_ENDPOINT" "$TARGET_SLOT" >/dev/null 2>&1; then
STABLE_SUCCESS_COUNT=$((STABLE_SUCCESS_COUNT + 1))
if [ "$STABLE_SUCCESS_COUNT" -ge 3 ]; then
return 0
fi
else
STABLE_SUCCESS_COUNT=0
fi
ATTEMPT=$((ATTEMPT + 1))
sleep 1
done
echo "proxy runtime readiness check failed for slot $TARGET_SLOT via $HEALTH_ENDPOINT" >&2
return 1 return 1
} }
@@ -374,28 +410,28 @@ else
exit "$BUILD_STATUS" exit "$BUILD_STATUS"
fi fi
write_deploy_state running verify-target-health "새 슬롯 health 확인을 진행합니다." "verify-target-health" running "대상 컨테이너 ${TARGET_CONTAINER}" write_deploy_state running verify-target-health "새 슬롯 API 준비 상태를 확인합니다." "verify-target-health" running "대상 컨테이너 ${TARGET_CONTAINER}"
if wait_for_container_health "$TARGET_CONTAINER"; then if wait_for_container_runtime_ready "$TARGET_CONTAINER" "$TARGET_SLOT"; then
write_deploy_state running verify-target-health "새 슬롯 health 확인이 완료되었습니다." "verify-target-health" completed "대상 슬롯 ${TARGET_SLOT} 정상 응답" write_deploy_state running verify-target-health "새 슬롯 API 준비 상태 확인이 완료되었습니다." "verify-target-health" completed "대상 슬롯 ${TARGET_SLOT} health/runtime 정상 응답"
else else
LAST_DEPLOY_ERROR="새 슬롯 health 확인에 실패했습니다." LAST_DEPLOY_ERROR="새 슬롯 API 준비 상태 확인에 실패했습니다."
LAST_DEPLOY_LOG="health check failed for ${TARGET_CONTAINER}" LAST_DEPLOY_LOG="runtime readiness check failed for ${TARGET_CONTAINER}"
write_deploy_state failed failed "새 슬롯 health 확인에 실패했습니다." "verify-target-health" failed "대상 슬롯 ${TARGET_SLOT} health 실패" "$LAST_DEPLOY_ERROR" "$LAST_DEPLOY_LOG" write_deploy_state failed failed "새 슬롯 API 준비 상태 확인에 실패했습니다." "verify-target-health" failed "대상 슬롯 ${TARGET_SLOT} health/runtime 실패" "$LAST_DEPLOY_ERROR" "$LAST_DEPLOY_LOG"
exit 1 exit 1
fi fi
write_deploy_state running switch-proxy "프록시를 새 슬롯으로 전환합니다." "switch-proxy" running "활성 ${ACTIVE_SLOT} -> 대상 ${TARGET_SLOT}" write_deploy_state running switch-proxy "프록시를 새 슬롯으로 전환합니다." "switch-proxy" running "활성 ${ACTIVE_SLOT} -> 대상 ${TARGET_SLOT}"
write_proxy_config "$TARGET_SLOT" write_proxy_config "$TARGET_SLOT"
if ensure_proxy_running; then if ensure_proxy_running && wait_for_proxy_slot_health "$TARGET_SLOT"; then
write_deploy_state running switch-proxy "프록시 전환을 완료했습니다." "switch-proxy" completed "활성 ${ACTIVE_SLOT} -> 대상 ${TARGET_SLOT}" printf '%s\n' "$TARGET_SLOT" >"$ACTIVE_SLOT_FILE"
ACTIVE_SLOT="$TARGET_SLOT"
write_deploy_state running switch-proxy "프록시 전환을 완료했습니다." "switch-proxy" completed "프록시 3100 -> 대상 슬롯 ${TARGET_SLOT} 안정 응답 확인"
else else
LAST_DEPLOY_ERROR="프록시 전환에 실패했습니다." LAST_DEPLOY_ERROR="프록시 전환에 실패했습니다."
LAST_DEPLOY_LOG="nginx reload failed" LAST_DEPLOY_LOG="nginx reload or proxy health verification failed"
write_deploy_state failed failed "프록시 전환에 실패했습니다." "switch-proxy" failed "활성 ${ACTIVE_SLOT} -> 대상 ${TARGET_SLOT}" "$LAST_DEPLOY_ERROR" "$LAST_DEPLOY_LOG" write_deploy_state failed failed "프록시 전환에 실패했습니다." "switch-proxy" failed "대상 슬롯 ${TARGET_SLOT} 프록시 응답 확인 실패" "$LAST_DEPLOY_ERROR" "$LAST_DEPLOY_LOG"
exit 1 exit 1
fi fi
printf '%s\n' "$TARGET_SLOT" >"$ACTIVE_SLOT_FILE"
ACTIVE_SLOT="$TARGET_SLOT"
if [ "$PREVIOUS_SERVICE" != "$TARGET_SERVICE" ]; then if [ "$PREVIOUS_SERVICE" != "$TARGET_SERVICE" ]; then
set_container_draining "$PREVIOUS_CONTAINER" true set_container_draining "$PREVIOUS_CONTAINER" true
@@ -420,12 +456,12 @@ if [ "$PREVIOUS_SERVICE" != "$TARGET_SERVICE" ]; then
exit "$PREVIOUS_BUILD_STATUS" exit "$PREVIOUS_BUILD_STATUS"
fi fi
if wait_for_container_health "$PREVIOUS_CONTAINER"; then if wait_for_container_runtime_ready "$PREVIOUS_CONTAINER" "$PREVIOUS_SLOT"; then
write_deploy_state running rebuild-previous-slot "이전 슬롯을 대기 슬롯으로 복구했습니다." "rebuild-previous-slot" completed "대기 슬롯 ${PREVIOUS_SLOT} 정상 응답" write_deploy_state running rebuild-previous-slot "이전 슬롯을 대기 슬롯으로 복구했습니다." "rebuild-previous-slot" completed "대기 슬롯 ${PREVIOUS_SLOT} health/runtime 정상 응답"
else else
LAST_DEPLOY_ERROR="이전 슬롯 복구 health 확인에 실패했습니다." LAST_DEPLOY_ERROR="이전 슬롯 복구 API 준비 상태 확인에 실패했습니다."
LAST_DEPLOY_LOG="health check failed for ${PREVIOUS_CONTAINER}" LAST_DEPLOY_LOG="runtime readiness check failed for ${PREVIOUS_CONTAINER}"
write_deploy_state failed failed "이전 슬롯 복구 health 확인에 실패했습니다." "rebuild-previous-slot" failed "대기 슬롯 ${PREVIOUS_SLOT} health 실패" "$LAST_DEPLOY_ERROR" "$LAST_DEPLOY_LOG" write_deploy_state failed failed "이전 슬롯 복구 API 준비 상태 확인에 실패했습니다." "rebuild-previous-slot" failed "대기 슬롯 ${PREVIOUS_SLOT} health/runtime 실패" "$LAST_DEPLOY_ERROR" "$LAST_DEPLOY_LOG"
exit 1 exit 1
fi fi
fi fi

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,18 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test'; 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', () => { test('resolveStaticContentType returns html content type for chat resource html files', () => {
assert.equal(resolveStaticContentType('/tmp/sample.html'), 'text/html; charset=utf-8'); 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('queue'), 'queue');
assert.equal(resolvePromptFollowupMode('direct'), 'direct'); 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, getChatShareTokenRoomMap,
resolveChatShareTokenRoomSessionIds, resolveChatShareTokenRoomSessionIds,
upsertChatShareTokenRoomMap, upsertChatShareTokenRoomMap,
type ChatShareRoomLinkContext,
type ChatShareTokenRoomMapItem, type ChatShareTokenRoomMapItem,
} from '../services/chat-share-room-map-service.js'; } from '../services/chat-share-room-map-service.js';
import { chatRuntimeService } from '../services/chat-runtime-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 { openResourceManagerPreviewStream } from '../services/resource-manager-service.js';
import { getTokenSettingById, type TokenSettingRecord } from '../services/token-setting-config-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 = 300 * 1024 * 1024;
const CHAT_ATTACHMENT_FILE_SIZE_LIMIT = 10 * 1024 * 1024; const CHAT_ATTACHMENT_ROUTE_BODY_LIMIT = 450 * 1024 * 1024;
const CHAT_PUBLIC_ROUTE_PREFIX = '/.codex_chat/'; const CHAT_PUBLIC_ROUTE_PREFIX = '/.codex_chat/';
const CHAT_API_RESOURCE_ROUTE_PREFIX = '/api/chat/resources'; const CHAT_API_RESOURCE_ROUTE_PREFIX = '/api/chat/resources';
const CHAT_SHARE_ROUTE_PREFIX = '/api/chat/shares'; const CHAT_SHARE_ROUTE_PREFIX = '/api/chat/shares';
@@ -248,6 +249,7 @@ type ChatShareResolvedRoom = {
contextLabel: string | null; contextLabel: string | null;
contextDescription: string | null; contextDescription: string | null;
notifyOffline: boolean; notifyOffline: boolean;
linkContext: ChatShareRoomLinkContext | null;
createdAt: string | null; createdAt: string | null;
updatedAt: string | null; updatedAt: string | null;
}; };
@@ -265,6 +267,7 @@ function mapResolvedShareRoomItem(room: ChatShareTokenRoomMapItem): ChatShareRes
contextLabel: room.contextLabel, contextLabel: room.contextLabel,
contextDescription: room.contextDescription, contextDescription: room.contextDescription,
notifyOffline: room.notifyOffline, notifyOffline: room.notifyOffline,
linkContext: room.linkContext,
createdAt: room.createdAt, createdAt: room.createdAt,
updatedAt: room.conversationUpdatedAt ?? room.updatedAt, updatedAt: room.conversationUpdatedAt ?? room.updatedAt,
}; };
@@ -292,6 +295,7 @@ async function resolveManagedShareRooms(args: {
contextLabel: null, contextLabel: null,
contextDescription: null, contextDescription: null,
notifyOffline: false, notifyOffline: false,
linkContext: null,
createdAt: null, createdAt: null,
updatedAt: null, updatedAt: null,
} satisfies ChatShareResolvedRoom, } satisfies ChatShareResolvedRoom,
@@ -319,6 +323,7 @@ async function resolveManagedShareRooms(args: {
contextLabel: null, contextLabel: null,
contextDescription: null, contextDescription: null,
notifyOffline: false, notifyOffline: false,
linkContext: null,
createdAt: null, createdAt: null,
updatedAt: null, updatedAt: null,
} satisfies ChatShareResolvedRoom, } 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[]) { function sortShareMessages(messages: ListedChatConversationMessage[]) {
return [...messages].sort((left, right) => { return [...messages].sort((left, right) => {
if (left.id !== right.id) { if (left.id !== right.id) {
@@ -700,6 +730,21 @@ async function saveChatAttachmentFile(args: {
contentBase64: string; contentBase64: string;
}) { }) {
const buffer = Buffer.from(args.contentBase64, 'base64'); 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) { if (buffer.byteLength === 0) {
return { return {
@@ -713,7 +758,7 @@ async function saveChatAttachmentFile(args: {
return { return {
ok: false as const, ok: false as const,
statusCode: 413, 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> }) { function getClientIdHeader(request: { headers: Record<string, unknown> }) {
const raw = request.headers['x-client-id']; const raw = request.headers['x-client-id'];
return Array.isArray(raw) ? String(raw[0] ?? '').trim() : String(raw ?? '').trim(); return Array.isArray(raw) ? String(raw[0] ?? '').trim() : String(raw ?? '').trim();
@@ -1119,22 +1220,32 @@ async function buildChatShareSnapshot(
options?: { options?: {
sessionId?: string | null; sessionId?: string | null;
requestId?: string | null; requestId?: string | null;
detailLevel?: 'full' | 'initial';
}, },
) { ) {
const normalizedSessionId = options?.sessionId?.trim() || tokenPayload.sessionId.trim(); const normalizedSessionId = options?.sessionId?.trim() || tokenPayload.sessionId.trim();
const detailLevel = options?.detailLevel === 'initial' ? 'initial' : 'full';
const conversation = await getChatConversation(normalizedSessionId, null); const conversation = await getChatConversation(normalizedSessionId, null);
if (!conversation) { if (!conversation) {
return null; return null;
} }
const [requests, messages] = await Promise.all([ const isManagedShareRoomSession =
listChatConversationRequests(normalizedSessionId, 1000), tokenPayload.kind === 'request-bundle' && normalizedSessionId.startsWith(MANAGED_CHAT_SHARE_SESSION_PREFIX);
listChatConversationMessages(normalizedSessionId, { limit: 1000 }), 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 requestMap = new Map(requests.map((request) => [request.requestId.trim(), request] as const));
const targetRequestId = options?.requestId?.trim() || tokenPayload.requestId.trim(); 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 placeholderTargetRequest = targetRequestFromStore ? null : buildManagedSharePlaceholderRequest(tokenPayload, conversation);
const targetRequest = targetRequestFromStore ?? placeholderTargetRequest; const targetRequest = targetRequestFromStore ?? placeholderTargetRequest;
@@ -1143,13 +1254,13 @@ async function buildChatShareSnapshot(
} }
const childRequestIdsByParentRequestId = buildChildRequestIdsByParentRequestId(requests); const childRequestIdsByParentRequestId = buildChildRequestIdsByParentRequestId(requests);
const isManagedShareRoomSession =
tokenPayload.kind === 'request-bundle' && normalizedSessionId.startsWith(MANAGED_CHAT_SHARE_SESSION_PREFIX);
const isManagedShareRoomPlaceholder = isManagedShareRoomSession && !targetRequestFromStore; const isManagedShareRoomPlaceholder = isManagedShareRoomSession && !targetRequestFromStore;
const rootRequestId = isManagedShareRoomPlaceholder const rootRequestId = isManagedShareRoomPlaceholder
? targetRequestId ? targetRequestId
: resolveShareRootRequestId(targetRequestId, requestMap, tokenPayload.kind); : 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) ? requests.map((request) => request.requestId.trim()).filter(Boolean)
: collectShareScopeRequestIds(rootRequestId, childRequestIdsByParentRequestId); : collectShareScopeRequestIds(rootRequestId, childRequestIdsByParentRequestId);
const scopeRequestIdSet = new Set(scopeRequestIds); const scopeRequestIdSet = new Set(scopeRequestIds);
@@ -1158,9 +1269,11 @@ async function buildChatShareSnapshot(
const linkedRequestId = message.clientRequestId?.trim() || ''; const linkedRequestId = message.clientRequestId?.trim() || '';
return linkedRequestId ? scopeRequestIdSet.has(linkedRequestId) : false; 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 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) { if (tokenPayload.kind === 'prompt' && !promptTarget) {
return null; return null;
@@ -1176,6 +1289,7 @@ async function buildChatShareSnapshot(
activityLogs, activityLogs,
roomRequestCounts, roomRequestCounts,
promptTarget, promptTarget,
detailLevel,
} satisfies { } satisfies {
conversation: Awaited<ReturnType<typeof getChatConversation>>; conversation: Awaited<ReturnType<typeof getChatConversation>>;
rootRequestId: string; rootRequestId: string;
@@ -1187,7 +1301,7 @@ async function buildChatShareSnapshot(
roomRequestCounts: { roomRequestCounts: {
processingCount: number; processingCount: number;
unansweredCount: number; unansweredCount: number;
}; } | undefined;
promptTarget: promptTarget:
| { | {
sourceMessageId: number; sourceMessageId: number;
@@ -1195,6 +1309,7 @@ async function buildChatShareSnapshot(
prompt: Extract<ListedChatConversationMessage['parts'][number], { type: 'prompt' }>; prompt: Extract<ListedChatConversationMessage['parts'][number], { type: 'prompt' }>;
} }
| null; | null;
detailLevel: 'full' | 'initial';
}; };
} }
@@ -1509,6 +1624,10 @@ function hasManagedShareAllowedApp(
} }
export async function registerChatRoutes(app: FastifyInstance) { 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) => { app.addHook('onSend', async (request, reply, payload) => {
if (request.method.toUpperCase() === 'GET' && request.url.startsWith('/api/chat')) { if (request.method.toUpperCase() === 'GET' && request.url.startsWith('/api/chat')) {
applyChatApiNoStoreHeaders(reply); applyChatApiNoStoreHeaders(reply);
@@ -1756,6 +1875,11 @@ export async function registerChatRoutes(app: FastifyInstance) {
title: z.string().trim().min(1).max(200), title: z.string().trim().min(1).max(200),
requestBadgeLabel: z.string().trim().max(120).optional().nullable(), requestBadgeLabel: z.string().trim().max(120).optional().nullable(),
seedMessage: z.string().trim().min(1).max(20000), 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 ?? {}); }).parse(request.body ?? {});
const managedContext = await resolveManagedChatShareContext(params.token); const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(params.token); const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(params.token);
@@ -1852,6 +1976,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
rootRequestId: requestId, rootRequestId: requestId,
isDefault: false, isDefault: false,
createdByClientId: clientId || null, createdByClientId: clientId || null,
linkContext: normalizeShareRoomLinkContext(payload),
}); });
const room = await getChatShareTokenRoomMap(currentToken.id, sessionId); const room = await getChatShareTokenRoomMap(currentToken.id, sessionId);
@@ -1872,6 +1997,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
contextLabel: payload.chatTypeLabel, contextLabel: payload.chatTypeLabel,
contextDescription: null, contextDescription: null,
notifyOffline: true, notifyOffline: true,
linkContext: normalizeShareRoomLinkContext(payload),
createdAt, createdAt,
updatedAt: createdAt, updatedAt: createdAt,
}, },
@@ -2322,6 +2448,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
}).parse(request.params ?? {}); }).parse(request.params ?? {});
const query = z.object({ const query = z.object({
sessionId: z.string().trim().min(1).max(120).optional(), sessionId: z.string().trim().min(1).max(120).optional(),
view: z.enum(['full', 'initial']).optional(),
}).parse(request.query ?? {}); }).parse(request.query ?? {});
const managedContext = await resolveManagedChatShareContext(params.token); const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(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, { const shareSnapshot = await buildChatShareSnapshot(tokenPayload, {
sessionId: activeRoom.sessionId, sessionId: activeRoom.sessionId,
requestId: activeRoom.requestId, requestId: activeRoom.requestId,
detailLevel: query.view === 'initial' ? 'initial' : 'full',
}); });
if (!shareSnapshot) { if (!shareSnapshot) {
@@ -2433,6 +2561,7 @@ export async function registerChatRoutes(app: FastifyInstance) {
rooms: resolvedRoomContext.rooms, rooms: resolvedRoomContext.rooms,
activeSessionId: activeRoom.sessionId, activeSessionId: activeRoom.sessionId,
promptTarget: shareSnapshot.promptTarget, promptTarget: shareSnapshot.promptTarget,
detailLevel: shareSnapshot.detailLevel,
refreshedAt: new Date().toISOString(), 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({ const params = z.object({
token: z.string().trim().min(1).max(16000), token: z.string().trim().min(1).max(16000),
}).parse(request.params ?? {}); }).parse(request.params ?? {});
const payload = z.object({ const payload = z.object({
sessionId: z.string().trim().min(1).max(120).optional().nullable(), sessionId: z.string().trim().min(1).max(120).optional().nullable(),
fileName: z.string().trim().max(255).optional(), sourceSessionId: z.string().trim().min(1).max(120),
mimeType: z.string().trim().max(200).optional(), sourceRequestId: z.string().trim().min(1).max(120),
contentBase64: z.string().trim().min(1).max(CHAT_ATTACHMENT_ROUTE_BODY_LIMIT * 2), text: z.string().trim().min(1).max(20000),
mode: z.enum(['queue', 'direct']).optional(),
}).parse(request.body ?? {}); }).parse(request.body ?? {});
const managedContext = await resolveManagedChatShareContext(params.token); const managedContext = await resolveManagedChatShareContext(params.token);
const tokenPayload = resolveChatSharePayloadFromManagedResource(managedContext.managedResource) ?? parseChatShareToken(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, { const shareSnapshot = await buildChatShareSnapshot(tokenPayload, {
sessionId: resolvedRoomContext.activeRoom.sessionId, sessionId: resolvedRoomContext.activeRoom.sessionId,
requestId: resolvedRoomContext.activeRoom.requestId, requestId: resolvedRoomContext.activeRoom.requestId,
@@ -2823,12 +3056,19 @@ export async function registerChatRoutes(app: FastifyInstance) {
}); });
} }
const saved = await saveChatAttachmentFile({ const saved = isBinaryRequest
sessionId: resolvedRoomContext.activeRoom.sessionId, ? await saveChatAttachmentBuffer({
fileName: payload.fileName, sessionId: resolvedRoomContext.activeRoom.sessionId,
mimeType: payload.mimeType, fileName: payload.fileName,
contentBase64: payload.contentBase64, 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) { if (!saved.ok) {
return reply.code(saved.statusCode).send({ 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) => { app.post('/api/chat/attachments', { bodyLimit: CHAT_ATTACHMENT_ROUTE_BODY_LIMIT }, async (request, reply) => {
const payload = z.object({ const isBinaryRequest = isOctetStreamRequest(request.headers['content-type']);
sessionId: z.string().trim().min(1).max(120).regex(/^[A-Za-z0-9._:-]+$/), const saved = isBinaryRequest
fileName: z.string().trim().max(255).optional(), ? await (() => {
mimeType: z.string().trim().max(200).optional(), const binaryPayload = parseChatAttachmentBinaryHeaders(request.headers);
contentBase64: z.string().trim().min(1).max(CHAT_ATTACHMENT_ROUTE_BODY_LIMIT * 2), return saveChatAttachmentBuffer({
}).parse(request.body ?? {}); sessionId: binaryPayload.sessionId ?? '',
const saved = await saveChatAttachmentFile(payload); 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) { if (!saved.ok) {
return reply.code(saved.statusCode).send({ return reply.code(saved.statusCode).send({

View File

@@ -20,11 +20,22 @@ export type ChatShareTokenRoomMapItem = {
contextLabel: string | null; contextLabel: string | null;
contextDescription: string | null; contextDescription: string | null;
notifyOffline: boolean; notifyOffline: boolean;
linkContext: ChatShareRoomLinkContext | null;
createdAt: string | null; createdAt: string | null;
updatedAt: string | null; updatedAt: string | null;
conversationUpdatedAt: 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) { function normalizeOptionalText(value: unknown) {
if (typeof value !== 'string') { if (typeof value !== 'string') {
return null; return null;
@@ -72,6 +83,72 @@ function normalizeDateTime(value: unknown) {
return null; 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 { function mapChatShareTokenRoomRow(row: Record<string, unknown>): ChatShareTokenRoomMapItem {
return { return {
tokenId: normalizeRequiredText(row.shared_resource_token_id), tokenId: normalizeRequiredText(row.shared_resource_token_id),
@@ -87,6 +164,7 @@ function mapChatShareTokenRoomRow(row: Record<string, unknown>): ChatShareTokenR
contextLabel: normalizeOptionalText(row.context_label), contextLabel: normalizeOptionalText(row.context_label),
contextDescription: normalizeOptionalText(row.context_description), contextDescription: normalizeOptionalText(row.context_description),
notifyOffline: normalizeBoolean(row.notify_offline), notifyOffline: normalizeBoolean(row.notify_offline),
linkContext: parseChatShareRoomLinkContext(row.link_context_json),
createdAt: normalizeDateTime(row.created_at), createdAt: normalizeDateTime(row.created_at),
updatedAt: normalizeDateTime(row.updated_at), updatedAt: normalizeDateTime(row.updated_at),
conversationUpdatedAt: normalizeDateTime(row.conversation_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)], ['is_default', (table) => table.boolean('is_default').notNullable().defaultTo(false)],
['sort_order', (table) => table.integer('sort_order').notNullable().defaultTo(0)], ['sort_order', (table) => table.integer('sort_order').notNullable().defaultTo(0)],
['created_by_client_id', (table) => table.string('created_by_client_id', 120).nullable()], ['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()], ['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())], ['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())], ['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_label',
'conversation.context_description', 'conversation.context_description',
'conversation.notify_offline', 'conversation.notify_offline',
'room_map.link_context_json',
'conversation.updated_at as conversation_updated_at', 'conversation.updated_at as conversation_updated_at',
) )
.where({ 'room_map.shared_resource_token_id': normalizedTokenId }) .where({ 'room_map.shared_resource_token_id': normalizedTokenId })
@@ -194,6 +274,7 @@ export async function upsertChatShareTokenRoomMap(args: {
isDefault?: boolean; isDefault?: boolean;
sortOrder?: number | null; sortOrder?: number | null;
createdByClientId?: string | null; createdByClientId?: string | null;
linkContext?: ChatShareRoomLinkContext | null;
}) { }) {
const normalizedTokenId = args.tokenId.trim(); const normalizedTokenId = args.tokenId.trim();
const normalizedSessionId = args.sessionId.trim(); const normalizedSessionId = args.sessionId.trim();
@@ -240,6 +321,10 @@ export async function upsertChatShareTokenRoomMap(args: {
is_default: args.isDefault === true, is_default: args.isDefault === true,
sort_order: nextSortOrder, sort_order: nextSortOrder,
created_by_client_id: normalizeOptionalText(args.createdByClientId), created_by_client_id: normalizeOptionalText(args.createdByClientId),
link_context_json:
args.linkContext === undefined
? (current?.link_context_json ?? null)
: stringifyChatShareRoomLinkContext(args.linkContext),
archived_at: null, archived_at: null,
updated_at: db.fn.now(), updated_at: db.fn.now(),
}; };

View File

@@ -25,6 +25,7 @@ import {
import { getKstNowParts } from './worklog-automation-utils.js'; import { getKstNowParts } from './worklog-automation-utils.js';
export const PLAN_SCHEDULED_TASK_TABLE = 'plan_scheduled_tasks'; 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 scheduleModes = ['interval', 'daily'] as const;
const repeatIntervalUnits = ['second', 'minute', 'hour', 'day', 'week', 'month'] as const; const repeatIntervalUnits = ['second', 'minute', 'hour', 'day', 'week', 'month'] as const;
const scheduleExecutionModes = ['codex', 'managed-service'] as const; const scheduleExecutionModes = ['codex', 'managed-service'] as const;
@@ -515,6 +516,39 @@ function normalizeBoolean(value: unknown, fallback: boolean) {
return fallback; 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: { function buildManagedServiceFailureSummary(result: {
title?: string; title?: string;
skipped?: boolean; skipped?: boolean;
@@ -1510,162 +1544,179 @@ export async function registerDuePlanScheduledTasks(now = new Date()) {
} }
async function registerPlanScheduledTaskRow(row: Record<string, unknown>, now: Date) { async function registerPlanScheduledTaskRow(row: Record<string, unknown>, now: Date) {
const executionMode = normalizeScheduleExecutionMode(row.execution_mode); const scheduleId = Number(row.id);
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();
if (executionMode === 'managed-service') { if (!Number.isInteger(scheduleId) || scheduleId <= 0) {
if (!managedServiceReady.ready) { throw new Error('유효하지 않은 스케줄 ID입니다.');
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 (!(await tryAcquirePlanScheduleRegistrationLock(scheduleId))) {
return { return {
createdPlan, createdPlan: null,
createdBoardPosts: [], createdBoardPosts: [],
}; };
} }
const boardPost = await createBoardPost({ try {
title: buildScheduledBoardPostTitle(effectiveRow), const executionMode = normalizeScheduleExecutionMode(row.execution_mode);
content: scheduleNote, const automationContextIds = parseAutomationContextIds(row.automation_context_ids_json);
attachments: [], const shouldRefreshSnapshot =
automationType: String(effectiveRow.automation_type_id ?? effectiveRow.automation_type ?? 'none'), !row.context_snapshot_generated_at || normalizeBoolean(row.context_snapshot_refresh_requested, false);
automationContextIds, const scheduleSnapshot = shouldRefreshSnapshot
requestExecutionMode: 'all_at_once', ? await ensureSchedulePromptSnapshot({
requestItems: [], scheduleId: Number(row.id),
}); workId: buildScheduledPlanWorkIdBase(row),
note: String(row.note ?? ''),
await db(PLAN_SCHEDULED_TASK_TABLE) forceRefresh: true,
.where({ id: effectiveRow.id }) })
.update({ : {
last_registered_at: now, directory: `.auto_codex/schedule/${row.id}`,
context_snapshot_generated_at: now, requestPath: `.auto_codex/schedule/${row.id}/request.md`,
context_snapshot_refresh_requested: false, contextPath: `.auto_codex/schedule/${row.id}/context.md`,
updated_at: db.fn.now(), manifestPath: `.auto_codex/schedule/${row.id}/manifest.json`,
};
const managedServiceReady = await ensureManagedServiceExecutionReady({
row,
scheduleSnapshot,
automationContextIds,
}); });
return { const effectiveRow = managedServiceReady.row;
createdPlan: null, const scheduleNote = [
createdBoardPosts: [boardPost], 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( export async function registerPlanScheduledTaskNow(

View File

@@ -13,6 +13,7 @@ import {
listServerCommands, listServerCommands,
resolveDockerSocketPath, resolveDockerSocketPath,
restartServerCommand, restartServerCommand,
readWorkServerDeploymentState,
} from './server-command-service.js'; } from './server-command-service.js';
test('buildRestartFailureMessage includes exit info and stderr output', () => { 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, /recover_interrupted_chat_requests "\$TARGET_CONTAINER"/);
assert.match(workServerScript, /docker exec "\$PROXY_CONTAINER" nginx -s reload/); 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(workServerScript, /work-server zero-downtime switch completed/);
assert.match(socketRestartScript, /\/containers\/\$\{encodeURIComponent\(containerName\)\}\/restart\?t=30/); 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 }); 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 { execFile, spawn } from 'node:child_process';
import fs from 'node:fs'; import fs from 'node:fs';
import http from 'node:http'; 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 path from 'node:path';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import { env } from '../config/env.js'; 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> { export async function readWorkServerDeploymentState(): Promise<WorkServerDeploymentSnapshot | null> {
try { try {
const raw = await readFile(getWorkServerDeploymentStatePath(), 'utf8'); 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 { } catch {
return null; return null;
} }

View File

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

View File

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

View File

@@ -66,6 +66,7 @@ import { ChatActivityChecklist, buildChatActivityChecklistEntries } from './Chat
import { describeExecutorCommand } from './executorActivitySummary'; import { describeExecutorCommand } from './executorActivitySummary';
import { buildComposerFilePickKey } from './composerFilePickKey'; import { buildComposerFilePickKey } from './composerFilePickKey';
import { ChatPromptCard, buildPromptTargetSignature, type PromptDraftSelection, type PromptSubmitPayload } from './ChatPromptCard'; import { ChatPromptCard, buildPromptTargetSignature, type PromptDraftSelection, type PromptSubmitPayload } from './ChatPromptCard';
import { ChatStructuredPreviewCard } from './ChatStructuredPreviewCard';
import { openChatExternalLink } from './linkNavigation'; import { openChatExternalLink } from './linkNavigation';
import { classifyPreviewKind } from './previewKind'; import { classifyPreviewKind } from './previewKind';
import { isPromptResolved } from './promptState'; import { isPromptResolved } from './promptState';
@@ -495,6 +496,7 @@ type MessageRenderPayload = {
diffBlocks: string[]; diffBlocks: string[];
rankedLinkTargets: RankedLinkPreviewTarget[]; rankedLinkTargets: RankedLinkPreviewTarget[];
linkCardTargets: Extract<ChatMessagePart, { type: 'link_card' }>[]; linkCardTargets: Extract<ChatMessagePart, { type: 'link_card' }>[];
previewCardTargets: Extract<ChatMessagePart, { type: 'preview_card' }>[];
promptTargets: Extract<ChatMessagePart, { type: 'prompt' }>[]; promptTargets: Extract<ChatMessagePart, { type: 'prompt' }>[];
}; };
@@ -1172,6 +1174,17 @@ function extractMessageRenderPayload(message: ChatMessage): MessageRenderPayload
...structuredParts.filter((part): part is Extract<ChatMessagePart, { type: 'link_card' }> => part.type === 'link_card'), ...structuredParts.filter((part): part is Extract<ChatMessagePart, { type: 'link_card' }> => part.type === 'link_card'),
...extractedMessageParts.parts.filter((part): part is Extract<ChatMessagePart, { type: 'link_card' }> => part.type === 'link_card'), ...extractedMessageParts.parts.filter((part): part is Extract<ChatMessagePart, { type: 'link_card' }> => part.type === 'link_card'),
].filter((part, index, collection) => collection.findIndex((candidate) => `${candidate.title}:${candidate.url}` === `${part.title}:${part.url}`) === index); ].filter((part, index, collection) => collection.findIndex((candidate) => `${candidate.title}:${candidate.url}` === `${part.title}:${part.url}`) === index);
const previewCardTargets = [
...structuredParts.filter((part): part is Extract<ChatMessagePart, { type: 'preview_card' }> => part.type === 'preview_card'),
...extractedMessageParts.parts.filter((part): part is Extract<ChatMessagePart, { type: 'preview_card' }> => part.type === 'preview_card'),
].filter(
(part, index, collection) =>
collection.findIndex(
(candidate) =>
`${candidate.title}:${candidate.preview.type}:${candidate.preview.url ?? ''}:${candidate.preview.content ?? ''}` ===
`${part.title}:${part.preview.type}:${part.preview.url ?? ''}:${part.preview.content ?? ''}`,
) === index,
);
const promptTargets = (() => { const promptTargets = (() => {
const promptParts = [ const promptParts = [
...structuredParts.filter((part): part is Extract<ChatMessagePart, { type: 'prompt' }> => part.type === 'prompt'), ...structuredParts.filter((part): part is Extract<ChatMessagePart, { type: 'prompt' }> => part.type === 'prompt'),
@@ -1219,6 +1232,7 @@ function extractMessageRenderPayload(message: ChatMessage): MessageRenderPayload
diffBlocks, diffBlocks,
rankedLinkTargets, rankedLinkTargets,
linkCardTargets, linkCardTargets,
previewCardTargets,
promptTargets, promptTargets,
}; };
} }
@@ -6098,7 +6112,7 @@ export function ChatConversationView({
const baseMessageBodyClassName = `app-chat-message__body${shouldTruncateMessage ? ' app-chat-message__body--collapsed' : ''}${ const baseMessageBodyClassName = `app-chat-message__body${shouldTruncateMessage ? ' app-chat-message__body--collapsed' : ''}${
isRecoveredMissingRequest || isRecoveredExecutionFailure ? ' app-chat-message__body--system-status' : '' isRecoveredMissingRequest || isRecoveredExecutionFailure ? ' app-chat-message__body--system-status' : ''
}`; }`;
const { previewSourceText, visibleText, diffBlocks, rankedLinkTargets, linkCardTargets, promptTargets } = const { previewSourceText, visibleText, diffBlocks, rankedLinkTargets, linkCardTargets, previewCardTargets, promptTargets } =
messageRenderPayloadById.get(message.id) ?? extractMessageRenderPayload(message); messageRenderPayloadById.get(message.id) ?? extractMessageRenderPayload(message);
const renderedText = isRecoveredMissingRequest const renderedText = isRecoveredMissingRequest
? getMissingRequestMessageText(message) ? getMissingRequestMessageText(message)
@@ -6122,6 +6136,7 @@ export function ChatConversationView({
inlinePreviewTargets.length > 0 || inlinePreviewTargets.length > 0 ||
rankedLinkTargets.length > 0 || rankedLinkTargets.length > 0 ||
linkCardTargets.length > 0 || linkCardTargets.length > 0 ||
previewCardTargets.length > 0 ||
promptTargets.length > 0; promptTargets.length > 0;
const shouldRenderStandalonePreview = const shouldRenderStandalonePreview =
hasPreviewCards && !visibleText && (message.author === 'codex' || message.author === 'system'); hasPreviewCards && !visibleText && (message.author === 'codex' || message.author === 'system');
@@ -6540,6 +6555,19 @@ export function ChatConversationView({
}} }}
/> />
))} ))}
{previewCardTargets.map((target, index) => (
<ChatStructuredPreviewCard
key={`${message.id}-preview-card-${index}-${target.title}`}
target={target}
onOpen={(previewUrl) => {
markPreviewArtifactOpened(message.clientRequestId ?? null);
if (previewUrl) {
markPreviewResourceOpened(previewUrl);
}
}}
/>
))}
{promptTargets.map((target, index) => ( {promptTargets.map((target, index) => (
(() => { (() => {
const selectionKey = buildPendingPromptSelectionKey(message.id, index, target.title, target); const selectionKey = buildPendingPromptSelectionKey(message.id, index, target.title, target);

View File

@@ -728,7 +728,7 @@ function usePromptPreviewContent(preview: PromptPreview | null | undefined) {
return { remoteContent, remoteContentType, isLoading, loadError }; return { remoteContent, remoteContentType, isLoading, loadError };
} }
function PromptPreviewSurface({ export function PromptPreviewSurface({
preview, preview,
compact = false, compact = false,
htmlMode = 'preview', htmlMode = 'preview',
@@ -872,6 +872,16 @@ function PromptPreviewSurface({
return <div className="app-chat-prompt-card__preview-placeholder"> preview가 .</div>; return <div className="app-chat-prompt-card__preview-placeholder"> preview가 .</div>;
} }
function PromptPreviewViewport({ children }: { children: ReactNode }) {
return (
<div className="app-chat-prompt-card__preview-scroll">
<div className="app-chat-prompt-card__preview-scroll-inner">
{children}
</div>
</div>
);
}
function PromptPreviewCard({ function PromptPreviewCard({
option, option,
onOpenPreview, onOpenPreview,
@@ -975,7 +985,11 @@ function PromptPreviewCard({
/> />
)} )}
</div> </div>
<PromptPreviewSurface preview={preview} compact /> <div className="app-chat-prompt-card__preview-body">
<PromptPreviewViewport>
<PromptPreviewSurface preview={preview} compact />
</PromptPreviewViewport>
</div>
</div> </div>
); );
} }

View File

@@ -0,0 +1,111 @@
import { ExportOutlined, LinkOutlined, ShareAltOutlined } from '@ant-design/icons';
import { App, Button, Typography } from 'antd';
import { PromptPreviewSurface } from './ChatPromptCard';
import { sharePreviewLink } from './chatUtils';
import { openChatExternalLink } from './linkNavigation';
import type { ChatMessagePart } from './types';
const { Paragraph } = Typography;
function resolveStructuredPreviewKindLabel(target: Extract<ChatMessagePart, { type: 'preview_card' }>) {
const explicit = target.kindLabel?.trim();
if (explicit) {
return explicit;
}
switch (target.preview.type) {
case 'markdown':
return 'markdown card';
case 'html':
return 'html card';
case 'image':
return 'image card';
default:
return 'resource card';
}
}
export function ChatStructuredPreviewCard({
target,
onOpen,
}: {
target: Extract<ChatMessagePart, { type: 'preview_card' }>;
onOpen?: (previewUrl?: string | null) => void;
}) {
const { message } = App.useApp();
const normalizedPreviewUrl = target.preview.url?.trim() || null;
const handleShare = () => {
if (!normalizedPreviewUrl) {
message.info('이 카드는 공유할 링크가 없습니다.');
return;
}
onOpen?.(normalizedPreviewUrl);
void sharePreviewLink({
url: normalizedPreviewUrl,
title: target.title,
})
.then((result) => {
message.success(result === 'shared' ? '카드 링크를 공유했습니다.' : '카드 링크를 복사했습니다.');
})
.catch((error: unknown) => {
if (error instanceof DOMException && error.name === 'AbortError') {
return;
}
message.error(error instanceof Error ? error.message : '카드 링크를 공유하지 못했습니다.');
});
};
return (
<section className="app-chat-preview-card app-chat-preview-card--structured">
<div className="app-chat-preview-card__header">
<div className="app-chat-preview-card__meta">
<span className="app-chat-preview-card__glyph app-chat-preview-card__glyph--prompt" aria-hidden="true">
<LinkOutlined />
</span>
<div className="app-chat-preview-card__titles">
<span className="app-chat-preview-card__label">{target.title}</span>
<span className="app-chat-preview-card__kind">{resolveStructuredPreviewKindLabel(target)}</span>
</div>
</div>
<div className="app-chat-preview-card__actions">
{normalizedPreviewUrl ? (
<>
<Button
type="text"
size="small"
className="app-chat-preview-card__action"
icon={<ShareAltOutlined />}
aria-label={`${target.title} 카드 공유`}
onClick={handleShare}
/>
<Button
type="link"
size="small"
className="app-chat-preview-card__open-link"
icon={<ExportOutlined />}
onClick={(event) => {
onOpen?.(normalizedPreviewUrl);
void openChatExternalLink(normalizedPreviewUrl, event);
}}
>
{target.actionLabel?.trim() || '열기'}
</Button>
</>
) : null}
</div>
</div>
<div className="app-chat-preview-card__body app-chat-preview-card__body--structured">
{target.description ? <Paragraph className="app-chat-preview-card__description">{target.description}</Paragraph> : null}
<div className="app-chat-prompt-card__preview-shell">
<div className="app-chat-prompt-card__preview-body">
<PromptPreviewSurface preview={target.preview} compact />
</div>
</div>
</div>
</section>
);
}

View File

@@ -14,6 +14,7 @@ import type {
ChatPromptContextRef, ChatPromptContextRef,
ChatConversationRequest, ChatConversationRequest,
ChatConversationSummary, ChatConversationSummary,
ChatShareRoomLinkContext,
ChatSourceChangeSnapshot, ChatSourceChangeSnapshot,
ChatSourceChangeSnapshotListResponse, ChatSourceChangeSnapshotListResponse,
ChatJobEvent, ChatJobEvent,
@@ -35,7 +36,7 @@ const CHAT_INTRO_MESSAGE =
const CHAT_ACTIVITY_MESSAGE_PREFIX = '[[activity-log]]'; const CHAT_ACTIVITY_MESSAGE_PREFIX = '[[activity-log]]';
const CHAT_MISSING_REQUEST_MESSAGE_PREFIX = '[[missing-request]]'; const CHAT_MISSING_REQUEST_MESSAGE_PREFIX = '[[missing-request]]';
const CHAT_EXECUTION_FAILURE_MESSAGE_PREFIX = '[[execution-failure]]'; const CHAT_EXECUTION_FAILURE_MESSAGE_PREFIX = '[[execution-failure]]';
const CHAT_COMPOSER_UPLOAD_FILE_SIZE_LIMIT = 10 * 1024 * 1024; const CHAT_COMPOSER_UPLOAD_FILE_SIZE_LIMIT = 300 * 1024 * 1024;
const KST_TIME_ZONE = 'Asia/Seoul'; const KST_TIME_ZONE = 'Asia/Seoul';
const chatSessionLastTypeMemory = new Map<string, string>(); const chatSessionLastTypeMemory = new Map<string, string>();
const chatLastEventIdMemory = new Map<string, number>(); const chatLastEventIdMemory = new Map<string, number>();
@@ -1691,8 +1692,20 @@ async function requestChatApi<T>(
window.clearTimeout(timeoutId); window.clearTimeout(timeoutId);
if (!response.ok) { if (!response.ok) {
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
const text = await response.text(); const text = await response.text();
if (response.status === 413) {
throw new ChatApiError(
'첨부 업로드 크기가 현재 허용 한도를 초과했습니다. 300MB 이하 파일로 다시 시도해 주세요.',
response.status,
);
}
if (contentType.includes('text/html') && text.trim().startsWith('<')) {
throw new ChatApiError('채팅 API가 HTML 오류 페이지를 반환했습니다. 프록시 업로드 한도를 확인해 주세요.', response.status);
}
if (text.trim()) { if (text.trim()) {
try { try {
const payload = JSON.parse(text) as { message?: string; code?: string }; const payload = JSON.parse(text) as { message?: string; code?: string };
@@ -1728,26 +1741,8 @@ async function requestChatApi<T>(
} }
} }
async function readFileAsBase64(file: File) { function encodeChatAttachmentHeaderValue(value: string) {
return new Promise<string>((resolve, reject) => { return encodeURIComponent(value);
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result !== 'string') {
reject(new Error('파일 내용을 읽지 못했습니다.'));
return;
}
const commaIndex = reader.result.indexOf(',');
resolve(commaIndex >= 0 ? reader.result.slice(commaIndex + 1) : reader.result);
};
reader.onerror = () => {
reject(reader.error ?? new Error('파일 내용을 읽지 못했습니다.'));
};
reader.readAsDataURL(file);
});
} }
const FALLBACK_UPLOAD_MIME_BY_EXTENSION: Record<string, string> = { const FALLBACK_UPLOAD_MIME_BY_EXTENSION: Record<string, string> = {
@@ -2036,6 +2031,38 @@ function normalizeChatSourceChangeSnapshot(item: ChatSourceChangeSnapshot): Chat
}; };
} }
async function uploadChatAttachmentBinary(
path: string,
file: File,
args: {
sessionId: string;
fileName: string;
mimeType: string;
allowUnauthenticated?: boolean;
sharePin?: string | null;
},
) {
const response = await requestChatApi<{ ok: boolean; item: ChatComposerAttachment }>(
path,
{
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'X-Chat-Attachment-Session-Id': encodeChatAttachmentHeaderValue(args.sessionId),
'X-Chat-Attachment-File-Name': encodeChatAttachmentHeaderValue(args.fileName),
'X-Chat-Attachment-Mime-Type': encodeChatAttachmentHeaderValue(args.mimeType),
},
body: file,
},
{
allowUnauthenticated: args.allowUnauthenticated,
sharePin: args.sharePin,
},
);
return response.item;
}
export async function uploadChatComposerFile(sessionId: string, file: File) { export async function uploadChatComposerFile(sessionId: string, file: File) {
const normalizedSessionId = sessionId.trim(); const normalizedSessionId = sessionId.trim();
const resolvedMimeType = resolveUploadMimeType(file); const resolvedMimeType = resolveUploadMimeType(file);
@@ -2071,35 +2098,17 @@ export async function uploadChatComposerFile(sessionId: string, file: File) {
} }
if (file.size > CHAT_COMPOSER_UPLOAD_FILE_SIZE_LIMIT) { if (file.size > CHAT_COMPOSER_UPLOAD_FILE_SIZE_LIMIT) {
const uploadError = new Error(`첨부 파일은 10MB 이하만 업로드할 수 있습니다. (${resolvedFileName})`); const uploadError = new Error(`첨부 파일은 300MB 이하만 업로드할 수 있습니다. (${resolvedFileName})`);
await reportUploadFailure('validate-file', uploadError); await reportUploadFailure('validate-file', uploadError);
throw uploadError; throw uploadError;
} }
let contentBase64 = '';
try { try {
contentBase64 = await readFileAsBase64(file); return await uploadChatAttachmentBinary('/attachments', file, {
} catch (error) { sessionId: normalizedSessionId,
const message = error instanceof Error && error.message.trim() ? error.message.trim() : '파일 내용을 읽지 못했습니다.'; fileName: resolvedFileName,
const uploadError = new Error(`${message} (${resolvedFileName})`); mimeType: resolvedMimeType,
uploadError.name = error instanceof Error && error.name ? error.name : 'FileReadError';
await reportUploadFailure('read-file', uploadError);
throw uploadError;
}
try {
const response = await requestChatApi<{ ok: boolean; item: ChatComposerAttachment }>('/attachments', {
method: 'POST',
body: JSON.stringify({
sessionId: normalizedSessionId,
fileName: resolvedFileName,
mimeType: resolvedMimeType,
contentBase64,
}),
}); });
return response.item;
} catch (error) { } catch (error) {
const uploadError = const uploadError =
error instanceof Error && error.message.trim() error instanceof Error && error.message.trim()
@@ -2153,41 +2162,22 @@ export async function uploadChatShareComposerFile(token: string, sessionId: stri
} }
if (file.size > CHAT_COMPOSER_UPLOAD_FILE_SIZE_LIMIT) { if (file.size > CHAT_COMPOSER_UPLOAD_FILE_SIZE_LIMIT) {
const uploadError = new Error(`첨부 파일은 10MB 이하만 업로드할 수 있습니다. (${resolvedFileName})`); const uploadError = new Error(`첨부 파일은 300MB 이하만 업로드할 수 있습니다. (${resolvedFileName})`);
await reportUploadFailure('validate-file', uploadError); await reportUploadFailure('validate-file', uploadError);
throw uploadError; throw uploadError;
} }
let contentBase64 = '';
try { try {
contentBase64 = await readFileAsBase64(file); return await uploadChatAttachmentBinary(
} catch (error) {
const message = error instanceof Error && error.message.trim() ? error.message.trim() : '파일 내용을 읽지 못했습니다.';
const uploadError = new Error(`${message} (${resolvedFileName})`);
uploadError.name = error instanceof Error && error.name ? error.name : 'FileReadError';
await reportUploadFailure('read-file', uploadError);
throw uploadError;
}
try {
const response = await requestChatApi<{ ok: boolean; item: ChatComposerAttachment }>(
`/shares/${encodeURIComponent(normalizedToken)}/attachments`, `/shares/${encodeURIComponent(normalizedToken)}/attachments`,
file,
{ {
method: 'POST', sessionId: normalizedSessionId,
body: JSON.stringify({ fileName: resolvedFileName,
sessionId: normalizedSessionId, mimeType: resolvedMimeType,
fileName: resolvedFileName,
mimeType: resolvedMimeType,
contentBase64,
}),
},
{
allowUnauthenticated: true, allowUnauthenticated: true,
}, },
); );
return response.item;
} catch (error) { } catch (error) {
const uploadError = const uploadError =
error instanceof Error && error.message.trim() error instanceof Error && error.message.trim()
@@ -2341,6 +2331,11 @@ export async function createChatShareRoom(
title: string; title: string;
requestBadgeLabel?: string | null; requestBadgeLabel?: string | null;
seedMessage: string; seedMessage: string;
linkedSessionId?: string | null;
linkedRequestId?: string | null;
linkedTitle?: string | null;
linkedRequestPreview?: string | null;
linkedChatTypeLabel?: string | null;
}, },
) { ) {
const response = await requestChatApi<{ ok: boolean; room: ChatShareRoomSummary }>( const response = await requestChatApi<{ ok: boolean; room: ChatShareRoomSummary }>(
@@ -2366,6 +2361,18 @@ export async function createChatShareRoom(
contextLabel: normalizeOptionalText(response.room.contextLabel), contextLabel: normalizeOptionalText(response.room.contextLabel),
contextDescription: normalizeOptionalText(response.room.contextDescription), contextDescription: normalizeOptionalText(response.room.contextDescription),
notifyOffline: response.room.notifyOffline === true, notifyOffline: response.room.notifyOffline === true,
linkContext:
response.room.linkContext?.kind === 'linked-session'
? {
kind: 'linked-session',
sourceSessionId: normalizeRequiredText(response.room.linkContext.sourceSessionId),
sourceRequestId: normalizeRequiredText(response.room.linkContext.sourceRequestId),
sourceTitle: normalizeOptionalText(response.room.linkContext.sourceTitle),
sourceRequestPreview: normalizeOptionalText(response.room.linkContext.sourceRequestPreview),
sourceChatTypeLabel: normalizeOptionalText(response.room.linkContext.sourceChatTypeLabel),
linkedAt: normalizeOptionalText(response.room.linkContext.linkedAt),
}
: null,
createdAt: normalizeOptionalText(response.room.createdAt), createdAt: normalizeOptionalText(response.room.createdAt),
updatedAt: normalizeOptionalText(response.room.updatedAt), updatedAt: normalizeOptionalText(response.room.updatedAt),
} satisfies ChatShareRoomSummary; } satisfies ChatShareRoomSummary;
@@ -2516,11 +2523,13 @@ export type ChatShareRoomSummary = {
contextLabel?: string | null; contextLabel?: string | null;
contextDescription?: string | null; contextDescription?: string | null;
notifyOffline?: boolean; notifyOffline?: boolean;
linkContext?: ChatShareRoomLinkContext | null;
createdAt?: string | null; createdAt?: string | null;
updatedAt?: string | null; updatedAt?: string | null;
}; };
export type ChatShareSnapshot = { export type ChatShareSnapshot = {
detailLevel?: 'full' | 'initial';
share: { share: {
kind: ChatShareKind; kind: ChatShareKind;
sessionId: string; sessionId: string;
@@ -2759,9 +2768,27 @@ export async function saveChatShareRoomSettings(
}; };
} }
export async function fetchChatShareSnapshot(token: string, options?: { sharePin?: string | null; sessionId?: string | null }) { export async function fetchChatShareSnapshot(
token: string,
options?: {
sharePin?: string | null;
sessionId?: string | null;
view?: 'full' | 'initial';
},
) {
const query = new URLSearchParams();
if (options?.sessionId?.trim()) {
query.set('sessionId', options.sessionId.trim());
}
if (options?.view === 'initial') {
query.set('view', 'initial');
}
const response = await requestChatApi<{ const response = await requestChatApi<{
ok: boolean; ok: boolean;
detailLevel?: ChatShareSnapshot['detailLevel'];
share: ChatShareSnapshot['share']; share: ChatShareSnapshot['share'];
conversation: ChatShareSnapshot['conversation']; conversation: ChatShareSnapshot['conversation'];
rootRequestId: string; rootRequestId: string;
@@ -2775,7 +2802,7 @@ export async function fetchChatShareSnapshot(token: string, options?: { sharePin
promptTarget?: ChatShareSnapshot['promptTarget']; promptTarget?: ChatShareSnapshot['promptTarget'];
refreshedAt: string; refreshedAt: string;
}>( }>(
`/shares/${encodeURIComponent(token)}${options?.sessionId?.trim() ? `?sessionId=${encodeURIComponent(options.sessionId.trim())}` : ''}`, `/shares/${encodeURIComponent(token)}${query.size > 0 ? `?${query.toString()}` : ''}`,
undefined, undefined,
{ {
allowUnauthenticated: true, allowUnauthenticated: true,
@@ -2785,6 +2812,7 @@ export async function fetchChatShareSnapshot(token: string, options?: { sharePin
); );
return { return {
detailLevel: response.detailLevel === 'initial' ? 'initial' : 'full',
share: { share: {
...response.share, ...response.share,
createdAt: normalizeOptionalText(response.share?.createdAt), createdAt: normalizeOptionalText(response.share?.createdAt),
@@ -2855,6 +2883,18 @@ export async function fetchChatShareSnapshot(token: string, options?: { sharePin
contextLabel: normalizeOptionalText(item.contextLabel), contextLabel: normalizeOptionalText(item.contextLabel),
contextDescription: normalizeOptionalText(item.contextDescription), contextDescription: normalizeOptionalText(item.contextDescription),
notifyOffline: item.notifyOffline === true, notifyOffline: item.notifyOffline === true,
linkContext:
item.linkContext?.kind === 'linked-session'
? {
kind: 'linked-session',
sourceSessionId: normalizeRequiredText(item.linkContext.sourceSessionId),
sourceRequestId: normalizeRequiredText(item.linkContext.sourceRequestId),
sourceTitle: normalizeOptionalText(item.linkContext.sourceTitle),
sourceRequestPreview: normalizeOptionalText(item.linkContext.sourceRequestPreview),
sourceChatTypeLabel: normalizeOptionalText(item.linkContext.sourceChatTypeLabel),
linkedAt: normalizeOptionalText(item.linkContext.linkedAt),
}
: null,
createdAt: normalizeOptionalText(item.createdAt), createdAt: normalizeOptionalText(item.createdAt),
updatedAt: normalizeOptionalText(item.updatedAt), updatedAt: normalizeOptionalText(item.updatedAt),
})) }))
@@ -2897,6 +2937,34 @@ export async function submitChatShareMessage(
); );
} }
export async function submitChatShareOriginReply(
token: string,
payload: {
sessionId?: string | null;
sourceSessionId: string;
sourceRequestId: string;
text: string;
mode?: 'queue' | 'direct';
},
) {
return requestChatApi<{ ok: boolean; queuedRequestId: string }>(
`/shares/${encodeURIComponent(token)}/origin-reply`,
{
method: 'POST',
body: JSON.stringify({
sessionId: payload.sessionId?.trim() || undefined,
sourceSessionId: payload.sourceSessionId.trim(),
sourceRequestId: payload.sourceRequestId.trim(),
text: payload.text,
mode: payload.mode === 'direct' ? 'direct' : 'queue',
}),
},
{
allowUnauthenticated: true,
},
);
}
export async function submitChatSharePrompt( export async function submitChatSharePrompt(
token: string, token: string,
payload: { payload: {

View File

@@ -1,9 +1,11 @@
import type { ChatMessagePart } from './types'; import type { ChatMessagePart } from './types';
const LINK_CARD_LINE_PATTERN = /^\s*\[\[link-card:(.+?)\]\]\s*$/i; const LINK_CARD_LINE_PATTERN = /^\s*\[\[link-card:(.+?)\]\]\s*$/i;
const CARD_LINE_PATTERN = /^\s*\[\[card:(.+?)\]\]\s*$/i;
const PROMPT_LINE_PATTERN = /^\s*\[\[prompt:(.+?)\]\]\s*$/i; const PROMPT_LINE_PATTERN = /^\s*\[\[prompt:(.+?)\]\]\s*$/i;
const STANDALONE_MARKDOWN_LINK_LINE_PATTERN = /^\s*(?:[-*+]\s+|\d+\.\s+)?\[([^\]]+)\]\((.+)\)\s*$/; const STANDALONE_MARKDOWN_LINK_LINE_PATTERN = /^\s*(?:[-*+]\s+|\d+\.\s+)?\[([^\]]+)\]\((.+)\)\s*$/;
const STANDALONE_URL_LINE_PATTERN = /^\s*(?:[-*+]\s+|\d+\.\s+)?((?:https?:\/\/|\/)[^\s<>)\]]+)\s*$/i; const STANDALONE_URL_LINE_PATTERN = /^\s*(?:[-*+]\s+|\d+\.\s+)?((?:https?:\/\/|\/)[^\s<>)\]]+)\s*$/i;
const CARD_BLOCK_START_PATTERN = /^\s*\[\[card:\s*$/i;
const PROMPT_BLOCK_START_PATTERN = /^\s*\[\[prompt:\s*$/i; const PROMPT_BLOCK_START_PATTERN = /^\s*\[\[prompt:\s*$/i;
const PROMPT_BLOCK_END_PATTERN = /^\s*\]\]\s*$/; const PROMPT_BLOCK_END_PATTERN = /^\s*\]\]\s*$/;
const PROMPT_CODE_BLOCK_START_PATTERN = /^\s*```(?:json|prompt)(?:\s+prompt)?\s*$/i; const PROMPT_CODE_BLOCK_START_PATTERN = /^\s*```(?:json|prompt)(?:\s+prompt)?\s*$/i;
@@ -21,6 +23,7 @@ type PromptPart = Extract<ChatMessagePart, { type: 'prompt' }>;
type PromptOption = PromptPart['options'][number]; type PromptOption = PromptPart['options'][number];
type PromptPreview = NonNullable<PromptOption['preview']>; type PromptPreview = NonNullable<PromptOption['preview']>;
type PromptStep = NonNullable<PromptPart['steps']>[number]; type PromptStep = NonNullable<PromptPart['steps']>[number];
type PreviewCardPart = Extract<ChatMessagePart, { type: 'preview_card' }>;
function normalizeText(value: unknown) { function normalizeText(value: unknown) {
return String(value ?? '').trim(); return String(value ?? '').trim();
@@ -313,6 +316,51 @@ function normalizePromptPreview(value: unknown): PromptPreview | null {
}; };
} }
function buildPreviewCardPart(rawBody: string): PreviewCardPart | null {
const trimmed = rawBody.trim();
if (!trimmed) {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {
return null;
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null;
}
const record = parsed as Record<string, unknown>;
const title = normalizeText(record.title) || normalizeText(record.label);
const preview =
normalizePromptPreview(record.preview) ||
normalizePromptPreview({
type: record.type,
url: record.url,
content: record.content,
alt: record.alt,
title: record.previewTitle ?? record.title,
});
if (!title || !preview) {
return null;
}
return {
type: 'preview_card',
title,
description: normalizeText(record.description) || null,
kindLabel: normalizeText(record.kindLabel) || null,
actionLabel: normalizeText(record.actionLabel) || null,
preview,
};
}
function isPromptOption(value: PromptOption | null): value is PromptOption { function isPromptOption(value: PromptOption | null): value is PromptOption {
return value != null; return value != null;
} }
@@ -647,7 +695,20 @@ export function extractChatMessageParts(text: string) {
const dedupeKey = const dedupeKey =
nextPart.type === 'link_card' nextPart.type === 'link_card'
? `${nextPart.type}:${nextPart.title}:${nextPart.url}:${nextPart.actionLabel ?? ''}` ? `${nextPart.type}:${nextPart.title}:${nextPart.url}:${nextPart.actionLabel ?? ''}`
: [ : nextPart.type === 'preview_card'
? [
nextPart.type,
nextPart.title,
nextPart.description ?? '',
nextPart.kindLabel ?? '',
nextPart.actionLabel ?? '',
nextPart.preview.type,
nextPart.preview.url ?? '',
nextPart.preview.content ?? '',
nextPart.preview.alt ?? '',
nextPart.preview.title ?? '',
].join(':')
: [
nextPart.type, nextPart.type,
nextPart.title, nextPart.title,
nextPart.options nextPart.options
@@ -728,6 +789,43 @@ export function extractChatMessageParts(text: string) {
continue; continue;
} }
const cardMatched = line.match(CARD_LINE_PATTERN);
if (cardMatched) {
if (!pushPart(buildPreviewCardPart(cardMatched[1] ?? ''))) {
keptLines.push(line);
}
continue;
}
if (CARD_BLOCK_START_PATTERN.test(line)) {
const wrappedLines = [line];
const cardBodyLines: string[] = [];
let cursor = lineIndex + 1;
let foundBlockEnd = false;
for (; cursor < lines.length; cursor += 1) {
const nextLine = lines[cursor] ?? '';
wrappedLines.push(nextLine);
if (PROMPT_BLOCK_END_PATTERN.test(nextLine)) {
foundBlockEnd = true;
break;
}
cardBodyLines.push(nextLine);
}
if (foundBlockEnd && pushPart(buildPreviewCardPart(cardBodyLines.join('\n')))) {
lineIndex = cursor;
continue;
}
keptLines.push(...wrappedLines);
lineIndex = foundBlockEnd ? cursor : lines.length;
continue;
}
const promptMatched = line.match(PROMPT_LINE_PATTERN); const promptMatched = line.match(PROMPT_LINE_PATTERN);
if (promptMatched) { if (promptMatched) {

View File

@@ -1861,16 +1861,50 @@
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
padding: 0 8px 8px; padding: 0 8px 8px;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: auto;
overscroll-behavior: contain;
} }
.app-chat-preview-card__body--prompt-collapsed { .app-chat-preview-card__body--prompt-collapsed {
display: none; display: none;
} }
.app-chat-preview-card--prompt,
.app-chat-preview-card--structured {
width: min(100%, 720px);
min-width: 0;
max-width: 100%;
}
.app-chat-preview-card__body--structured {
display: flex;
flex-direction: column;
gap: 8px;
padding: 0 8px 8px;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: auto;
overscroll-behavior: contain;
}
.app-chat-preview-card__description.ant-typography {
margin: 0;
color: #334155;
white-space: pre-wrap;
word-break: break-word;
}
.app-chat-prompt-card__description.ant-typography { .app-chat-prompt-card__description.ant-typography {
margin: 0; margin: 0;
font-size: 12px; font-size: 12px;
color: #334155; color: #334155;
white-space: pre-wrap;
overflow-wrap: anywhere;
word-break: break-word;
} }
.app-chat-prompt-card__context { .app-chat-prompt-card__context {
@@ -2054,6 +2088,8 @@
.app-chat-prompt-card__option-preview-inline { .app-chat-prompt-card__option-preview-inline {
margin-top: 6px; margin-top: 6px;
min-width: 0;
max-width: 100%;
} }
@media (max-width: 640px) { @media (max-width: 640px) {
@@ -2069,10 +2105,41 @@
.app-chat-prompt-card__preview-shell { .app-chat-prompt-card__preview-shell {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: hidden; overflow: hidden;
border: 1px solid rgba(148, 163, 184, 0.2); border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 10px; border-radius: 10px;
background: rgba(241, 245, 249, 0.8); background: rgba(241, 245, 249, 0.8);
box-sizing: border-box;
}
.app-chat-prompt-card__preview-body {
width: 100%;
min-width: 0;
max-width: 100%;
max-height: min(420px, 70vh);
overflow: hidden;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
}
.app-chat-prompt-card__preview-scroll {
width: 100%;
min-width: 0;
max-width: 100%;
max-height: inherit;
overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-x: contain;
-webkit-overflow-scrolling: touch;
}
.app-chat-prompt-card__preview-scroll-inner {
width: 100%;
min-width: 0;
max-width: 100%;
} }
.app-chat-prompt-card__stepper { .app-chat-prompt-card__stepper {
@@ -2328,6 +2395,18 @@
word-break: break-word; word-break: break-word;
} }
.app-chat-prompt-card__context,
.app-chat-prompt-card__description.ant-typography,
.app-chat-prompt-card__result.ant-typography,
.app-chat-prompt-card__stepper,
.app-chat-prompt-card__step-panel,
.app-chat-prompt-card__options,
.app-chat-prompt-card__free-text,
.app-chat-prompt-card__footer {
min-width: 0;
max-width: 100%;
}
.app-chat-prompt-card__submitted { .app-chat-prompt-card__submitted {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;

View File

@@ -9,6 +9,14 @@ export type ChatComposerAttachment = {
mimeType: string; mimeType: string;
}; };
export type ChatStructuredPreview = {
type: 'image' | 'markdown' | 'html' | 'resource';
url?: string | null;
content?: string | null;
alt?: string | null;
title?: string | null;
};
export type ChatPromptContextRef = { export type ChatPromptContextRef = {
key: 'prompt_parent_question'; key: 'prompt_parent_question';
promptTitle: string; promptTitle: string;
@@ -23,6 +31,14 @@ export type ChatMessagePart =
url: string; url: string;
actionLabel?: string | null; actionLabel?: string | null;
} }
| {
type: 'preview_card';
title: string;
description?: string | null;
kindLabel?: string | null;
actionLabel?: string | null;
preview: ChatStructuredPreview;
}
| { | {
type: 'prompt'; type: 'prompt';
title: string; title: string;
@@ -50,15 +66,7 @@ export type ChatMessagePart =
value: string; value: string;
label: string; label: string;
description?: string | null; description?: string | null;
preview?: preview?: ChatStructuredPreview | null;
| {
type: 'image' | 'markdown' | 'html' | 'resource';
url?: string | null;
content?: string | null;
alt?: string | null;
title?: string | null;
}
| null;
}>; }>;
}>; }>;
readOnly?: boolean; readOnly?: boolean;
@@ -71,15 +79,7 @@ export type ChatMessagePart =
value: string; value: string;
label: string; label: string;
description?: string | null; description?: string | null;
preview?: preview?: ChatStructuredPreview | null;
| {
type: 'image' | 'markdown' | 'html' | 'resource';
url?: string | null;
content?: string | null;
alt?: string | null;
title?: string | null;
}
| null;
}>; }>;
}; };
@@ -163,6 +163,16 @@ export type ChatConversationSummary = {
lastMessageAt: string | null; lastMessageAt: string | null;
}; };
export type ChatShareRoomLinkContext = {
kind: 'linked-session';
sourceSessionId: string;
sourceRequestId: string;
sourceTitle: string | null;
sourceRequestPreview: string | null;
sourceChatTypeLabel: string | null;
linkedAt: string | null;
};
export type ChatConversationRequestStatus = export type ChatConversationRequestStatus =
| 'accepted' | 'accepted'
| 'queued' | 'queued'

View File

@@ -178,6 +178,7 @@
.chat-share-page__conversation-panel { .chat-share-page__conversation-panel {
flex: 1 1 auto; flex: 1 1 auto;
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
padding: 8px 10px 10px; padding: 8px 10px 10px;
@@ -192,6 +193,7 @@
.chat-share-page__composer-panel { .chat-share-page__composer-panel {
display: flex; display: flex;
position: relative;
flex-direction: column; flex-direction: column;
flex: 0 0 auto; flex: 0 0 auto;
min-height: var(--chat-share-page-composer-panel-min-height); min-height: var(--chat-share-page-composer-panel-min-height);
@@ -204,6 +206,7 @@
} }
.chat-share-page__activity-panel { .chat-share-page__activity-panel {
position: relative;
padding: 8px 10px; padding: 8px 10px;
border-radius: 14px; border-radius: 14px;
background: rgba(248, 250, 252, 0.94); background: rgba(248, 250, 252, 0.94);
@@ -219,6 +222,16 @@
box-shadow: inset 0 0 0 1px rgba(219, 226, 236, 0.82); box-shadow: inset 0 0 0 1px rgba(219, 226, 236, 0.82);
} }
.chat-share-page__room-list-panel--floating {
position: fixed;
z-index: 1300;
overflow: hidden;
box-shadow:
0 18px 42px rgba(15, 23, 42, 0.18),
inset 0 0 0 1px rgba(219, 226, 236, 0.9);
backdrop-filter: blur(18px);
}
.chat-share-page__room-filter-input.ant-input-affix-wrapper { .chat-share-page__room-filter-input.ant-input-affix-wrapper {
width: 100%; width: 100%;
border-radius: 12px; border-radius: 12px;
@@ -233,6 +246,111 @@
gap: 8px; gap: 8px;
width: 100%; width: 100%;
min-width: 0; min-width: 0;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.chat-share-page__room-group {
display: grid;
gap: 8px;
}
.chat-share-page__room-group--standalone {
gap: 0;
}
.chat-share-page__room-group-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border-radius: 14px;
background: rgba(255, 255, 255, 0.82);
box-shadow: inset 0 0 0 1px rgba(226, 232, 240, 0.9);
}
.chat-share-page__room-group-copy {
display: grid;
gap: 3px;
min-width: 0;
}
.chat-share-page__room-group-title {
color: #0f172a;
font-size: 13px;
font-weight: 700;
line-height: 1.35;
}
.chat-share-page__room-group-meta {
color: #475569;
font-size: 12px;
line-height: 1.4;
}
.chat-share-page__room-group-preview {
color: #64748b;
font-size: 12px;
line-height: 1.45;
display: -webkit-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.chat-share-page__room-group-actions {
display: flex;
align-items: center;
gap: 4px;
flex-wrap: wrap;
justify-content: flex-end;
}
.chat-share-page__room-group-action.ant-btn {
padding-inline: 6px;
}
.chat-share-page__room-group-list {
display: grid;
gap: 8px;
}
.chat-share-page__room-card-counts {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.chat-share-page__room-card-count {
display: inline-flex;
align-items: center;
min-width: 0;
padding: 3px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
line-height: 1.3;
box-sizing: border-box;
}
.chat-share-page__room-card-count--processing {
color: #0958d9;
background: rgba(230, 244, 255, 0.96);
box-shadow: inset 0 0 0 1px rgba(145, 213, 255, 0.95);
}
.chat-share-page__room-card-count--unanswered {
color: #ad6800;
background: rgba(255, 247, 230, 0.96);
box-shadow: inset 0 0 0 1px rgba(255, 214, 102, 0.95);
}
.chat-share-page__room-card-count--idle {
color: #64748b;
background: rgba(241, 245, 249, 0.96);
box-shadow: inset 0 0 0 1px rgba(203, 213, 225, 0.92);
} }
.chat-share-page__room-item { .chat-share-page__room-item {
@@ -342,6 +460,16 @@
line-height: 1.4; line-height: 1.4;
} }
.chat-share-page__room-card-preview {
color: #475569;
font-size: 12px;
line-height: 1.45;
display: -webkit-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.chat-share-page__room-list-empty { .chat-share-page__room-list-empty {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -363,6 +491,35 @@
gap: 6px; gap: 6px;
} }
.chat-share-page__create-room-hint {
font-size: 12px;
line-height: 1.45;
}
.chat-share-page__source-detail-card {
display: grid;
gap: 8px;
padding: 14px;
border-radius: 14px;
background: rgba(248, 250, 252, 0.95);
box-shadow: inset 0 0 0 1px rgba(226, 232, 240, 0.9);
}
.chat-share-page__source-detail-preview {
margin-bottom: 0;
white-space: pre-wrap;
}
.chat-share-page__source-room-chip-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.chat-share-page__source-room-chip.ant-btn {
border-radius: 999px;
}
.chat-share-page__message-list { .chat-share-page__message-list {
display: flex; display: flex;
flex: 1 1 auto; flex: 1 1 auto;
@@ -375,6 +532,46 @@
padding-right: 0; padding-right: 0;
} }
.chat-share-page__message-list--switching,
.chat-share-page__panel--switching,
.chat-share-page__composer-shell--switching {
opacity: 0.68;
}
.chat-share-page__composer-shell--switching {
pointer-events: none;
}
.chat-share-page__panel-switching-indicator {
position: sticky;
top: 0;
z-index: 3;
display: inline-flex;
align-items: center;
gap: 8px;
align-self: flex-start;
margin: 0 0 10px;
padding: 6px 10px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.92);
box-shadow:
inset 0 0 0 1px rgba(191, 204, 220, 0.92),
0 8px 20px rgba(148, 163, 184, 0.16);
backdrop-filter: blur(10px);
}
.chat-share-page__panel-switching-indicator--compact {
margin-bottom: 8px;
}
.chat-share-page__panel-switching-indicator--composer {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
margin: 0;
}
.chat-share-page__conversation-loading-block { .chat-share-page__conversation-loading-block {
display: grid; display: grid;
flex: 1 1 auto; flex: 1 1 auto;
@@ -1839,6 +2036,55 @@
background: #020617; background: #020617;
} }
.chat-share-page__server-command-drawer-shell .ant-drawer-content,
.chat-share-page__server-command-drawer-shell .ant-drawer-wrapper-body {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
background:
linear-gradient(180deg, #f7fafc 0%, #eef3f9 100%),
radial-gradient(circle at top left, rgba(37, 99, 235, 0.08), transparent 26%);
}
.chat-share-page__server-command-drawer-shell .ant-drawer-header,
.chat-share-page__server-command-drawer-shell .ant-drawer-header-title,
.chat-share-page__server-command-drawer-shell .ant-drawer-extra {
min-width: 0;
}
.chat-share-page__server-command-drawer-shell .ant-drawer-header {
border-bottom: 1px solid rgba(196, 210, 226, 0.96);
padding: 14px 18px;
background: rgba(248, 250, 252, 0.94);
}
.chat-share-page__server-command-drawer-shell .ant-drawer-body {
display: flex;
flex: 1 1 auto;
min-width: 0;
min-height: 0;
padding: 0;
overflow: hidden;
}
.chat-share-page__server-command-drawer-body {
display: flex;
flex: 1 1 auto;
width: 100%;
min-width: 0;
min-height: 0;
height: 100%;
}
.chat-share-page__server-command-drawer-body .server-command-page {
flex: 1 1 auto;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
}
.chat-share-page__program-modal-content { .chat-share-page__program-modal-content {
display: flex; display: flex;
flex: 1 1 auto; flex: 1 1 auto;
@@ -1933,6 +2179,14 @@
gap: 10px; gap: 10px;
} }
.chat-share-page__room-list-panel--floating {
border-radius: 16px;
}
.chat-share-page__server-command-drawer-shell .ant-drawer-header {
padding-top: calc(14px + env(safe-area-inset-top, 0px));
}
.chat-share-page__program-app-shell--system-chat-room { .chat-share-page__program-app-shell--system-chat-room {
padding: 0; padding: 0;
} }
@@ -2757,12 +3011,20 @@
.chat-share-page .app-chat-prompt-card__body, .chat-share-page .app-chat-prompt-card__body,
.chat-share-page .app-chat-prompt-card__content, .chat-share-page .app-chat-prompt-card__content,
.chat-share-page .app-chat-prompt-card__options, .chat-share-page .app-chat-prompt-card__options,
.chat-share-page .app-chat-prompt-card__option,
.chat-share-page .app-chat-prompt-card__option-head,
.chat-share-page .app-chat-prompt-card__option-body,
.chat-share-page .app-chat-prompt-card__option-preview-inline,
.chat-share-page .app-chat-prompt-card__preview-shell, .chat-share-page .app-chat-prompt-card__preview-shell,
.chat-share-page .app-chat-prompt-card__preview-toolbar,
.chat-share-page .app-chat-prompt-card__preview-body,
.chat-share-page .app-chat-prompt-card__preview-image,
.chat-share-page .app-chat-prompt-card__preview-frame, .chat-share-page .app-chat-prompt-card__preview-frame,
.chat-share-page .app-chat-prompt-card__preview-markdown, .chat-share-page .app-chat-prompt-card__preview-markdown,
.chat-share-page .app-chat-prompt-card__summary, .chat-share-page .app-chat-prompt-card__summary,
.chat-share-page .app-chat-prompt-card__submitted { .chat-share-page .app-chat-prompt-card__submitted {
width: 100%; width: 100%;
inline-size: 100%;
max-width: 100%; max-width: 100%;
min-width: 0; min-width: 0;
box-sizing: border-box; box-sizing: border-box;
@@ -2793,6 +3055,166 @@
gap: var(--chat-share-page-prompt-footer-gap); gap: var(--chat-share-page-prompt-footer-gap);
} }
.chat-share-page .app-chat-prompt-card__preview-body,
.chat-share-page .app-chat-preview-card__body--structured,
.chat-share-page .app-chat-prompt-card__option-preview-inline,
.chat-share-page .app-chat-prompt-card__preview-shell,
.chat-share-page .app-chat-prompt-card__preview-image,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-table,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-table-scroll,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-image,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-video,
.chat-share-page .app-chat-prompt-card__preview-body .codex-diff-previewer,
.chat-share-page .app-chat-prompt-card__preview-body .codex-diff-previewer__diff-body,
.chat-share-page .app-chat-prompt-card__preview-body .codex-diff-previewer__diff-list,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui__body,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui__editor,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui__editor-body,
.chat-share-page .app-chat-prompt-card__preview-body > *,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui__editor-body > *,
.chat-share-page .app-chat-prompt-card__preview-body .codex-diff-previewer__diff-list > * {
width: 100%;
inline-size: 100%;
max-width: 100%;
min-width: 0;
box-sizing: border-box;
}
.chat-share-page .app-chat-prompt-card__preview-body,
.chat-share-page .app-chat-preview-card__body--structured,
.chat-share-page .app-chat-prompt-card__option-preview-inline,
.chat-share-page .app-chat-prompt-card__preview-shell,
.chat-share-page .app-chat-prompt-card__preview-image {
contain: layout;
}
.chat-share-page .app-chat-message-group__body,
.chat-share-page .app-chat-message-group__activity,
.chat-share-page .app-chat-message-group__activity-stack,
.chat-share-page .app-chat-message-group__activity-children,
.chat-share-page .app-chat-message-group__activity-item,
.chat-share-page .app-chat-preview-card__body,
.chat-share-page .app-chat-preview-card__body--prompt,
.chat-share-page .app-chat-preview-card__body--structured,
.chat-share-page .app-chat-prompt-card__stepper,
.chat-share-page .app-chat-prompt-card__step-panel {
width: 100%;
max-width: 100%;
min-width: 0;
box-sizing: border-box;
}
.chat-share-page .app-chat-message-group__body,
.chat-share-page .app-chat-message-group__activity,
.chat-share-page .app-chat-message-group__activity-stack,
.chat-share-page .app-chat-message-group__activity-children,
.chat-share-page .app-chat-message-group__activity-item,
.chat-share-page .app-chat-preview-card__body,
.chat-share-page .app-chat-preview-card__body--prompt,
.chat-share-page .app-chat-preview-card__body--structured {
overflow-x: hidden;
}
.chat-share-page .app-chat-prompt-card__option-preview-inline,
.chat-share-page .app-chat-prompt-card__preview-shell,
.chat-share-page .app-chat-prompt-card__preview-scroll,
.chat-share-page .app-chat-prompt-card__preview-scroll-inner,
.chat-share-page .app-chat-prompt-card__preview-body,
.chat-share-page .app-chat-prompt-card__preview-image {
overflow-x: hidden;
}
.chat-share-page .app-chat-prompt-card__preview-scroll {
overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-x: contain;
-webkit-overflow-scrolling: touch;
}
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-table-scroll,
.chat-share-page .app-chat-prompt-card__preview-body .codex-diff-previewer__diff-body,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui__editor-body,
.chat-share-page .app-chat-prompt-card__preview-body .codex-diff-previewer__diff-list {
overflow-x: auto;
overflow-y: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
}
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown,
.chat-share-page .app-chat-prompt-card__preview-body .previewer-ui__editor-body {
max-height: min(420px, 70vh);
}
.chat-share-page .app-chat-prompt-card__preview-image,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-image,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-video {
display: block;
width: 100%;
max-width: 100%;
min-width: 0;
}
.chat-share-page .app-chat-prompt-card__description.ant-typography,
.chat-share-page .app-chat-prompt-card__preview-title.ant-typography,
.chat-share-page .app-chat-prompt-card__context-text,
.chat-share-page .app-chat-prompt-card__summary,
.chat-share-page .app-chat-prompt-card__summary-detail {
overflow-wrap: anywhere;
word-break: break-word;
}
.chat-share-page .app-chat-message-group__body .app-chat-panel__preview-rich .previewer-ui__editor-body,
.chat-share-page .app-chat-message-group__body .app-chat-panel__preview-rich--markdown,
.chat-share-page .app-chat-message-group__body .app-chat-panel__preview-table-scroll,
.chat-share-page .app-chat-message-group__body .app-chat-message__preview-text {
max-width: 100%;
max-height: min(420px, 70vh);
overflow-x: auto;
overflow-y: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
}
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview,
.chat-share-page .app-chat-message-group__body .app-chat-panel__preview-rich--markdown .markdown-preview,
.chat-share-page .app-chat-message-group__body .app-chat-panel__preview-rich--markdown .markdown-preview > *,
.chat-share-page .app-chat-message-group__body .previewer-ui__editor-body > *,
.chat-share-page .app-chat-message-group__body .codex-diff-previewer__diff-list > * {
max-width: 100%;
}
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview > *,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview .ant-typography,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview p,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview ul,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview ol,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview li,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview h1,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview h2,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview h3,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview h4,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview h5,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview h6 {
min-width: 0;
max-width: 100%;
overflow-wrap: anywhere;
word-break: break-word;
white-space: normal;
}
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview ul,
.chat-share-page .app-chat-prompt-card__preview-body .app-chat-panel__preview-rich--markdown .markdown-preview ol {
margin-inline: 0;
padding-inline-start: 18px;
}
.chat-share-page .app-chat-preview-card__header, .chat-share-page .app-chat-preview-card__header,
.chat-share-page .app-chat-preview-card--prompt .app-chat-preview-card__header { .chat-share-page .app-chat-preview-card--prompt .app-chat-preview-card__header {
align-items: center; align-items: center;

File diff suppressed because it is too large Load Diff

View File

@@ -1835,12 +1835,43 @@
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
padding: 0 8px 8px; padding: 0 8px 8px;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: auto;
overscroll-behavior: contain;
} }
.app-chat-preview-card__body--prompt-collapsed { .app-chat-preview-card__body--prompt-collapsed {
display: none; display: none;
} }
.app-chat-preview-card--prompt,
.app-chat-preview-card--structured {
width: min(100%, 720px);
min-width: 0;
max-width: 100%;
}
.app-chat-preview-card__body--structured {
display: flex;
flex-direction: column;
gap: 8px;
padding: 0 8px 8px;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: auto;
overscroll-behavior: contain;
}
.app-chat-preview-card__description.ant-typography {
margin: 0;
color: #334155;
white-space: pre-wrap;
word-break: break-word;
}
.app-chat-prompt-card__description.ant-typography { .app-chat-prompt-card__description.ant-typography {
margin: 0; margin: 0;
font-size: 12px; font-size: 12px;
@@ -2028,6 +2059,8 @@
.app-chat-prompt-card__option-preview-inline { .app-chat-prompt-card__option-preview-inline {
margin-top: 6px; margin-top: 6px;
min-width: 0;
max-width: 100%;
} }
@media (max-width: 640px) { @media (max-width: 640px) {
@@ -2043,10 +2076,24 @@
.app-chat-prompt-card__preview-shell { .app-chat-prompt-card__preview-shell {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%;
min-width: 0;
max-width: 100%;
overflow: hidden; overflow: hidden;
border: 1px solid rgba(148, 163, 184, 0.2); border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 10px; border-radius: 10px;
background: rgba(241, 245, 249, 0.8); background: rgba(241, 245, 249, 0.8);
box-sizing: border-box;
}
.app-chat-prompt-card__preview-body {
width: 100%;
min-width: 0;
max-width: 100%;
max-height: min(420px, 70vh);
overflow: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
} }
.app-chat-prompt-card__stepper { .app-chat-prompt-card__stepper {
@@ -2287,6 +2334,18 @@
word-break: break-word; word-break: break-word;
} }
.app-chat-prompt-card__context,
.app-chat-prompt-card__description.ant-typography,
.app-chat-prompt-card__result.ant-typography,
.app-chat-prompt-card__stepper,
.app-chat-prompt-card__step-panel,
.app-chat-prompt-card__options,
.app-chat-prompt-card__free-text,
.app-chat-prompt-card__footer {
min-width: 0;
max-width: 100%;
}
.app-chat-prompt-card__submitted { .app-chat-prompt-card__submitted {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;

View File

@@ -268,7 +268,7 @@ function resolveWorkServerControlStatus(
return { return {
statusTone: 'online', statusTone: 'online',
statusLabel: '배포 가능', statusLabel: '최신 실행 중',
}; };
} }