Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions App/Sources/CatalystBusinessCheck.swift
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,8 @@ enum CatalystBusinessCheck {
try await until("stopped message displayed") { !store.isAgentRunningInActiveChat && controller.messages.last?.state == .stopped }
try check("stop_preserves_received_text", store.messages.last?.completionState == .interrupted
&& store.messages.last?.text.hasPrefix(received) == true && controller.messages.last?.markdown.hasPrefix(received) == true)
try await verifyDividerLanguage(controller, workspace: store)
try check("divider_interface_language_updates", true)
try await verifyDividerResize(controller)
try check("divider_batches_widths_and_reflows_during_drag", true)
try await verifyConversationAppearance(controller, workspace: store)
Expand Down Expand Up @@ -936,6 +938,34 @@ enum CatalystBusinessCheck {
return true
}

private static func verifyDividerLanguage(_ controller: ConversationController, workspace: WorkspaceStore) async throws {
guard let window = controller.view.window,
let split = descendants(window).compactMap({ $0 as? StableDocumentSplitView }).first,
split.dividerViews.count == 2, split.dividerViews.allSatisfy({ !$0.isHidden }) else {
throw Failure("three-pane dividers unavailable")
}
let originalLanguage = workspace.interfaceLanguage
defer { workspace.setInterfaceLanguage(originalLanguage) }
for language in [WeiBeiInterfaceLanguage.english, .chinese] {
workspace.setInterfaceLanguage(language)
try await until("divider applies changed interface language") {
let expected = (
language.text("调整分栏宽度", "Resize panes"),
language.text("双击均分相邻两栏;按住 Option 松手可跳过吸附。", "Double-click to split the adjacent panes evenly. Hold Option while releasing to skip snapping."),
language.text("均分相邻两栏", "Split adjacent panes evenly")
)
return split.dividerViews.allSatisfy {
$0.interfaceLanguage == language
&& $0.accessibilityLabel == expected.0
&& $0.accessibilityHint == expected.1
&& $0.accessibilityCustomActions?.first?.name == expected.2
}
&& controller.collection.accessibilityLabel
== language.text("会话消息列表", "Conversation messages")
}
}
}

private static func verifyDividerResize(_ controller: ConversationController) async throws {
guard let window = controller.view.window,
let split = descendants(window).compactMap({ $0 as? StableDocumentSplitView }).first,
Expand Down
18 changes: 14 additions & 4 deletions App/Sources/CatalystWorkspaceChrome.swift
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,11 @@ struct StableDocumentWorkspace: UIViewRepresentable {
coordinator.onFramesChange = onFramesChange
coordinator.onExpansionRequestHandled = onExpansionRequestHandled
coordinator.reduceMotion = reduceMotion
for divider in view.dividerViews { divider.appearanceMode = appearanceMode; divider.reduceMotion = reduceMotion }
for divider in view.dividerViews {
divider.appearanceMode = appearanceMode
divider.reduceMotion = reduceMotion
divider.interfaceLanguage = store.interfaceLanguage
}
coordinator.update(state: StableDocumentLayoutState(normalizedOrder: WorkspacePaneRole.normalized(normalizedOrder),
visibleOrder: visibleOrder, firstSplit: firstSplit, secondSplit: secondSplit, halfSplit: halfSplit),
draggedRole: draggedRole, expansionRequest: expansionRequest, in: view)
Expand Down Expand Up @@ -333,6 +337,12 @@ final class CatalystDividerView: UIView {
var skipSnap = false
var appearanceMode: WeiBeiAppearanceMode = .paper { didSet { setNeedsDisplay() } }
var reduceMotion = false
var interfaceLanguage: WeiBeiInterfaceLanguage = .chinese {
didSet {
guard interfaceLanguage != oldValue else { return }
refreshCopy()
}
}
private var hovering = false
private var pressed = false
private let accent = CALayer()
Expand All @@ -351,9 +361,9 @@ final class CatalystDividerView: UIView {
}
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
private func refreshCopy() {
accessibilityLabel = CatalystInterfaceCopy.text("调整分栏宽度", "Resize panes")
accessibilityHint = CatalystInterfaceCopy.text("双击均分相邻两栏;按住 Option 松手可跳过吸附。", "Double-click to split the adjacent panes evenly. Hold Option while releasing to skip snapping.")
accessibilityCustomActions = [UIAccessibilityCustomAction(name: CatalystInterfaceCopy.text("均分相邻两栏", "Split adjacent panes evenly"), target: self, selector: #selector(equalize))]
accessibilityLabel = interfaceLanguage.text("调整分栏宽度", "Resize panes")
accessibilityHint = interfaceLanguage.text("双击均分相邻两栏;按住 Option 松手可跳过吸附。", "Double-click to split the adjacent panes evenly. Hold Option while releasing to skip snapping.")
accessibilityCustomActions = [UIAccessibilityCustomAction(name: interfaceLanguage.text("均分相邻两栏", "Split adjacent panes evenly"), target: self, selector: #selector(equalize))]
}
@objc private func drag(_ gesture: UIPanGestureRecognizer) {
skipSnap = gesture.modifierFlags.contains(.alternate) || gesture.state == .cancelled
Expand Down
5 changes: 4 additions & 1 deletion App/Sources/ConversationController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ final class ConversationController: UIViewController, UICollectionViewDataSource
didSet {
CatalystInterfaceCopy.language = interfaceLanguage
latest.accessibilityLabel = interfaceLanguage.text("回到最新消息", "Jump to latest")
if isViewLoaded {
collection.accessibilityLabel = interfaceLanguage.text("会话消息列表", "Conversation messages")
}
}
}
private var loadingSession = false
Expand Down Expand Up @@ -98,7 +101,7 @@ final class ConversationController: UIViewController, UICollectionViewDataSource
collection.register(MessageCell.self, forCellWithReuseIdentifier: "message")
collection.alwaysBounceVertical = true
collection.keyboardDismissMode = .none
collection.accessibilityLabel = "会话消息列表"
collection.accessibilityLabel = interfaceLanguage.text("会话消息列表", "Conversation messages")
flow.itemHeight = { [weak self] path in self?.itemHeight(at: path) ?? 0 }
flow.replyStartSection = { [weak self] in
guard let self, reservesReplySpace else { return nil }
Expand Down
5 changes: 3 additions & 2 deletions App/script/check-ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,10 @@ required_business_checks = {
'conversation_appearance_and_scale_after_resize',
'history_and_long_answer_through_original_messages',
'floating_11pt_math_diagram_and_layout',
'divider_interface_language_updates',
}
# Require every original gate and the new floating gate; verify() above also
# rejects any failed additional gate, including accepted PR515's language check.
# Require all baseline, floating, and interface-language gates; verify() above
# rejects failures in additional gates as well.
assert required_business_checks <= business['checks'].keys(), business
assert business['floating_rich_answer']['body_font_size_pt'] == 11, business
assert business['floating_rich_answer']['math_images'] == 2, business
Expand Down
14 changes: 12 additions & 2 deletions Sources/WeiBei/OfficeReader/office.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ let pptSearchOrder: { note: boolean; index: number }[] = [];
const clean = (text?: string | null) => (text ?? '').replace(/\s+/g, ' ').trim();
let english = false;
const t = (zh: string, en: string) => (english ? en : zh);
const pageLabel = (page: number) => t(`第 ${page} 页`, `Page ${page}`);

function fail(error: unknown) {
loadError = error instanceof Error ? error.message : String(error);
Expand Down Expand Up @@ -340,6 +341,15 @@ function attachNote(index: number, wrapper: HTMLElement | null) {
wrapper.append(button, note);
}

function setLanguage(language?: string) {
english = language === 'english';
root?.querySelectorAll<HTMLElement>('[data-weibei-slide-label]').forEach(label => {
const page = Number(label.dataset.weibeiSlideLabel);
if (Number.isFinite(page)) label.textContent = pageLabel(page);
});
if (viewer || root) post('contentRailSections', sections());
}

async function open(url: string | ArrayBuffer, format: string, language?: string) {
english = language === 'english';
root = document.getElementById('office-document')!;
Expand Down Expand Up @@ -425,5 +435,5 @@ window.addEventListener('scroll', () => {
if (active) post('contentRailActive', { id: active.dataset.weibeiLocation, reason: 'scroll' });
}, { passive: true });

(window as any).WeiBeiOffice = { open, math, drawWMFText, renderGraphic, graphicRelations, has3DChart, render3DChart, goTo, find, searchResults, activateSearchResult, sections, sourceOrder, applyMarks, attachNote, get isPresentation() { return Boolean(viewer); }, get error() { return loadError; } };
(window as any).WeiBeiContentRail = { installed: true, scrollTo: (id: string) => { void goTo(id); }, scan: () => post('contentRailSections', sections()) };
(window as any).WeiBeiOffice = { open, math, drawWMFText, renderGraphic, graphicRelations, has3DChart, render3DChart, goTo, find, searchResults, activateSearchResult, sections, sourceOrder, applyMarks, attachNote, pageLabel, setLanguage, get isPresentation() { return Boolean(viewer); }, get error() { return loadError; } };
(window as any).WeiBeiContentRail = { installed: true, scrollTo: (id: string) => { void goTo(id); }, scan: () => post('contentRailSections', sections()), setLanguage };
2 changes: 1 addition & 1 deletion Sources/WeiBei/OfficeReader/vendor-patches.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export function parseOfficeCharts(bytes) {
replace(' requestAnimationFrame(() => {\n if (!i.isConnected)', ' setTimeout(() => {\n if (!i.isConnected)');
replace('if (n.setOption(t), r == null || r.add(n), typeof ResizeObserver > "u")', 'if (n.setOption({ ...t, animation: false }), n.getZr().flush(), r == null || r.add(n), typeof ResizeObserver > "u")');
replace(' const i = document.createElement("div");\n i.style.width = "100%", i.style.flex', ' if (window.WeiBeiOffice.has3DChart(e.chartPath)) { r.appendChild(window.WeiBeiOffice.render3DChart(e.chartPath, e.size)); return r; }\n const i = document.createElement("div");\n i.style.width = "100%", i.style.flex');
replace('o.textContent = `Slide ${t + 1}`', 'o.dataset.weibeiAnnotationUi = "true", o.textContent = `第 ${t + 1} 页`');
replace('o.textContent = `Slide ${t + 1}`', 'o.dataset.weibeiAnnotationUi = "true", o.dataset.weibeiSlideLabel = String(t + 1), o.textContent = window.WeiBeiOffice.pageLabel(t + 1)');
// Keep note controls outside the lazily mounted slide content.
replace('return { item: i, wrapper: a };', 'window.WeiBeiOffice.attachNote(t, i);\n return { item: i, wrapper: a };');
// Equal visibility must not replace the page the reader just chose.
Expand Down
4 changes: 2 additions & 2 deletions Sources/WeiBei/Resources/Editor/editor-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@
},
{
"name": "office-entry.js.deflate",
"bytes": 1446591,
"sha256": "7cb1fb231f2cd692ee889c6cd71c4ffea52714b4ab09ced55e5dffbbabd9bbaf"
"bytes": 1446661,
"sha256": "3b06ce82d0b4f04e21a9f17674a35e2ddc611d1efb786684db6e2ac6e8deba37"
},
{
"name": "office-licenses.txt",
Expand Down
Binary file modified Sources/WeiBei/Resources/Editor/office-entry.js.deflate
Binary file not shown.
29 changes: 16 additions & 13 deletions Sources/WeiBei/Stores/WorkspaceInteractionState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,13 @@ final class WorkspaceInteractionState: ObservableObject {
/// "记"模式的独立草稿;与问的 agentDraft 互不覆盖,提交后清空。
/// 按选区锚点分开存放。换到另一段时只显示那段自己的草稿。
@Published var selectionNoteDraft = ""
private var selectionNoteDraftsByAnchor: [String: String] = [:]
private struct SelectionNoteDraftKey: Hashable {
let source: SelectionSource
let itemID: String?
let normalizedText: String
let documentAnchor: SelectionDocumentAnchor?
}
private var selectionNoteDraftsByAnchor: [SelectionNoteDraftKey: String] = [:]

func rebaseSelectionNoteDraft(from previous: SelectionContext?, to next: SelectionContext?) {
let previousKey = previous.map(Self.selectionNoteDraftKey)
Expand All @@ -59,18 +65,15 @@ final class WorkspaceInteractionState: ObservableObject {
selectionNoteDraft = nextKey.flatMap { selectionNoteDraftsByAnchor[$0] } ?? ""
}

static func selectionNoteDraftKey(for context: SelectionContext) -> String {
var parts = [
"\(context.source)",
context.itemID ?? "",
SelectionAttachmentMerge.normalized(context.text),
]
if let anchor = context.documentAnchor,
let data = try? JSONEncoder().encode(anchor),
let encoded = String(data: data, encoding: .utf8) {
parts.append(encoded)
}
return parts.joined(separator: "\u{1f}")
private static func selectionNoteDraftKey(
for context: SelectionContext
) -> SelectionNoteDraftKey {
SelectionNoteDraftKey(
source: context.source,
itemID: context.itemID,
normalizedText: SelectionAttachmentMerge.normalized(context.text),
documentAnchor: context.documentAnchor
)
}

/// Selection capsule position. Anchor-only drag/scroll updates can suppress
Expand Down
15 changes: 6 additions & 9 deletions Sources/WeiBei/Stores/WorkspaceStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6322,16 +6322,12 @@ final class WorkspaceStore: ObservableObject {
}
invalidateAgentContext()
save()
let status = sourceItem == nil
? ui("已新建空白笔记:\(url.lastPathComponent)", "Created blank note: \(url.lastPathComponent)")
: ui("已为当前文稿新建笔记:\(url.lastPathComponent)", "Created a note for this document: \(url.lastPathComponent)")
requestNoteSelectionTransition(to: item.id) { [weak self] in
guard let self else { return }
activeNotebookItemID = item.id
noteText = markdown
revealRichWritingSurface()
focus(.notes)
showTransientNoteStatus(status)
}
return item
} catch {
Expand Down Expand Up @@ -10104,18 +10100,18 @@ final class WorkspaceStore: ObservableObject {
_ = await flushPendingWorkspaceSaveAsync()
} catch is CancellationError {
guard activeAgentRequestID == requestID else { return }
let userStopped = agentRuns[target.sessionID]?.isStoppingAgent == true
if let replyMessageID {
interruptAgentReply(
requestID: requestID,
messageID: replyMessageID,
chatID: target.sessionID,
kind: .cancelled,
restoreDraft: questionOverride == nil
restoreDraft: questionOverride == nil && !userStopped
)
}
// A2: 用户主动停止(stopAgent 已置 isStoppingAgent)不回填旧问题;
// 其他取消仅在输入框为空时回填。
let userStopped = agentRuns[target.sessionID]?.isStoppingAgent == true
if questionOverride == nil, !userStopped {
restoreComposerDraftIfEmpty(question, for: target.sessionID)
}
Expand All @@ -10136,15 +10132,16 @@ final class WorkspaceStore: ObservableObject {
}
// A2: the failed question comes back only when the composer is empty.
let kind = AgentFailureKind.classify(error)
let userStopped = agentRuns[target.sessionID]?.isStoppingAgent == true
if didStartModelRequest {
agentAuthenticationStatus.recordFailure(
kind,
provider: requestProvider,
authMethod: requestAuthMethod
)
}
if questionOverride == nil {
// A2: 失败时仅在输入框为空时回填上一问。
if questionOverride == nil, !userStopped {
// A2: 失败时仅在输入框为空时回填上一问;网络层取消同样保留主动停止的空草稿。
restoreComposerDraftIfEmpty(question, for: target.sessionID)
}
if activeStudySessionID == target.sessionID {
Expand All @@ -10164,7 +10161,7 @@ final class WorkspaceStore: ObservableObject {
chatID: target.sessionID,
kind: kind,
fallbackText: failureText,
restoreDraft: questionOverride == nil
restoreDraft: questionOverride == nil && !userStopped
)
} else if let previousReply {
// A3: 重新生成在消息创建前就失败时,原回答保持原样,只标中断、失败原因和重试。
Expand Down
20 changes: 15 additions & 5 deletions Sources/WeiBei/Views/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,6 @@ struct ContentView: View {
.background {
LibraryAwareEscapeBridge(
courseWorkspacePresented: store.courseWorkspacePresented,
onToggleLibrary: { store.toggleLibrary() },
onDismissFloatingAgent: { store.dismissFloatingSelectionAgent() },
onHideReaderSearch: {
store.hideDocumentSearch()
Expand Down Expand Up @@ -607,7 +606,6 @@ private struct LibraryAwareEscapeBridge: View {
@EnvironmentObject private var interaction: WorkspaceInteractionState
@EnvironmentObject private var store: WorkspaceStore
let courseWorkspacePresented: Bool
let onToggleLibrary: () -> Void
let onDismissFloatingAgent: () -> Void
let onHideReaderSearch: () -> Void

Expand All @@ -618,8 +616,6 @@ private struct LibraryAwareEscapeBridge: View {
store.notePickerPresented = false
store.focus(.notes)
})
} else if !courseWorkspacePresented && libraryDrawer.isOpen {
EscapeKeyBridge(onEscape: onToggleLibrary)
} else if !courseWorkspacePresented && !libraryDrawer.isOpen && showsGlobalFloatingAgent {
EscapeKeyBridge(onEscape: onDismissFloatingAgent)
} else if !courseWorkspacePresented && !libraryDrawer.isOpen && paneState.showDocumentSearch {
Expand Down Expand Up @@ -722,7 +718,21 @@ struct WeiBeiPlainTextField: UIViewRepresentable {
}

func sizeThatFits(_ proposal: ProposedViewSize, uiView: WeiBeiSearchTextField, context: Context) -> CGSize? {
CGSize(width: proposal.width ?? 160, height: proposal.height ?? max(fontSize + 8, 22))
let intrinsicHeight = uiView.intrinsicContentSize.height
let fittedHeight = intrinsicHeight.isFinite && intrinsicHeight > 0
? intrinsicHeight
: uiView.sizeThatFits(
CGSize(
width: proposal.width ?? UIView.layoutFittingCompressedSize.width,
height: UIView.layoutFittingCompressedSize.height
)
).height
return CGSize(
width: proposal.width ?? 160,
height: fittedHeight.isFinite && fittedHeight > 0
? fittedHeight
: max(fontSize + 8, 22)
)
}

func makeCoordinator() -> Coordinator { Coordinator(self) }
Expand Down
Loading
Loading