Skip to content

feat(extension): implement development-only logger with debug toggle #942

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 8, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { getElementType } from '../utils';
import { genContentSelectorID } from '@refly/utils/id';
import { getMarkdown } from '@refly/utils/html2md';
import { BLOCK_SELECTED_MARK_ID, INLINE_SELECTED_MARK_ID } from '../utils/index';
import { logger } from '../../../utils/logger';

// utils
import { getSelectionNodesMarkdown } from '@refly/utils/html2md';
Expand Down Expand Up @@ -126,7 +127,7 @@ export const useContentSelector = (
containerElem?.removeChild(menuContainer);
document.head.removeChild(styleContainer);
} catch (err) {
console.log('remove err', err);
logger.log('remove err', err);
}
}, 300);
};
Expand Down Expand Up @@ -392,7 +393,7 @@ export const useContentSelector = (
} as Mark,
},
};
console.log('contentSelectorClickHandler', safeStringifyJSON(msg));
logger.debug('contentSelectorClickHandler', safeStringifyJSON(msg));
sendMessage(msg);
};

Expand Down Expand Up @@ -437,13 +438,13 @@ export const useContentSelector = (
const onMouseMove = (ev: MouseEvent) => {
ev.stopImmediatePropagation();

console.log('isMouseOutsideContainer', isMouseOutsideContainer(ev), selector);
logger.debug('isMouseOutsideContainer', isMouseOutsideContainer(ev), selector);

if (isMouseOutsideContainer(ev)) {
return;
}

console.log('contentActionHandler', ev, statusRef, markRef, showContentSelectorRef);
logger.debug('contentActionHandler', ev, statusRef, markRef, showContentSelectorRef);
if (
statusRef.current &&
markRef.current &&
Expand Down Expand Up @@ -523,7 +524,7 @@ export const useContentSelector = (
const selection = window.getSelection();
const text = selection?.toString();

console.log('onMouseDownUpEvent');
logger.debug('onMouseDownUpEvent');

if (statusRef.current && markRef.current && showContentSelectorRef.current) {
if (text && text?.trim()?.length > 0) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { sendHeartBeatMessage } from './utils';
import { Tabs } from 'wxt/browser';
import { logger } from '../../../utils/logger';

export const onActivated = (activeInfo: Tabs.OnActivatedActiveInfoType) => {
// 在此处处理标签切换
console.log(`Tab with ID ${activeInfo.tabId} was activated in window ${activeInfo.windowId}`);
logger.debug(`Tab with ID ${activeInfo.tabId} was activated in window ${activeInfo.windowId}`);

sendHeartBeatMessage(activeInfo);
};
3 changes: 2 additions & 1 deletion apps/extension/src/entrypoints/background/events/detached.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Tabs } from 'wxt/browser';
import { logger } from '../../../utils/logger';

export const onDetached = (tabId: number, detachInfo: Tabs.OnDetachedDetachInfoType) => {
// 在此处处理标签切换
console.log(`Tab with ID ${tabId} was detached in window ${detachInfo.oldWindowId}`);
logger.debug(`Tab with ID ${tabId} was detached in window ${detachInfo.oldWindowId}`);
};
13 changes: 7 additions & 6 deletions apps/extension/src/entrypoints/background/events/ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ import { TASK_STATUS, SkillEvent } from '@refly/common-types';
import { getCookie } from '@/utils/cookie';
import { ssePost } from '@refly-packages/ai-workspace-common/utils/sse-post';
import { getAbortController, getLastUniqueId, setAbortController, setLastUniqueId } from '../index';
import { logger } from '../../../utils/logger';

export const handleStreamingChat = async (
req: { body: any; uniqueId: string },
res: { send: (response?: any) => void },
) => {
const { type, payload } = req?.body || {};
const { uniqueId } = req;
console.log('receive request', req.body);
logger.debug('receive request', req.body);
setLastUniqueId(uniqueId);

try {
Expand Down Expand Up @@ -76,7 +77,7 @@ export const handleStreamingChat = async (
},
});

console.log('after abortController', abortController);
logger.debug('after abortController', abortController);
} else if (type === TASK_STATUS.SHUTDOWN) {
const abortController = getAbortController(uniqueId);

Expand All @@ -85,21 +86,21 @@ export const handleStreamingChat = async (
}
}
} catch (err) {
console.log('err', err);
logger.error('streaming chat error', err);
try {
const abortController = getAbortController(uniqueId);
if (!abortController?.signal?.aborted) {
abortController?.abort?.();
}
} catch (err) {
console.log('err', err);
logger.error('abort controller cleanup error', err);
}
}
};

export const onPort = async (port: Runtime.Port) => {
port.onMessage.addListener(async (message: any, comingPort: Runtime.Port) => {
console.log('onPort', message, comingPort);
logger.debug('onPort', message, comingPort);
if (comingPort.name === 'streaming-chat') {
return handleStreamingChat(message, {
send: async (msg: any) => {
Expand All @@ -115,7 +116,7 @@ export const onPort = async (port: Runtime.Port) => {
try {
abortController?.abort?.();
} catch (err) {
console.log('err', err);
logger.error('port disconnect cleanup error', err);
}
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { defineContentScript } from 'wxt/sandbox';
import { createShadowRootUi } from 'wxt/client';
import { App } from './App';
import { setRuntime } from '@refly/utils/env';
import { logger } from '@/utils/logger';

export default defineContentScript({
matches: ['<all_urls>'],
Expand All @@ -16,7 +17,7 @@ export default defineContentScript({

async main(ctx) {
setRuntime('extension-csui');
console.log('ctx', ctx);
logger.debug('contentSelector ctx', ctx);

const injectSelectorCSS = () => {
const style = document.createElement('style');
Expand Down
22 changes: 18 additions & 4 deletions apps/extension/src/entrypoints/floatingSphere-csui.content/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { useSaveSelectedContent } from '@/hooks/use-save-selected-content';
import { BackgroundMessage, SyncMarkEvent, type MessageName } from '@refly/common-types';
import { useGetUserSettings } from '@/hooks/use-get-user-settings';
import { useUserStore } from '@refly-packages/ai-workspace-common/stores/user';
import { logger } from '@/utils/logger';

const getPopupContainer = () => {
const elem = document
Expand Down Expand Up @@ -54,7 +55,7 @@ export const App = () => {
getLoginStatus();
}, []);

console.log('i18n', i18n?.languages);
logger.debug('i18n', i18n?.languages);

// 加载快捷键
const [_shortcut] = useState<string>(reflyEnv.getOsType() === 'OSX' ? '⌘ J' : 'Ctrl J');
Expand Down Expand Up @@ -229,7 +230,7 @@ export const App = () => {
icon={<IconSave />}
size="small"
onClick={() => {
console.log('saveResource', saveResource);
logger.debug('saveResource', saveResource);
handleSaveResourceAndNotify(saveResource);
}}
className="refly-floating-sphere-dropdown-item assist-action-item"
Expand Down Expand Up @@ -274,7 +275,7 @@ export const App = () => {
};

const handleMouseUp = () => {
console.log('handleMouseUp');
logger.debug('handleMouseUp');
setIsDragging(false);
isDraggingRef.current = false;
};
Expand All @@ -294,6 +295,18 @@ export const App = () => {

const [isVisible, setIsVisible] = useState(true);

const handleDebugClick = useCallback(() => {
const showMessage = (content: string, type: 'info' | 'success' = 'info') => {
if (type === 'success') {
Message.success({ content, duration: 4000 });
} else {
Message.info({ content, duration: 2000 });
}
};

logger.handleDebugClick(showMessage);
}, []);

const handleClose = (e: React.MouseEvent) => {
Message.info({
content: t('extension.floatingSphere.toggleCopilotClose'),
Expand Down Expand Up @@ -357,7 +370,8 @@ export const App = () => {
<img
src={Logo}
alt={t('extension.floatingSphere.toggleCopilot')}
style={{ width: 25, height: 25 }}
style={{ width: 25, height: 25, cursor: 'pointer' }}
onClick={handleDebugClick}
/>
<span className="refly-floating-sphere-entry-shortcut">Refly</span>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { setRuntime } from '@refly/utils/env';
import { ConfigProvider } from 'antd';
import { MemoryRouter, Route } from '@refly-packages/ai-workspace-common/utils/router';
import { AppRouter } from '@/routes';
import { logger } from '@/utils/logger';

export default defineContentScript({
matches: ['<all_urls>'],
Expand All @@ -22,7 +23,7 @@ export default defineContentScript({
async main(ctx) {
setRuntime('extension-csui');

console.log('ctx', ctx);
logger.debug('floatingSphere ctx', ctx);
let _removeInjectCSS: () => void;
// 3. Define your UI`
const ui = await createShadowRootUi(ctx, {
Expand Down
3 changes: 2 additions & 1 deletion apps/extension/src/entrypoints/utils-csui.content/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import ReactDOM from 'react-dom/client';
import { setRuntime } from '@refly/utils/env';
import { createShadowRootUi } from 'wxt/client';
import App from './App';
import { logger } from '@/utils/logger';

export default defineContentScript({
matches: ['<all_urls>'],
Expand All @@ -19,7 +20,7 @@ export default defineContentScript({
async main(ctx) {
setRuntime('extension-csui');

console.log('ctx', ctx);
logger.debug('utils-csui ctx', ctx);
// 3. Define your UI`
const ui = await createShadowRootUi(ctx, {
name: 'refly-utils-app',
Expand Down
5 changes: 3 additions & 2 deletions apps/extension/src/hooks/use-get-user-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { getRuntime } from '@refly/utils/env';
import { UserSettings } from '@refly/openapi-schema';
import { browser } from 'wxt/browser';
import debounce from 'lodash.debounce';
import { logger } from '@/utils/logger';

export const useGetUserSettings = () => {
const userStore = useUserStore((state) => ({
Expand All @@ -40,7 +41,7 @@ export const useGetUserSettings = () => {
userStore.setIsCheckingLoginStatus(true);
const res = await getClient().getSettings();

console.log('loginStatus', res);
logger.debug('loginStatus', res);

if (!res?.error || !res) {
userStore.resetState();
Expand Down Expand Up @@ -92,7 +93,7 @@ export const useGetUserSettings = () => {
}
}
} catch (err) {
console.log('getLoginStatus err', err);
logger.debug('getLoginStatus err', err);
userStore.setIsCheckingLoginStatus(false);
userStore.resetState();

Expand Down
3 changes: 2 additions & 1 deletion apps/extension/src/hooks/use-storage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { storage } from '@refly-packages/ai-workspace-common/utils/storage';
import { safeParseJSON } from '@refly-packages/ai-workspace-common/utils/parse';
import { logger } from '@/utils/logger';

export type StorageLocation = 'local' | 'sync' | 'session' | 'managed';

Expand Down Expand Up @@ -29,7 +30,7 @@ export const useStorage = <T>(

useEffect(() => {
storageItem.watch((newValue) => {
console.log('new Syn storage value', newValue);
logger.debug('new Syn storage value', newValue);
setStorageValue(newValue as T);
});
}, []);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import pTimeout from 'p-timeout';
import { checkPageUnsupported } from '@refly-packages/ai-workspace-common/utils/extension/check';
import { checkBrowserArc } from '@/utils/browser';
import { useCopilotTypeStore } from '@/modules/toggle-copilot/stores/use-copilot-type';
import { logger } from '@/utils/logger';

export const useToggleCopilot = () => {
const { copilotType } = useCopilotTypeStore((state) => ({
Expand All @@ -22,9 +23,9 @@ export const useToggleCopilot = () => {

await handleCheckArcBrowser();

console.log('isArcBrowserRef.current', isArcBrowserRef.current, isCopilotOpen);
logger.debug('isArcBrowserRef.current', isArcBrowserRef.current, isCopilotOpen);
if (isArcBrowserRef.current) {
console.log('sendMessage', 'toggleCopilotSidePanel');
logger.debug('sendMessage', 'toggleCopilotCSUI');
sendMessage({
type: 'others',
name: 'toggleCopilotCSUI',
Expand All @@ -35,7 +36,7 @@ export const useToggleCopilot = () => {
source: getRuntime(),
});
} else {
console.log('sendMessage', 'toggleCopilotSidePanel');
logger.debug('sendMessage', 'toggleCopilotSidePanel');
sendMessage({
type: 'toggleCopilot',
name: 'toggleCopilotSidePanel',
Expand Down Expand Up @@ -93,7 +94,7 @@ export const useToggleCopilot = () => {
});

useEffect(() => {
console.log('useToggleCopilot copilotType', copilotType);
logger.debug('useToggleCopilot copilotType', copilotType);
//

// Initial check if the page is already visible
Expand Down
Loading