Skip to content

feature: think block can be shown or hidden by user and beautify some ui setting - #18

Merged
luorome31 merged 16 commits into
mainfrom
feat/think-filter
Mar 29, 2026
Merged

luorome31 merged 16 commits into
mainfrom
feat/think-filter

Conversation

@luorome31

@luorome31 luorome31 commented Mar 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

实现 AI 思考内容的显示/隐藏功能:

  • 添加 showThinkContent 设置项到 StorageSchema
  • 在 NoteCard 中实现状态机,根据设置过滤 <think>...</think> 标签内容
  • 在 Popup UI 添加"显示思考内容"开关(灰色=隐藏,红色=显示)
  • 流式渲染时实时过滤思考内容
  • 导出时保留完整内容(包括思考内容)

主要功能

  1. Popup 开关

    • 灰色按钮:隐藏 THINK 内容(默认)
    • 红色按钮:显示 THINK 内容
  2. 流式过滤

    • 使用状态机实时跟踪 <think> 和 </think> 标签
    • 支持跨 chunk 的标签检测
    • 切换设置时自动重新渲染
  3. 导出保真

    • _aiBuffer 始终保留完整内容
    • 导出 Markdown 时包含完整思考过程

Test Plan

  • 灰色按钮(隐藏)→ Alt+Click 创建笔记,思考内容不显示
  • 红色按钮(显示)→ Alt+Click 创建笔记,思考内容正常显示
  • 切换设置后,新创建的笔记符合预期
  • 导出 Markdown 包含完整思考内容

Copilot AI review requested due to automatic review settings March 29, 2026 09:00
@luorome31
luorome31 marked this pull request as draft March 29, 2026 09:01

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a user-facing toggle to show/hide LLM “think/cognition” content and adjusts popup/UI + content-script behaviors to support it.

Changes:

  • Introduces showThinkContent persisted setting and popup toggle UI.
  • Implements streaming-time filtering of <think> blocks in NoteCard and keeps full AI buffer for export.
  • Updates extension metadata (manifest name/description) and small UI tweaks (highlight border color, popup header/title, debug gating for overlay).

Reviewed changes

Copilot reviewed 9 out of 13 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/pages/popup/popup.css Adjusts popup header layout and adds styling for the title.
src/pages/popup/Popup.tsx Adds “Show think content” toggle and stores showThinkContent in chrome.storage.
src/pages/content/services/sanitizeHtml.ts Changes sanitizer behavior for think/cognition tags (now removes tag + content).
src/pages/content/services/NoteCard.ts Adds buffering + filtering logic for think blocks and dynamic card width support.
src/pages/content/services/HighlightController.ts Changes highlight dashed border color.
src/pages/content/index.tsx Passes selection rect width into NoteCard; hides debug overlay when apiConfig.debug is false.
src/pages/background/storage.types.ts Adds showThinkContent to StorageSchema.
src/pages/background/config.ts Simplifies apiConfig to a minimal debug-only object.
manifest.json Updates extension name/description and removes newtab override.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +6 to +36
@@ -31,9 +31,9 @@ export function sanitizeHtml(html: string): string {
sanitized = sanitized.replace(/expression\s*\([^)]*\)/gi, '');
sanitized = sanitized.replace(/binding\s*:/gi, 'noop:');
sanitized = sanitized.replace(/url\s*\(['"]javascript:[^'"]*['"]\)/gi, '');
// Remove think/cognition tags but keep their content
sanitized = sanitized.replace(/<think[^>]*>([\s\S]*?)<\/think>/gi, '$1');
sanitized = sanitized.replace(/<cognition[^>]*>([\s\S]*?)<\/cognition>/gi, '$1');
// Remove think/cognition tags and their content entirely
sanitized = sanitized.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '');
sanitized = sanitized.replace(/<cognition[^>]*>[\s\S]*?<\/cognition>/gi, '');

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sanitizeHtml now removes <think>/<cognition> blocks and their content unconditionally. That makes the new “Show think content” toggle ineffective because NoteCard always calls sanitizeHtml even when showThinkContent is true, so think content can never be displayed. Consider reverting to stripping only the tags (keeping inner text) for display sanitization, or add an option/alternate sanitizer so think content is preserved when the setting is enabled.

Copilot uses AI. Check for mistakes.
Comment on lines +299 to +332
if (!this._showThinkContent) {
for (const char of chunk) {
// Add to tag buffer for partial tag detection
this._tagBuffer += char;

// Limit tag buffer size to max tag length (8 for </think>)
if (this._tagBuffer.length > 8) {
this._tagBuffer = this._tagBuffer.slice(-8);
}

// Check if we've completed a <think> tag
if (!this._inThinkBlock && this._tagBuffer.endsWith('<think>')) {
this._inThinkBlock = true;
// Clear the tag buffer (we consumed the tag characters)
this._tagBuffer = '';
continue;
}

// Check if we've completed a </think> tag
if (this._inThinkBlock && this._tagBuffer.endsWith('</think>')) {
this._inThinkBlock = false;
// Clear the tag buffer (we consumed the tag characters)
this._tagBuffer = '';
continue;
}

// If we're inside a think block, skip adding to display buffer
if (this._inThinkBlock) {
continue;
}

// Otherwise, add character to display buffer
this._displayBuffer += char;
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The state machine appends characters to _displayBuffer before it knows whether they are part of the <think> opening tag. For input like <think>..., this will leave a visible "<think" fragment in the rendered output (the <, t, h, i, n, k chars are appended before the endsWith('<think>') check fires). To avoid leaking partial tag text, buffer potential tag characters and only flush them to _displayBuffer once you’ve determined they aren’t part of a <think>/</think> tag (or retroactively remove the tag text from _displayBuffer when a tag is recognized).

Copilot uses AI. Check for mistakes.
}
}
this._showThinkContent = newValue;
});

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

appendAIResponse only reads showThinkContent once via chrome.storage.local.get(...) and never subscribes to chrome.storage.onChanged. As a result, toggling “Show think content” in the popup won’t affect already-mounted NoteCards (despite the code/comments implying it can reprocess on setting changes). If runtime toggling is intended, add a storage change listener (and remove it on unmount) to update _showThinkContent and re-render accordingly.

Suggested change
});
});
// Listen for runtime changes to showThinkContent so existing NoteCards update when the user toggles the setting
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'local' || !changes.showThinkContent) {
return;
}
const change = changes.showThinkContent;
// Maintain the same default behavior: treat undefined/true as "show", false as "hide"
const newValue = change.newValue !== false;
const aiResponseEl = this.shadow?.querySelector('.ai-response');
if (!aiResponseEl) {
this._showThinkContent = newValue;
return;
}
if (this._aiBuffer) {
if (!this._showThinkContent && newValue) {
// Was hiding, now showing - copy full buffer to display
this._displayBuffer = this._aiBuffer;
} else if (this._showThinkContent && !newValue) {
// Was showing, now hiding - filter buffer
this.reprocessBufferForThinkFilter();
}
}
this._showThinkContent = newValue;
// Immediately re-render using the updated buffers and setting
const bufferToRender = this._showThinkContent ? this._aiBuffer : this._displayBuffer;
if (bufferToRender) {
let html = marked.parse(bufferToRender) as string;
if (!this._showThinkContent) {
// Ensure any remaining think/cognition blocks are removed from the HTML
html = html.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '');
html = html.replace(/<cognition[^>]*>[\s\S]*?<\/cognition>/gi, '');
}
aiResponseEl.innerHTML = sanitizeHtml(html);
}
});

Copilot uses AI. Check for mistakes.
Comment on lines +436 to +471
this._displayBuffer = '';
this._inThinkBlock = false;
this._tagBuffer = '';

// Process the full AI buffer through the state machine
for (const char of this._aiBuffer) {
this._tagBuffer += char;

// Limit tag buffer size
if (this._tagBuffer.length > 8) {
this._tagBuffer = this._tagBuffer.slice(-8);
}

// Check if we've entered a think block
if (!this._inThinkBlock && this._tagBuffer.endsWith('<think>')) {
this._inThinkBlock = true;
this._tagBuffer = '';
continue;
}

// Check if we've exited a think block
if (this._inThinkBlock && this._tagBuffer.endsWith('</think>')) {
this._inThinkBlock = false;
this._tagBuffer = '';
continue;
}

// If we're inside a think block, skip adding to display buffer
if (this._inThinkBlock) {
continue;
}

// Otherwise, add character to display buffer
this._displayBuffer += char;
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reprocessBufferForThinkFilter reuses the same char-by-char tag detection logic as appendAIResponse, so it has the same issue of emitting partial <think text into _displayBuffer before the full <think> tag is recognized. Fixing the streaming state machine should be applied here as well (e.g., hold a pending tag buffer and only append to _displayBuffer once it’s confirmed to be non-tag content).

Suggested change
this._displayBuffer = '';
this._inThinkBlock = false;
this._tagBuffer = '';
// Process the full AI buffer through the state machine
for (const char of this._aiBuffer) {
this._tagBuffer += char;
// Limit tag buffer size
if (this._tagBuffer.length > 8) {
this._tagBuffer = this._tagBuffer.slice(-8);
}
// Check if we've entered a think block
if (!this._inThinkBlock && this._tagBuffer.endsWith('<think>')) {
this._inThinkBlock = true;
this._tagBuffer = '';
continue;
}
// Check if we've exited a think block
if (this._inThinkBlock && this._tagBuffer.endsWith('</think>')) {
this._inThinkBlock = false;
this._tagBuffer = '';
continue;
}
// If we're inside a think block, skip adding to display buffer
if (this._inThinkBlock) {
continue;
}
// Otherwise, add character to display buffer
this._displayBuffer += char;
}
// Reset streaming state
this._inThinkBlock = false;
this._tagBuffer = '';
// Start from the full AI buffer and remove think/cognition blocks at the text level
let filteredText = this._aiBuffer || '';
filteredText = filteredText.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '');
filteredText = filteredText.replace(/<cognition[^>]*>[\s\S]*?<\/cognition>/gi, '');
this._displayBuffer = filteredText;

Copilot uses AI. Check for mistakes.
Comment thread src/pages/content/services/NoteCard.ts Outdated
Comment on lines +297 to +357
@@ -262,9 +343,19 @@ export class NoteCard {
if (!this._renderScheduled) {
this._renderScheduled = true;
const scheduleRender = () => {
if (this._streaming && this._aiBuffer) {
const html = marked.parse(this._aiBuffer) as string;
aiResponse.innerHTML = sanitizeHtml(html);
if (this._streaming) {
// Use display buffer for rendering (filtered or full based on setting)
const bufferToRender = this._showThinkContent ? this._aiBuffer : this._displayBuffer;
if (bufferToRender) {
let html = marked.parse(bufferToRender) as string;
// Post-process: remove any remaining think tags from HTML output
// This handles cases where markdown parser doesn't fully consume the tags
if (!this._showThinkContent) {
html = html.replace(/<think[^>]*>[\s\S]*?<\/think>/gi, '');
html = html.replace(/<cognition[^>]*>[\s\S]*?<\/cognition>/gi, '');
}
aiResponse.innerHTML = sanitizeHtml(html);

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New behavior introduces a user-facing “think” filtering feature, but the existing NoteCard tests don’t cover scenarios like: (1) showThinkContent=false removes think blocks without leaving tag artifacts, and (2) showThinkContent=true preserves think content. Since NoteCard.test.ts already exists, adding focused tests around appendAIResponse/finalizeAIResponse with <think>...</think> input would help prevent regressions.

Copilot uses AI. Check for mistakes.
@luorome31 luorome31 changed the title Feat/think filter feature: think block can be shown or hidden by user and beautify some ui setting Mar 29, 2026
@luorome31
luorome31 requested a review from Copilot March 29, 2026 09:13
Replace the problematic pattern that caused TypeError: str.split is not
a function and test timeouts. Using vi.runAllTimers() properly flushes
all pending timers synchronously.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 14 changed files in this pull request and generated 7 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/pages/popup/Popup.tsx
Comment on lines 24 to 28
const [siteDisabled, setSiteDisabled] = useState(false);
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- used via functional setState update
const [disabledSites, setDisabledSites] = useState<string[]>([]);
const [showThinkContent, setShowThinkContent] = useState(true);

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

showThinkContent is initialized to true, so on fresh installs (when storage has no value yet) the popup defaults to showing think content. This conflicts with the described default behavior (hidden by default) and with the NoteCard comment that the default is to hide. Initialize state to false and treat undefined from storage as false to keep defaults consistent.

Copilot uses AI. Check for mistakes.
if (!this._initialized) {
this._initialized = true;
chrome.storage.local.get(['showThinkContent'], (result: { showThinkContent?: boolean }) => {
const newValue = result.showThinkContent !== false; // Default to true (show think)

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The storage fallback here defaults showThinkContent to true when the key is missing (!== false). That makes new installs show think blocks by default and contradicts the field comment (default: false = hide think) and the PR description. Change the default so undefined resolves to false (hide).

Suggested change
const newValue = result.showThinkContent !== false; // Default to true (show think)
const newValue = result.showThinkContent ?? false; // Default to false (hide think)

Copilot uses AI. Check for mistakes.
const aiResponseEl = this.shadow?.querySelector('.ai-response');
if (aiResponseEl) {
const html = marked.parse(this._displayBuffer) as string;
aiResponseEl.innerHTML = sanitizeHtml(html);

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When switching from hidden→shown in the storage callback, the re-render uses sanitizeHtml(html) without passing preserveThink/newValue. Since sanitizeHtml defaults to removing think blocks, this path will still hide think content during streaming even when the setting is enabled. Pass the intended preserveThink value (e.g., newValue) when sanitizing in this re-render.

Suggested change
aiResponseEl.innerHTML = sanitizeHtml(html);
aiResponseEl.innerHTML = sanitizeHtml(html, newValue);

Copilot uses AI. Check for mistakes.
Comment on lines +270 to +291
// Initialize showThinkContent setting on first chunk
if (!this._initialized) {
this._initialized = true;
chrome.storage.local.get(['showThinkContent'], (result: { showThinkContent?: boolean }) => {
const newValue = result.showThinkContent !== false; // Default to true (show think)
if (this._aiBuffer) {
if (!this._showThinkContent && newValue) {
// Was hiding, now showing - copy full buffer to display
this._displayBuffer = this._aiBuffer;
const aiResponseEl = this.shadow?.querySelector('.ai-response');
if (aiResponseEl) {
const html = marked.parse(this._displayBuffer) as string;
aiResponseEl.innerHTML = sanitizeHtml(html);
}
} else if (this._showThinkContent && !newValue) {
// Was showing, now hiding - filter buffer
this.reprocessBufferForThinkFilter();
}
}
this._showThinkContent = newValue;
});
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation only reads showThinkContent once (on first chunk) and never subscribes to chrome.storage.onChanged. That means toggling the setting won’t re-render already-mounted NoteCards, even though the PR description says switching the setting triggers an automatic re-render. Add a storage change listener (and remove it on unmount) to update _showThinkContent and reprocess/re-render existing buffers.

Copilot uses AI. Check for mistakes.
Comment on lines 247 to 255
updateAIResponse(markdown: string): void {
if (!this.shadow) return;
const aiResponse = this.shadow.querySelector('.ai-response');
if (aiResponse) {
// Parse markdown to HTML
this._aiBuffer = markdown;
const html = marked.parse(markdown) as string;
aiResponse.innerHTML = sanitizeHtml(html);
aiResponse.innerHTML = sanitizeHtml(html, this._showThinkContent);
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updateAIResponse() renders using _showThinkContent, but _showThinkContent is only loaded in appendAIResponse() (first chunk). If any code path calls updateAIResponse() without streaming first, it will always use the default (false) and hide think content regardless of the stored setting. Consider loading showThinkContent earlier (e.g., on mount()), or making updateAIResponse accept an explicit preserveThink/showThinkContent value.

Copilot uses AI. Check for mistakes.
Comment on lines +9 to +32
declare const global: { chrome?: unknown };

beforeAll(() => {
global.chrome = {
storage: {
local: {
get: vi.fn(
(_keys: string[], callback: (result: { showThinkContent?: boolean }) => void) => {
callback({ showThinkContent: mockStorage.showThinkContent });
}
),
},
},
};
});

describe('NoteCard', () => {
beforeEach(() => {
vi.useFakeTimers();
document.body.innerHTML = '<div id="test-target"></div>';
});

afterEach(() => {
vi.useRealTimers();

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test file overwrites global.chrome at module load time, which can leak into other test files and break the shared chrome mock set up in src/test/setup.ts. Instead, stub/spyon globalThis.chrome.storage.local.get in a beforeEach and restore it in afterEach, or merge with the existing mock rather than replacing the whole object.

Suggested change
declare const global: { chrome?: unknown };
beforeAll(() => {
global.chrome = {
storage: {
local: {
get: vi.fn(
(_keys: string[], callback: (result: { showThinkContent?: boolean }) => void) => {
callback({ showThinkContent: mockStorage.showThinkContent });
}
),
},
},
};
});
describe('NoteCard', () => {
beforeEach(() => {
vi.useFakeTimers();
document.body.innerHTML = '<div id="test-target"></div>';
});
afterEach(() => {
vi.useRealTimers();
let chromeGetSpy: ReturnType<typeof vi.spyOn> | undefined;
describe('NoteCard', () => {
beforeEach(() => {
vi.useFakeTimers();
document.body.innerHTML = '<div id="test-target"></div>';
const chromeStorageLocal = (globalThis as any)?.chrome?.storage?.local;
if (chromeStorageLocal) {
chromeGetSpy = vi
.spyOn(chromeStorageLocal, 'get')
.mockImplementation(
(_keys: string[], callback: (result: { showThinkContent?: boolean }) => void) => {
callback({ showThinkContent: mockStorage.showThinkContent });
}
);
}
});
afterEach(() => {
vi.useRealTimers();
chromeGetSpy?.mockRestore();
chromeGetSpy = undefined;

Copilot uses AI. Check for mistakes.
Comment thread manifest.json
Comment on lines 11 to 14
"default_icon": {
"32": "icon-32.png"
}
},

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR removes the chrome_url_overrides.newtab entry, which changes extension behavior (no longer overrides the new tab page) but isn’t mentioned in the PR description. Either include this in the PR summary/description or split it into a separate PR to keep scope clear.

Copilot uses AI. Check for mistakes.
@luorome31
luorome31 marked this pull request as ready for review March 29, 2026 09:21
- Add chrome.storage.onChanged listener in mount() for runtime setting changes
- Remove listener on unmount() to prevent memory leaks
- Fix default value comment: _showThinkContent defaults to true
- Improve test file: use spyOn instead of overwriting global.chrome
- Add proper typing for chrome.storage mock in tests
@luorome31
luorome31 merged commit de83042 into main Mar 29, 2026
4 checks passed
@luorome31
luorome31 deleted the feat/think-filter branch March 29, 2026 09:41
@luorome31
luorome31 restored the feat/think-filter branch March 29, 2026 09:41
@luorome31
luorome31 deleted the feat/think-filter branch March 29, 2026 09:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants