webview-trpc-messaging

작성자: microsoft

VS Code 확장 호스트와 React 웹뷰 간의 tRPC 기반 통신을 구현합니다. 새 웹뷰 프로시저(쿼리, 뮤테이션 등)를 생성할 때 사용하세요.

npx skills add https://github.com/microsoft/vscode-documentdb --skill webview-trpc-messaging

Webview tRPC Messaging

Type-safe RPC communication between the VS Code extension host (server) and React webviews (client) using tRPC.

Architecture Overview

React Webview (client)                    Extension Host (server)
─────────────────────                     ──────────────────────
useTrpcClient() hook                      WebviewController
  └─ createTRPCClient                       └─ setupTrpc()
       └─ vscodeLink ──── postMessage ────►     ├─ callerFactory(appRouter)
            (send/onReceive)              ◄─────┤   └─ procedure(input)
                                                └─ abort/subscription.stop

Key files (read as needed for implementation details):

FilePurpose
@microsoft/vscode-ext-webview (shared)tRPC init via initWebviewTrpc, publicProcedure, router, BaseRouterContext
@microsoft/vscode-ext-webview/host (telemetry)telemetryMiddlewareBody, ProcedureLogger, TelemetryRunner (consumer builds publicProcedureWithTelemetry)
src/webviews/_integration/trpc.tsConsumer tRPC instance: publicProcedureWithTelemetry, the DocumentDB TelemetryRunner, and the RpcEnrichment shape it contributes to ctx.actionContext
src/webviews/_integration/appRouter.tsRoot router + publicProcedureWithTelemetry wiring + DocumentDB BaseRouterContext
src/webviews/_integration/configuration.tsConsumer-owned knobs (telemetry namespace, bundle layout, dev-server host)
@microsoft/vscode-ext-webview/host (WebviewController)WebviewController + openWebview factory: WebviewPanel lifecycle, tRPC dispatcher (queries, mutations, subscriptions, abort)
src/webviews/_integration/openAppWebview.tsDocumentDB factory preset that pre-fills router + bundle layout (openAppWebview)
src/webviews/_integration/useTrpcClient.tsReact hook providing the tRPC client (pre-typed against AppRouter)
@microsoft/vscode-ext-webview/webview (vscodeLink)Custom tRPC link bridging postMessage transport

Creating a New Router

Each webview maintains its own router. Follow this pattern:

1. Define the router context

Extend BaseRouterContext with view-specific fields:

// src/webviews/documentdb/myView/myViewRouter.ts
import { type BaseRouterContext } from '../../_integration/appRouter';

export type RouterContext = BaseRouterContext & {
  clusterId: string;
  viewId: string;
  databaseName: string;
  // add view-specific fields
};

2. Define procedures

import { z } from 'zod';
import {
  publicProcedure,
  publicProcedureWithTelemetry,
  router,
  type WithTelemetry,
} from '../../_integration/appRouter';
import { type RouterContext } from './myViewRouter';

export const myViewRouter = router({
  // Query with telemetry (preferred for operations that touch external services)
  getData: publicProcedureWithTelemetry.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {
    const myCtx = ctx as WithTelemetry<RouterContext>;
    // Instrumented procedure: myCtx.actionContext (the full IActionContext) is present.
    myCtx.actionContext.telemetry.properties.itemId = input.id;
    // myCtx.signal is the AbortSignal for cancellation
    return { data: 'result' };
  }),

  // Mutation without telemetry (rare, use for fire-and-forget)
  doAction: publicProcedure.input(z.string()).mutation(({ input }) => {
    // lightweight operation
  }),
});

3. Register in appRouter

// src/webviews/_integration/appRouter.ts
import { myViewRouter } from '../../documentdb/myView/myViewRouter';

export const appRouter = router({
  common: commonRouter,
  mongoClusters: {
    documentView: documentViewRouter,
    collectionView: collectionViewRouter,
    myView: myViewRouter, // <-- add here
  },
});

4. Create the controller

Construction-only panels are opened with a factory function that builds the config + router context and calls the openAppWebview preset (which pre-fills the app router, caller factory, and bundle layout):

// src/webviews/documentdb/myView/myViewController.ts
import * as vscode from 'vscode';
import { API } from '../../../DocumentDBExperiences';
import { type AppWebviewController, openAppWebview } from '../../_integration/openAppWebview';
import { type RouterContext } from './myViewRouter';

export function openMyViewPanel(initialData: MyViewConfig): AppWebviewController<MyViewConfig> {
  const title = `${initialData.databaseName}`;

  const trpcContext: RouterContext = {
    dbExperience: API.DocumentDB,
    webviewName: 'myView',
    clusterId: initialData.clusterId,
    viewId: initialData.viewId,
    databaseName: initialData.databaseName,
  };

  return openAppWebview({
    title,
    webviewName: 'myView',
    config: initialData,
    context: trpcContext,
  });
}

The returned AppWebviewController handle exposes panel, onDisposed, revealToForeground, isDisposed, and dispose. Genuinely stateful panels may still extend WebviewController from @microsoft/vscode-ext-webview/host directly instead of using the factory.

Important: The webviewName field passed to openAppWebview is the registry key (viewType, must match a key in WebviewRegistry, e.g. collectionView). The webviewName in the tRPC context is a telemetry label used in telemetry event names. These may be the same string but serve different purposes -- do not confuse them.

5. Register in WebviewRegistry

Add your React component to the registry. The key must match the webviewName passed to openAppWebview (viewType). The WebviewName type (exported from the same file) ensures compile-time validation of webview names.

// src/webviews/_integration/WebviewRegistry.ts
import { MyView } from '../../documentdb/myView/MyView';

export const WebviewRegistry = {
  collectionView: CollectionView,
  documentView: DocumentView,
  myViewName: MyView, // <-- add your entry
} as const;

export type WebviewName = keyof typeof WebviewRegistry;

Telemetry: publicProcedure vs publicProcedureWithTelemetry

BaseWhen to usectx.actionContext
publicProcedureFire-and-forget, no external calls, telemetry reported separatelyabsent (do not read it)
publicProcedureWithTelemetryDefault choice. Any procedure touching DB, network, or user-visible workGuaranteed, injected by the DocumentDB TelemetryRunner

publicProcedureWithTelemetry is publicProcedure.use(telemetryMiddlewareBody(documentDbTelemetryRunner, ...)) (built in trpc.ts). The framework's telemetryMiddlewareBody delegates to the DocumentDB TelemetryRunner, which wraps the call in callWithTelemetryAndErrorHandling, contributes the full IActionContext to ctx.actionContext, auto-generates a telemetry event named documentDB.rpc.{type}.{path}, and records errors, duration, and abort status.

actionContext is not a field on the base RouterContext — it is an additive enrichment. Narrow to WithTelemetry<RouterContext> (= RouterContext & { actionContext }) in an instrumented procedure to read it; a plain publicProcedure procedure narrows to bare RouterContext, so reading actionContext there is a compile error instead of a runtime undefined.

Access telemetry safely:

const myCtx = ctx as WithTelemetry<RouterContext>;
myCtx.actionContext.telemetry.properties.myCustomProp = 'value';
myCtx.actionContext.telemetry.measurements.itemCount = items.length;

AbortSignal Support

Every tRPC operation (query, mutation, subscription) receives its own AbortController. Cancellation flows:

Client (React)                              Server (Extension Host)
──────────────                              ──────────────────────
// Queries/Mutations:
ac = new AbortController()
trpcClient.myProc.query(input,
  { signal: ac.signal })
ac.abort()  →  sends 'abort' msg  →  abortController.abort()
                                        → ctx.signal.aborted = true

// Subscriptions:
sub = trpcClient.mySub.subscribe(...)
sub.unsubscribe()  →  'subscription.stop'  →  abortController.abort()

Using abort in procedures

// Pass signal to APIs that accept it (MongoDB driver, fetch, etc.)
getData: publicProcedureWithTelemetry
    .input(z.object({ filter: z.record(z.unknown()) }))
    .query(async ({ input, ctx }) => {
        const myCtx = ctx as RouterContext;

        // Option 1: Pass to driver (preferred)
        const cursor = collection.find(input.filter, { signal: myCtx.signal });

        // Option 2: Manual check in loops
        for (const item of items) {
            if (myCtx.signal?.aborted) return;
            await processItem(item);
        }
    }),

Client-side abort

const trpcClient = useTrpcClient();
const abortControllerRef = useRef<AbortController>();

const runQuery = async () => {
  abortControllerRef.current?.abort(); // cancel previous
  const ac = new AbortController();
  abortControllerRef.current = ac;

  const result = await trpcClient.mongoClusters.collectionView.myQuery.query(input, { signal: ac.signal });
};

When publicProcedureWithTelemetry detects an aborted signal, the DocumentDB TelemetryRunner sets telemetry.properties.aborted = 'true' and result = 'Canceled' automatically.

Subscriptions

Subscriptions stream multiple values from server to client using async generators:

// Server (router)
streamData: publicProcedureWithTelemetry
    .input(z.object({ batchSize: z.number() }))
    .subscription(async function* ({ input, ctx }) {
        const myCtx = ctx as RouterContext;

        for (let i = 0; i < total; i += input.batchSize) {
            if (myCtx.signal?.aborted) return; // check before each yield
            const batch = await fetchBatch(i, input.batchSize);
            yield batch;
        }
    }),

// Client (React)
const sub = trpcClient.mongoClusters.myView.streamData.subscribe(
    { batchSize: 100 },
    {
        onData(batch) { /* handle each batch */ },
        onComplete() { /* all done */ },
        onError(err) { /* handle error */ },
    },
);

// To stop:
sub.unsubscribe();

Client-Side Hook Usage

import { useTrpcClient } from '../_integration/useTrpcClient';
import { useConfiguration } from '@microsoft/vscode-ext-webview/react';

export const MyComponent = () => {
  const trpcClient = useTrpcClient();
  const config = useConfiguration<MyViewConfig>();

  useEffect(() => {
    trpcClient.mongoClusters.myView.getData.query({ id: config.documentId }).then(setData);
  }, []);
};

useConfiguration<T>() retrieves the initial config passed to WebviewController constructor (serialized via encodeURIComponent(JSON.stringify(...))).

Common Pitfalls

  • Never use any in procedure context casts — narrow with ctx as WithTelemetry<RouterContext> when the procedure reads telemetry (ctx.actionContext.telemetry), or ctx as RouterContext otherwise
  • Always prefer publicProcedureWithTelemetry unless you have a specific reason not to
  • Always check myCtx.signal?.aborted in long-running loops — not checking causes wasted work after client cancels
  • Do not mutate the shared context object — WebviewController clones it per-operation already, but router code should treat ctx as read-only
  • Input validation uses zod — always define .input(z.object({...})) for type safety
  • The commonRouter handles cross-cutting concerns (error reporting, telemetry events, surveys, URL opening) — do not duplicate these in view-specific routers

microsoft의 다른 스킬

oss-growth
microsoft
OSS 성장 해커 페르소나
agent-framework-azure-ai-py
microsoft
Microsoft Agent Framework Python SDK(agent-framework-azure-ai)를 사용하여 Azure AI Foundry 에이전트를 구축합니다. AzureAIAgentsProvider로 지속적 에이전트를 만들 때, 호스팅 도구(코드 인터프리터, 파일 검색, 웹 검색)를 사용할 때, MCP 서버를 통합할 때, 대화 스레드를 관리할 때, 또는 스트리밍 응답을 구현할 때 사용합니다. 함수 도구, 구조화된 출력, 다중 도구 에이전트를 다룹니다.
development
airunway-aks-setup
microsoft
AKS에서 AI Runway 설정 — 빈 클러스터에서 실행 중인 모델까지. 클러스터 검증, 컨트롤러 설치, GPU 평가, 공급자 설정, 첫 배포를 다룹니다. 시기: "AI Runway 설정", "AKS 클러스터 온보딩", "AI Runway 설치", "airunway 설정", "AKS에 모델 배포", "AKS에서 GPU 추론", "AKS에서 KAITO 설정", "AKS에서 LLM 실행", "AKS에서 vLLM", "AKS에서 모델 서빙 설정", "AI Runway 컨트롤러".
devops
appinsights-instrumentation
microsoft
Azure Application Insights로 웹앱을 계측하기 위한 지침입니다. 원격 분석 패턴, SDK 설정, 구성 참조를 제공합니다. WHEN: 앱 계측 방법, App Insights SDK, 원격 분석 패턴, App Insights란 무엇인가, Application Insights 지침, 계측 예시, APM 모범 사례.
devops
applicationinsights-web-ts
microsoft
브라우저/웹 앱을 Application Insights JavaScript SDK(@microsoft/applicationinsights-web)로 계측합니다. Real User Monitoring(RUM) — 페이지 뷰, 클릭, AJAX/fetch 종속성, 예외, 사용자 지정 이벤트, 백엔드 OpenTelemetry 트레이스와 상관관계가 있는 브라우저 측 GenAI 에이전트 트레이스에 사용합니다. SDK Loader Script 및 npm 설정, 프레임워크 확장(React, React Native, Angular), Click Analytics, 텔레메트리 이니셜라이저, 브라우저에서 생성된 에이전트/도구/모델 스팬에 대한 OTel GenAI 의미론적 규칙을 다룹니다.
devops
azure-ai-anomalydetector-java
microsoft
Azure AI Anomaly Detector SDK for Java로 이상 탐지 애플리케이션을 구축하세요. 단변량/다변량 이상 탐지, 시계열 분석 또는 AI 기반 모니터링을 구현할 때 사용하세요.
development
azure-ai-language-conversations-py
microsoft
azure-ai-language-conversations Python SDK를 사용하여 대화형 언어 이해(CLU)를 구현합니다. ConversationAnalysisClient로 대화 의도와 엔터티를 분석하거나, NLP 기능을 구축하거나, 애플리케이션에 언어 이해를 통합할 때 사용합니다.
development
azure-ai-ml-py
microsoft
Azure Machine Learning SDK v2 for Python. ML 작업 영역, 작업, 모델, 데이터 세트, 컴퓨팅 및 파이프라인에 사용합니다. 트리거: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets".
development