TidGi-Desktop/docs/internal/ServiceIPC.md
lin onetwo 9a6f3480f5
Feat/watch fs (#649)
* Add watch-filesystem-adaptor plugin and worker IPC

Introduces the watch-filesystem-adaptor TiddlyWiki plugin, enabling tag-based routing of tiddlers to sub-wikis by querying workspace info via worker thread IPC. Adds workerServiceCaller utility for worker-to-main service calls, updates workerAdapter and bindServiceAndProxy to support explicit service registration for workers, and documents the new IPC architecture. Updates wikiWorker and startNodeJSWiki to preload workspace ID and load the new plugin. Also updates the plugin build script to compile and copy the new plugin.

* test: wiki operation steps

* Add per-wiki labeled logging and console hijack

Introduces labeled loggers for each wiki, writing logs to separate files. Adds a logFor method to NativeService for logging with labels, updates interfaces, and hijacks worker thread console methods to redirect logs to main process for wiki-specific logging. Refactors workspaceID usage to workspace object for improved context.

* Update log handling for wiki worker and tests

Enhanced logging tests to check all log files, including wiki logs. Adjusted logger to write wiki worker logs to the main log directory. Updated e2e app script comment for correct usage.

* Enable worker thread access to main process services

Introduces a proxy system allowing worker threads to call main process services with full type safety and observable support. Adds worker-side service proxy creation, auto-attaches proxies to global.service, and updates service registration to use IPC descriptors. Documentation is added for usage and architecture.

* Update ErrorDuringStart.md

* chore: upgrade ipc cat and allow clean vite cache

* Refactor wiki worker initialization and service readiness

Moved wiki worker implementation from wikiWorker.ts to wikiWorker/index.ts and deleted the old file. Added servicesReady.ts to manage worker service readiness and callbacks, and integrated notifyServicesReady into the worker lifecycle. Updated console hijack logic to wait for service readiness before hijacking. Improved worker management in Wiki service to support detaching workers and notifying readiness.

* Refactor wiki logging to use centralized logger

Removed per-wiki loggers and console hijacking in favor of a single labeled logger. All wiki logs, including errors, are now written to a unified log file. Updated worker and service code to route logs through the main logger and removed obsolete log file naming and management logic.

* fix: ipc cat log error

* Refactor wiki test paths and improve file save logic

Updated test step to use wikiTestRootPath for directory replacements and added wikiTestRootPath to paths.ts for clarity. Improved error handling and directory logic in watch-filesystem-adaptor.ts, including saving tiddlers directly to sub-wiki folders, more informative logging, and ensuring cleanup after file writes is properly awaited.

* rename

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* feat: basic watch-fs

* feat: check file not exist

* refactor: use exponential-backoff

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* Initial commit when init a new git.

* fix: cleanup

* Refactor test setup and cleanup to separate file

Moved Before and After hooks from application.ts to a new cleanup.ts file for better organization and separation of concerns. Also removed unused imports and related code from application.ts. Minor type simplification in agent.ts for row parsing.

* test: modify and rename

* feat: enableFileSystemWatch

* refactor: unused utils.ts

* Update watch-filesystem-adaptor.ts

* refactor: use node-sentinel-file-watcher

* refactor: extract to two classes

* The logFor method lacks JSDoc describing the level parameter's

* Update startNodeJSWiki.ts

* fix: napi build

* Update electron-rebuild command in workflows

Changed the electron-rebuild command in release and test GitHub Actions workflows to use a comma-separated list for native modules instead of multiple -w flags. This simplifies the rebuild step for better-sqlite3 and nsfw modules.

* lint

* not build nsfw, try use prebuild

* Update package.json

* Update workerAdapter.ts

* remove subWikiPlugin.ts as we use new filesystem adaptor that supports tag based sub wiki

* fix: build

* fix: wrong type

* lint

* remove `act(...)` warnings

* uninstall chokidar

* refactor and test

* lint

* remove unused logic, as we already use ipc syncadaptor, not afriad of wiki status change

* Update translation.json

* test: increast timeout in CI

* Update application.ts

* fix: AI's wrong cleanup logic hidden by as unknown as

* fix: AI's wrong  as unknown as

* Update agent.feature

* Update wikiSearchPlugin.ts

* fix: A dynamic import callback was not specified.
2025-10-28 13:25:46 +08:00

3.9 KiB

Service IPC

Register a new service

See this 6aedff4b commit for example, you need to modify these files:

Register service for worker threads

If you need to expose a service to worker threads (e.g., for TiddlyWiki plugins running in wiki worker), register it in the registerServicesForWorkers() function in src/services/libs/bindServiceAndProxy.ts.

Example:

function registerServicesForWorkers(workspaceService: IWorkspaceService): void {
  registerServiceForWorker('workspace', {
    get: workspaceService.get.bind(workspaceService) as (...arguments_: unknown[]) => unknown,
    getWorkspacesAsList: workspaceService.getWorkspacesAsList.bind(workspaceService) as (...arguments_: unknown[]) => unknown,
  });
}

Worker threads can then call these services using:

import { callMainProcessService } from '@services/wiki/wikiWorker/workerServiceCaller';

const workspace = await callMainProcessService<IWorkspace>('workspace', 'get', [workspaceId]);
const allWorkspaces = await callMainProcessService<IWorkspace[]>('workspace', 'getWorkspacesAsList', []);

See src/services/wiki/wikiWorker/workerServiceCaller.ts for the worker-side implementation.

Sync service

Some services are sync, like getSubWorkspacesAsListSync getActiveWorkspaceSync from src/services/workspaces/index.ts, they can't be called from renderer, only can be used in the main process.

Because after pass through IPC, everything will be async, so its function typescript signature will be wrong.

Use async service on frontend

Given

export const WorkspaceServiceIPCDescriptor = {
  channel: WorkspaceChannel.name,
  properties: {
    workspaces$: ProxyPropertyType.Value$,
    getWorkspacesAsList: ProxyPropertyType.Function,
    get: ProxyPropertyType.Function,
    get$: ProxyPropertyType.Function$,
  },
};

Registered service's async method could be used like await window.service.workspace.getWorkspacesAsList(), and observable could be used as window.observables.workspace.workspaces$.pipe() (where pipe is a method on Observable on rxjs), and

import useObservable from 'beautiful-react-hooks/useObservable';

const workspace$ = useMemo(() => window.observables.workspace.get$(id), [id]);
useObservable(workspace$, workspaceSetter);

or in store use rxjs like window.observables.workspace.get$(id).observe().

IPC Communication Architecture

TidGi uses multiple IPC mechanisms for different scenarios:

1. Main Process ↔ Renderer Process (electron-ipc-cat)

Used for UI-related service calls (e.g., preferences, workspaces, windows).

  • Registration: src/services/libs/bindServiceAndProxy.ts - registerProxy()
  • Renderer access: window.service.* or window.observables.*
  • Implementation: electron-ipc-cat library

2. Main Process ↔ Worker Threads (worker_threads)

Used for TiddlyWiki plugins running in wiki workers to access TidGi services.

  • Registration: src/services/libs/bindServiceAndProxy.ts - registerServicesForWorkers()
  • Worker access: callMainProcessService(serviceName, methodName, args)
  • Implementation: Custom worker_threads IPC in src/services/libs/workerAdapter.ts
  • Use case: Watch Filesystem Adaptor plugin querying workspace information

Key differences:

  • Worker IPC is method-based (not proxy-based)
  • Worker IPC is async only (no observables)
  • Worker IPC requires explicit registration of each method