feat: enhance session UX and codex defaults

This commit is contained in:
shiyue
2026-05-15 18:35:38 +08:00
parent a6f3ab0485
commit 62ab6f358d
5 changed files with 564 additions and 45 deletions

View File

@@ -99,6 +99,8 @@
let sidebarSwipe = null;
let pendingAttachments = [];
let uploadingAttachments = [];
let attachmentPreviewModal = null;
const attachmentPreviewCache = new Map();
let loginPasswordValue = ''; // store login password for force-change flow
let currentCwd = null;
let currentSessionRunning = false;
@@ -1119,6 +1121,7 @@
},
});
} catch {}
clearAttachmentPreviewCache(id);
}
function ensureAuthenticatedWs() {
@@ -1160,14 +1163,184 @@
});
}
function renderAttachmentLabels(attachments, options = {}) {
function clearAttachmentPreviewCache(id) {
const entry = attachmentPreviewCache.get(id);
if (entry?.url && entry.objectUrl) URL.revokeObjectURL(entry.url);
attachmentPreviewCache.delete(id);
}
async function getAttachmentPreviewUrl(attachment) {
const id = String(attachment?.id || '').trim();
if (!id) throw new Error('图片附件缺少 ID');
if (attachment.storageState === 'expired') {
throw new Error('图片已过期');
}
if (attachment.previewUrl) return attachment.previewUrl;
const cached = attachmentPreviewCache.get(id);
if (cached?.url) return cached.url;
if (cached?.promise) return cached.promise;
const promise = (async () => {
await ensureAuthenticatedWs();
if (!authToken) {
throw new Error('登录状态已失效,请刷新页面后重新登录再预览图片。');
}
const url = `/api/attachments/${encodeURIComponent(id)}?token=${encodeURIComponent(authToken)}`;
attachmentPreviewCache.set(id, { url, objectUrl: false });
return url;
})().catch((err) => {
attachmentPreviewCache.delete(id);
throw err;
});
attachmentPreviewCache.set(id, { promise });
return promise;
}
function closeAttachmentPreviewModal() {
if (!attachmentPreviewModal) return;
const { overlay, escapeHandler } = attachmentPreviewModal;
if (escapeHandler) document.removeEventListener('keydown', escapeHandler);
if (overlay && overlay.parentNode) overlay.parentNode.removeChild(overlay);
attachmentPreviewModal = null;
}
async function openAttachmentPreviewModal(attachment) {
if (!attachment || attachment.storageState === 'expired') {
showToast('图片已过期,无法预览');
return;
}
closeAttachmentPreviewModal();
const overlay = document.createElement('div');
overlay.className = 'modal-overlay attachment-preview-overlay';
overlay.innerHTML = `
<div class="modal-panel modal-panel-wide attachment-preview-panel">
<div class="modal-header">
<span class="modal-title">图片预览</span>
<button class="modal-close-btn" type="button" aria-label="关闭">✕</button>
</div>
<div class="attachment-preview-body">
<div class="attachment-preview-stage is-loading">
<div class="attachment-preview-placeholder">正在加载图片…</div>
<img class="attachment-preview-image" alt="${escapeHtml(attachment.filename || 'image')}" hidden>
</div>
<div class="attachment-preview-meta">
<div class="attachment-preview-name">${escapeHtml(attachment.filename || 'image')}</div>
<div class="attachment-preview-desc">${escapeHtml(formatFileSize(attachment.size || 0))} · 点击空白处关闭</div>
</div>
</div>
</div>
`;
document.body.appendChild(overlay);
const stageEl = overlay.querySelector('.attachment-preview-stage');
const imgEl = overlay.querySelector('.attachment-preview-image');
const placeholderEl = overlay.querySelector('.attachment-preview-placeholder');
const closeBtn = overlay.querySelector('.modal-close-btn');
const finishClose = () => closeAttachmentPreviewModal();
attachmentPreviewModal = {
overlay,
escapeHandler: null,
};
attachmentPreviewModal.escapeHandler = (e) => {
if (e.key === 'Escape') finishClose();
};
document.addEventListener('keydown', attachmentPreviewModal.escapeHandler);
closeBtn.addEventListener('click', finishClose);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) finishClose();
});
try {
const url = await getAttachmentPreviewUrl(attachment);
if (!attachmentPreviewModal || attachmentPreviewModal.overlay !== overlay) return;
imgEl.onload = () => {
if (!attachmentPreviewModal || attachmentPreviewModal.overlay !== overlay) return;
imgEl.hidden = false;
placeholderEl.hidden = true;
stageEl.classList.remove('is-loading');
stageEl.classList.add('is-ready');
};
imgEl.onerror = () => {
if (!attachmentPreviewModal || attachmentPreviewModal.overlay !== overlay) return;
placeholderEl.textContent = '图片加载失败';
stageEl.classList.remove('is-loading');
stageEl.classList.add('is-error');
};
imgEl.src = url;
} catch (err) {
if (!attachmentPreviewModal || attachmentPreviewModal.overlay !== overlay) return;
placeholderEl.textContent = err.message || '图片预览失败';
stageEl.classList.remove('is-loading');
stageEl.classList.add('is-error');
}
}
function hydrateAttachmentPreviews(root, attachments = []) {
if (!root) return;
const attachmentMap = new Map((Array.isArray(attachments) ? attachments : []).map((attachment) => [attachment.id, attachment]));
root.querySelectorAll('[data-attachment-id]').forEach((node) => {
const attachment = attachmentMap.get(node.dataset.attachmentId);
if (!attachment) return;
const imgEl = node.querySelector('.msg-attachment-thumb-image');
const placeholderEl = node.querySelector('.msg-attachment-thumb-placeholder');
const isExpired = attachment.storageState === 'expired';
if (!isExpired) {
getAttachmentPreviewUrl(attachment)
.then((url) => {
if (!node.isConnected) return;
imgEl.src = url;
imgEl.onload = () => {
if (!node.isConnected) return;
imgEl.hidden = false;
placeholderEl.hidden = true;
node.classList.add('is-loaded');
};
imgEl.onerror = () => {
if (!node.isConnected) return;
placeholderEl.textContent = '图片加载失败';
node.classList.add('is-error');
};
})
.catch((err) => {
if (!node.isConnected) return;
placeholderEl.textContent = err.message || '图片加载失败';
node.classList.add('is-error');
});
}
node.addEventListener('click', () => openAttachmentPreviewModal(attachment));
});
}
function renderAttachmentPreviews(attachments, options = {}) {
if (!Array.isArray(attachments) || attachments.length === 0) return '';
const labels = attachments.map((attachment) => {
const stateSuffix = attachment.storageState === 'expired' ? '(已过期)' : '';
const items = attachments.map((attachment) => {
const state = attachment.storageState || 'available';
const name = escapeHtml(attachment.filename || 'image');
return `<span class="msg-attachment-label">图片: ${name}${stateSuffix}</span>`;
const size = formatFileSize(attachment.size || 0);
const isExpired = state === 'expired';
return `
<button class="msg-attachment-card${isExpired ? ' is-expired' : ''}" type="button" data-attachment-id="${escapeHtml(attachment.id || '')}" data-attachment-state="${escapeHtml(state)}" data-attachment-name="${name}" ${isExpired ? 'disabled' : ''} title="${isExpired ? '图片已过期' : '点击放大预览'}">
<span class="msg-attachment-thumb">
<span class="msg-attachment-thumb-placeholder">${isExpired ? '已过期' : '加载中'}</span>
<img class="msg-attachment-thumb-image" alt="${name}" hidden>
</span>
<span class="msg-attachment-meta">
<span class="msg-attachment-name">图片: ${name}</span>
<span class="msg-attachment-note">${isExpired ? '已过期' : `${size} · 点击放大预览`}</span>
</span>
</button>
`;
}).join('');
return `<div class="msg-attachments${options.compact ? ' compact' : ''}">${labels}</div>`;
return `<div class="msg-attachments${options.compact ? ' compact' : ''}">${items}</div>`;
}
function renderPendingAttachments() {
@@ -1262,7 +1435,9 @@
try {
const results = await Promise.allSettled(files.map(async (file) => {
const optimized = await compressImageFile(file);
return uploadImageFile(optimized);
const uploaded = await uploadImageFile(optimized);
uploaded.previewUrl = URL.createObjectURL(file);
return uploaded;
}));
const errors = [];
for (const result of results) {
@@ -2299,15 +2474,16 @@
bubble.appendChild(textNode);
}
if (attachments.length > 0) {
bubble.insertAdjacentHTML('beforeend', renderAttachmentLabels(attachments));
bubble.insertAdjacentHTML('beforeend', renderAttachmentPreviews(attachments));
}
} else {
renderAssistantContent(bubble, content);
if (attachments.length > 0) {
bubble.insertAdjacentHTML('beforeend', renderAttachmentLabels(attachments));
bubble.insertAdjacentHTML('beforeend', renderAttachmentPreviews(attachments));
}
}
hydrateAttachmentPreviews(bubble, attachments);
div.appendChild(avatar);
div.appendChild(bubble);
return div;
@@ -3258,7 +3434,10 @@
header.title = group.cwd || group.name;
header.innerHTML = `
<span class="session-project-name">${escapeHtml(group.name)}</span>
<span class="session-project-count">${group.sessions.length}</span>
<span class="session-project-header-actions">
<span class="session-project-count">${group.sessions.length}</span>
<button class="session-project-create" type="button" title="在此项目新建会话" aria-label="在此项目新建会话">+</button>
</span>
`;
groupEl.appendChild(header);
@@ -3266,6 +3445,11 @@
groupEl.appendChild(createSessionListItem(s));
}
header.querySelector('.session-project-create').addEventListener('click', (e) => {
e.stopPropagation();
quickCreateProjectSession(group.cwd || '', { agent: currentAgent, mode: currentMode });
});
sessionList.appendChild(groupEl);
}
@@ -3604,7 +3788,8 @@
showOptionPicker('选择 Codex 模型', baseOptions, current.base || '', (baseValue) => {
const base = String(baseValue || '').trim();
const thinkingOptions = [
{ value: '', label: '无 (默认)', desc: '不附加 (medium/high/xhigh) 后缀' },
{ value: '', label: '无 (默认)', desc: '不附加 (low/medium/high/xhigh) 后缀' },
{ value: 'low', label: 'low', desc: '较轻 thinking' },
{ value: 'medium', label: 'medium', desc: '中等 thinking' },
{ value: 'high', label: 'high', desc: '更强 thinking' },
{ value: 'xhigh', label: 'xhigh', desc: '最强 thinking' },
@@ -4994,6 +5179,21 @@
try { localStorage.setItem(RECENT_CWD_KEY, JSON.stringify(list)); } catch {}
}
function requestNewSession(options = {}) {
const cwd = options.cwd || null;
const rawCwd = options.rawCwd !== undefined ? options.rawCwd : (cwd || '');
const agent = normalizeAgent(options.agent || currentAgent);
const mode = ['default', 'plan', 'yolo'].includes(options.mode) ? options.mode : currentMode;
pendingNewSessionRequest = {
cwd,
rawCwd,
agent,
mode,
};
if (cwd) saveRecentCwd(cwd);
send({ type: 'new_session', cwd, agent, mode });
}
// --- New Session Modal ---
let _onCwdSuggestions = null;
@@ -5119,15 +5319,13 @@
function createSession() {
const cwd = getEffectiveCwd();
const rawCwd = cwdInput.value.trim();
pendingNewSessionRequest = {
close();
requestNewSession({
cwd,
rawCwd,
agent: targetAgent,
mode: requestedMode,
};
close();
if (cwd) saveRecentCwd(cwd);
send({ type: 'new_session', cwd, agent: targetAgent, mode: requestedMode });
});
}
pickDirBtn.addEventListener('click', () => {
@@ -5167,6 +5365,16 @@
cwdInput.focus();
}
function quickCreateProjectSession(cwd, options = {}) {
const targetCwd = String(cwd || '').trim();
requestNewSession({
cwd: targetCwd || null,
rawCwd: targetCwd,
agent: options.agent || currentAgent,
mode: options.mode || currentMode,
});
}
// --- Import Native Session Modal ---
let _onNativeSessions = null;