﻿# nf-softphone {#softphone}

Integrates the shared 94AI online web softphone microfrontend through qiankun or wujie. Features include outgoing and incoming calls, transfer to an agent, answering, ignoring, hanging up, breaks, network diagnostics, muting, real-time volume tracking, agent sign-in/sign-out, chat text retrieval, and agent monitoring log reporting. Action dispatch and callback notifications integrate the common softphone capabilities currently available. `NfSoftphone` is an SFC for MVVM applications. Use the default `nfSoftphone` instance for a single phone, or construct multiple instances with `new nfSoftphoneManager()`. The `name` property isolates the microfrontend applications.

## Exports {#exports}

```ts
import NfSoftphone, { nfSoftphone, nfSoftphoneManager, createSoftphoneSign, createSoftphoneAccessToken, createSoftphoneToken, installSoftphoneCryptoJS, SOFTPHONE_CRYPTO_JS_CDN_URL, waitForSoftphoneRender } from '@94ai-plus/nf-softphone'
import type {
  SoftphoneAccessToken,
  SoftphoneAccessTokenResult,
  SoftphoneAccessTokenOptions,
  SoftphoneTokenOptions,
  SoftphoneEnv,
  SoftphoneMode,
  SoftphoneSignDone,
  SoftphonePayload,
  SoftphoneMessageType,
  SoftphoneEnvironment,
  SoftphoneSign,
  SoftphoneCryptoJS,
  SoftphoneSignOptions,
  SoftphoneState,
  SoftphoneShared,
  SoftphoneConnection,
  SoftphoneMountConfig,
  SoftphoneRuntime,
  SoftphoneProps,
  SoftphoneCallbacks,
  SoftphoneOptions,
  NfSoftphoneComponent
} from '@94ai-plus/nf-softphone'
import '@94ai-plus/nf-softphone/style.css'
```

<div id="sign"></div>

## Debug signatures {#debug-signature}

```ts
import { createSoftphoneSign } from '@94ai-plus/nf-softphone'

const appKey = 'xxx'
const appSecret = 'xxx'
const signedAt = Date.now()
const nextSign = await createSoftphoneSign(appKey, signedAt, appSecret, {
  // env: 'sg',
  // cryptoJsUrl: '',
})
```

| Signature options | CryptoJS script URL |
| --- | --- |
| `env: 'sg'` | `https://seat.teleai.com/CryptoJS.js` |
| Default／`dev`／`test`／`gray`／`prod` | `https://seat.94ai.com/CryptoJS.js` |
| `cryptoJsUrl` | Custom script URL; overrides the default URL selected by `env` |

<div id="install-crypto-js"></div>

```ts
import { installSoftphoneCryptoJS } from '@94ai-plus/nf-softphone'

const appKey = 'xxx'
const timestamp = Date.now()
const appSecret = 'xxx'

const CryptoJS = await installSoftphoneCryptoJS({
  // env: 'sg',
  // cryptoJsUrl: '',
})
// CryptoJS === window.CryptoJS // Expose window.CryptoJS for signature debugging
const sha1 = CryptoJS.HmacSHA1(appKey + timestamp, appSecret)
sign.value = CryptoJS.enc.Base64.stringify(sha1)
```

<div id="online"></div>

<div id="component"></div>

## General integration {#general-integration}

Examples pass `lang="en"` to the phone bar. Other documentation languages use `zh`, `ja`, `es`, `id`, `th`, `tl`, or `pt`. Switching the documentation language destroys and remounts the example with the new language; it is not a seamless language change during a call. Loading and phone content share one area: an opaque loading layer covers rendering content until detection completes, then reveals it at once. The mount container stays measurable, with no fixed delay.

Online examples render an unconnected preview phone bar by default without embedded secrets. Enter test `appKey`, `appSecret`, and `agentTag` values in the editor to generate credentials and load the live phone bar.

### Async setup {#async-setup}

The `loading` slot appears while the microfrontend loads. Its default “Loading...” text follows the component-library locale. It disappears only after visible phone-bar content renders and browser paint frames complete, not merely after mounting; it does not wait for agent sign-in. qiankun containers and Wujie Shadow DOM / accessible same-origin iframes are supported. Loading failures or no visible content within 30 seconds after mounting show the `error` slot. Retrying shows loading again.


### Async setup requires a parent <Suspense>. Generate production signatures on your backend; do not keep secrets in frontend code. Shows an unconnected preview by default; fill in appKey, appSecret, and agentTag to load.
```vue
<script lang='ts' setup>
import {
  onMounted,
  onUnmounted,
  ref
} from 'vue'
import { createSoftphoneSign } from '@94ai-plus/nf-softphone'

const sign = ref('')
const timestamp = ref(Date.now())

// Fill in the three fields below for integration testing; leave empty to show the unconnected preview.
// In production, generate signatures on your backend and do not keep secrets in frontend code.
const appKey = ''
const appSecret = ''
const agentTag = ''
const configured = Boolean(appKey.trim() && appSecret.trim() && agentTag.trim())

if (configured) {
  sign.value = await createSoftphoneSign(appKey, timestamp.value, appSecret, {
    // env: 'sg',
    // cryptoJsUrl: '',
  })
}

const nfSoftPhone0 = ref()
const commonSoftphone = ref()

const softphoneConnectCallBack0 = async (data) => {
  console.log('softphone-connect0', data)
  commonSoftphone.value  = data.commonSoftphone
  // await (await data.commonSoftphone.getUserAgentManager()).toggleNap(false)
  // commonSoftphone.value.getUserAgentManagerSync().callNumber('15018707394')
}
const softphoneCallRefreshCallBack0 = (data) => {
  console.log('softphone-call-refresh0', data)
}
const softphoneSeatStatusChangeCallBack0 = (data) => {
  console.log('softphone-seats-status-change0', data)
}
const softphoneAcceptCallBack0 = (data) => {
  console.log('softphone-accept0', data)
}
const softphoneIgnoreCallBack0 = (data) => {
  console.log('softphone-ignore0', data)
}
const softphoneHangupCallBack0 = (data) => {
  console.log('softphone-hangup0', data)
}
const softphoneAutoIgnoreCallback0 = (data) => {
  console.log('softphone-auto-ignore-callback0', data)
}
const softphoneSessionStateChangeCallBack0 = (data) => {
  console.log('softphone-session-state-change0', data)
}
const softphoneIncomingCallBack0 = (data) => {
  console.log('softphone-incoming0', data)
}
const softphoneSendDtmfCallBack0 = (data) => {
  console.log('softphone-send-dtmf0', data)
}
const softphoneConnectRegisteredCallBack0 = (data) => {
  console.log('softphone-connect-registered0', data)
}

const softphoneSignOverduedCallBack0 = async (done) => {
  console.log('softphone-sign-overdued0')
  const timestamp = Date.now()
  done({
    timestamp,
    sign: await createSoftphoneSign(appKey, timestamp, appSecret)
  })
} // Refresh the signature when it expires

</script>

<template>
  <!-- Documentation preview and loading indicator; in production apps you can keep only the inner phone bar. -->
  <doc-phone-preview :active="configured">
    <nf-softphone
      v-if="configured"
      lang="en"
      ref="nfSoftPhone0"

      :agentTag="agentTag"
      :appKey="appKey"
      v-model:sign="sign"
      v-model:timestamp="timestamp"
      extStatus="1"

      name="nf-softphone0"
      destination-origin="nf-softphone0"
      ancestor-origin="nf-softphone0"

      @softphone-connect="softphoneConnectCallBack0"
      @softphone-call-refresh="softphoneCallRefreshCallBack0"
      @softphone-seats-status-change="softphoneSeatStatusChangeCallBack0"
      @softphone-accept="softphoneAcceptCallBack0"
      @softphone-ignore="softphoneIgnoreCallBack0"
      @softphone-hangup="softphoneHangupCallBack0"
      @softphone-auto-ignore-callback="softphoneAutoIgnoreCallback0"
      @softphone-session-state-change="softphoneSessionStateChangeCallBack0"
      @softphone-incoming="softphoneIncomingCallBack0"
      @softphone-send-dtmf="softphoneSendDtmfCallBack0"
      @softphone-connect-registered="softphoneConnectRegisteredCallBack0"
      @softphone-sign-overdued="softphoneSignOverduedCallBack0"
    >
      <template #error="{ error }">
        <p role="alert">Phone loading failed: {{ error.message }}</p>
      </template>
    </nf-softphone>
  </doc-phone-preview>
</template>
```

### Async onMounted {#async-on-mounted}

Disable automatic startup and obtain the signature asynchronously after mounting. Use `nextTick()` to synchronize the signature and timestamp to child props before calling `initSoftphone()`. Component unmount automatically destroys the phone, and a late signature response will not initialize it again. The component ref’s `initSoftphone()` waits for rendering detection to finish.

### Without async setup, use :auto-start="false". Generate production signatures on your backend; do not keep secrets in frontend code. Shows an unconnected preview by default; fill in appKey, appSecret, and agentTag to load.
```vue
<script lang='ts' setup>
import {
  nextTick,
  onMounted,
  onUnmounted,
  ref
} from 'vue'
import { createSoftphoneSign } from '@94ai-plus/nf-softphone'

const sign = ref('')
const timestamp = ref(Date.now())

// Fill in the three fields below for integration testing; leave empty to show the unconnected preview.
// In production, generate signatures on your backend and do not keep secrets in frontend code.
const appKey = ''
const appSecret = ''
const agentTag = ''
const configured = Boolean(appKey.trim() && appSecret.trim() && agentTag.trim())

const nfSoftPhone1 = ref()
const commonSoftphone = ref()
const loading = ref(configured)
const ready = ref(false)
const initError = ref('')
let disposed = false

onUnmounted(() => { disposed = true })
onMounted(async () => {
  if (!configured) return
  try {
    const signedAt = Date.now()
    const nextSign = await createSoftphoneSign(appKey, signedAt, appSecret, {
      // env: 'sg',
      // cryptoJsUrl: '',
    })
    if (disposed) return // An already-running async onMounted does not stop automatically on unmount
    timestamp.value = signedAt
    sign.value = nextSign
    ready.value = true
    await nextTick() // Synchronize the latest signature and timestamp to child props before manual startup.
    if (disposed) return
    loading.value = false
    await nfSoftPhone1.value?.initSoftphone()
  } catch (error) {
    if (!disposed) {
      loading.value = false
      initError.value = error instanceof Error ? error.message : String(error)
    }
  }
})

const softphoneConnectCallBack1 = async (data) => {
  console.log('softphone-connect1', data)
  commonSoftphone.value  = data.commonSoftphone
  // await (await data.commonSoftphone.getUserAgentManager()).toggleNap(false)
  // commonSoftphone.value.getUserAgentManagerSync().callNumber('15018707394')
}
const softphoneCallRefreshCallBack1 = (data) => {
  console.log('softphone-call-refresh1', data)
}
const softphoneSeatStatusChangeCallBack1 = (data) => {
  console.log('softphone-seats-status-change1', data)
}
const softphoneAcceptCallBack1 = (data) => {
  console.log('softphone-accept1', data)
}
const softphoneIgnoreCallBack1 = (data) => {
  console.log('softphone-ignore1', data)
}
const softphoneHangupCallBack1 = (data) => {
  console.log('softphone-hangup1', data)
}
const softphoneAutoIgnoreCallback1 = (data) => {
  console.log('softphone-auto-ignore-callback1', data)
}
const softphoneSessionStateChangeCallBack1 = (data) => {
  console.log('softphone-session-state-change1', data)
}
const softphoneIncomingCallBack1 = (data) => {
  console.log('softphone-incoming1', data)
}
const softphoneSendDtmfCallBack1 = (data) => {
  console.log('softphone-send-dtmf1', data)
}
const softphoneConnectRegisteredCallBack1 = (data) => {
  console.log('softphone-connect-registered1', data)
}

const softphoneSignOverduedCallBack1 = async (done) => {
  console.log('softphone-sign-overdued1')
  const timestamp = Date.now()
  done({
    timestamp,
    sign: await createSoftphoneSign(appKey, timestamp, appSecret)
  })
} // Refresh the signature when it expires

</script>

<template>
  <!-- Documentation preview and loading indicator; in production apps you can keep only the inner phone bar. -->
  <doc-phone-preview :active="ready" :loading="loading" :failed="Boolean(initError)" :error-text="initError">
    <nf-softphone
      v-if="ready"
      lang="en"
      ref="nfSoftPhone1"
      :auto-start="false"

      :agentTag="agentTag"
      :appKey="appKey"
      v-model:sign="sign"
      v-model:timestamp="timestamp"
      extStatus="1"

      name="nf-softphone1"
      destination-origin="nf-softphone1"
      ancestor-origin="nf-softphone1"

      @softphone-connect="softphoneConnectCallBack1"
      @softphone-call-refresh="softphoneCallRefreshCallBack1"
      @softphone-seats-status-change="softphoneSeatStatusChangeCallBack1"
      @softphone-accept="softphoneAcceptCallBack1"
      @softphone-ignore="softphoneIgnoreCallBack1"
      @softphone-hangup="softphoneHangupCallBack1"
      @softphone-auto-ignore-callback="softphoneAutoIgnoreCallback1"
      @softphone-session-state-change="softphoneSessionStateChangeCallBack1"
      @softphone-incoming="softphoneIncomingCallBack1"
      @softphone-send-dtmf="softphoneSendDtmfCallBack1"
      @softphone-connect-registered="softphoneConnectRegisteredCallBack1"
      @softphone-sign-overdued="softphoneSignOverduedCallBack1"
    />
  </doc-phone-preview>
</template>
```

### Overseas environment {#overseas-environment}

Domestic and overseas accounts are separate. To use the overseas environment, set `env="sg"`, `sg-open="1"`, `sg-domain="1"`, `sg-base="1"`, and `sg-gateway="1"`. Pass `{ env: 'sg' }` when generating the signature as well.

### Overseas environment. Generate production signatures on your backend; do not keep secrets in frontend code. Shows an unconnected preview by default; fill in appKey, appSecret, and agentTag to load.
```vue
<script lang='ts' setup>
import {
  onMounted,
  onUnmounted,
  ref
} from 'vue'
import { createSoftphoneSign } from '@94ai-plus/nf-softphone'

const sign = ref('')
const timestamp = ref(Date.now())

// Fill in the three overseas fields below for integration testing; leave empty to show the unconnected preview.
// In production, generate signatures on your backend and do not keep secrets in frontend code.
const appKey = ''
const appSecret = ''
const agentTag = ''
const configured = Boolean(appKey.trim() && appSecret.trim() && agentTag.trim())

if (configured) {
  sign.value = await createSoftphoneSign(appKey, timestamp.value, appSecret, {
    env: 'sg',
    // cryptoJsUrl: '',
  })
}

const nfSoftPhone2 = ref()
const commonSoftphone = ref()

const softphoneConnectCallBack2 = async (data) => {
  console.log('softphone-connect2', data)
  commonSoftphone.value  = data.commonSoftphone
  // await (await data.commonSoftphone.getUserAgentManager()).toggleNap(false)
  // commonSoftphone.value.getUserAgentManagerSync().callNumber('15018707394')
}
const softphoneCallRefreshCallBack2 = (data) => {
  console.log('softphone-call-refresh2', data)
}
const softphoneSeatStatusChangeCallBack2 = (data) => {
  console.log('softphone-seats-status-change2', data)
}
const softphoneAcceptCallBack2 = (data) => {
  console.log('softphone-accept2', data)
}
const softphoneIgnoreCallBack2 = (data) => {
  console.log('softphone-ignore2', data)
}
const softphoneHangupCallBack2 = (data) => {
  console.log('softphone-hangup2', data)
}
const softphoneAutoIgnoreCallback2 = (data) => {
  console.log('softphone-auto-ignore-callback2', data)
}
const softphoneSessionStateChangeCallBack2 = (data) => {
  console.log('softphone-session-state-change2', data)
}
const softphoneIncomingCallBack2 = (data) => {
  console.log('softphone-incoming2', data)
}
const softphoneSendDtmfCallBack2 = (data) => {
  console.log('softphone-send-dtmf2', data)
}
const softphoneConnectRegisteredCallBack2 = (data) => {
  console.log('softphone-connect-registered2', data)
}

const softphoneSignOverduedCallBack2 = async (done) => {
  console.log('softphone-sign-overdued2')
  const timestamp = Date.now()
  done({
    timestamp,
    sign: await createSoftphoneSign(appKey, timestamp, appSecret, { env: 'sg' })
  })
} // Refresh the signature when it expires

</script>

<template>
  <!-- Documentation preview and loading indicator; in production apps you can keep only the inner phone bar. -->
  <doc-phone-preview :active="configured">
    <nf-softphone
      v-if="configured"
      lang="en"
      ref="nfSoftPhone2"

      :agentTag="agentTag"
      :appKey="appKey"
      v-model:sign="sign"
      v-model:timestamp="timestamp"
      extStatus="1"

      env="sg"
      sg-open="1"
      sg-domain="1"
      sg-base="1"
      sg-gateway="1"

      name="nf-softphone2"
      destination-origin="nf-softphone2"
      ancestor-origin="nf-softphone2"

      @softphone-connect="softphoneConnectCallBack2"
      @softphone-call-refresh="softphoneCallRefreshCallBack2"
      @softphone-seats-status-change="softphoneSeatStatusChangeCallBack2"
      @softphone-accept="softphoneAcceptCallBack2"
      @softphone-ignore="softphoneIgnoreCallBack2"
      @softphone-hangup="softphoneHangupCallBack2"
      @softphone-auto-ignore-callback="softphoneAutoIgnoreCallback2"
      @softphone-session-state-change="softphoneSessionStateChangeCallBack2"
      @softphone-incoming="softphoneIncomingCallBack2"
      @softphone-send-dtmf="softphoneSendDtmfCallBack2"
      @softphone-connect-registered="softphoneConnectRegisteredCallBack2"
      @softphone-sign-overdued="softphoneSignOverduedCallBack2"
    />
  </doc-phone-preview>
</template>
```

### accessToken authorization {#access-token-authorization}

Use `accessToken` instead of `sign` to authorize and load the phone bar. This example obtains an overseas token with `createSoftphoneAccessToken(appKey, appSecret, { env: 'sg' })`. It renders an unconnected preview bar by default; enter test `appKey`, `appSecret`, and `agentTag` values in the editor to fetch a token and load the live phone bar. Initial loading and renewal both call this helper, without loading the softphone SDK.

### accessToken authorization: fetch credentials after mounting, start manually, and renew through createSoftphoneAccessToken. In production, generate accessToken on your backend and keep secrets out of frontend code. Shows an unconnected preview by default; fill in appKey, appSecret, and agentTag to load.
```vue
<script lang='ts' setup>
import {
  nextTick,
  onMounted,
  onUnmounted,
  ref
} from 'vue'
import { createSoftphoneAccessToken } from '@94ai-plus/nf-softphone'
import type { SoftphoneAccessTokenDone } from '@94ai-plus/nf-softphone'

const accessToken = ref('')
const accessTokenTimestamp = ref<string | number>()

// Fill in the three overseas fields below for integration testing; leave empty to show the unconnected preview.
// In production, obtain accessToken on your backend and do not keep secrets in frontend code.
const appKey = ''
const appSecret = ''
const agentTag = ''
const configured = Boolean(appKey.trim() && appSecret.trim() && agentTag.trim())

const nfSoftPhoneToken = ref()
const commonSoftphone = ref()
const loading = ref(configured)
const ready = ref(false)
const initError = ref('')
let disposed = false

onUnmounted(() => { disposed = true })
onMounted(async () => {
  if (!configured) return
  try {
    const credentials = await createSoftphoneAccessToken(appKey, appSecret, { env: 'sg' })
    if (disposed) return
    accessToken.value = credentials.accessToken
    accessTokenTimestamp.value = credentials.accessTokenTimestamp
    ready.value = true
    await nextTick() // Synchronize token props to the child before manual startup.
    if (disposed) return
    loading.value = false
    await nfSoftPhoneToken.value?.initSoftphone()
  } catch (error) {
    if (!disposed) {
      loading.value = false
      initError.value = error instanceof Error ? error.message : String(error)
    }
  }
})

const softphoneConnectCallBack1 = async (data) => {
  console.log('softphone-connect1', data)
  commonSoftphone.value  = data.commonSoftphone
  // await (await data.commonSoftphone.getUserAgentManager()).toggleNap(false)
  // commonSoftphone.value.getUserAgentManagerSync().callNumber('15018707394')
}
const softphoneCallRefreshCallBack1 = (data) => {
  console.log('softphone-call-refresh1', data)
}
const softphoneSeatStatusChangeCallBack1 = (data) => {
  console.log('softphone-seats-status-change1', data)
}
const softphoneAcceptCallBack1 = (data) => {
  console.log('softphone-accept1', data)
}
const softphoneIgnoreCallBack1 = (data) => {
  console.log('softphone-ignore1', data)
}
const softphoneHangupCallBack1 = (data) => {
  console.log('softphone-hangup1', data)
}
const softphoneAutoIgnoreCallback1 = (data) => {
  console.log('softphone-auto-ignore-callback1', data)
}
const softphoneSessionStateChangeCallBack1 = (data) => {
  console.log('softphone-session-state-change1', data)
}
const softphoneIncomingCallBack1 = (data) => {
  console.log('softphone-incoming1', data)
}
const softphoneSendDtmfCallBack1 = (data) => {
  console.log('softphone-send-dtmf1', data)
}
const softphoneConnectRegisteredCallBack1 = (data) => {
  console.log('softphone-connect-registered1', data)
}

const softphoneAccessTokenOverduedCallBack = async (done: SoftphoneAccessTokenDone) => {
  try {
    const credentials = await createSoftphoneAccessToken(appKey, appSecret, { env: 'sg' })
    if (!disposed) done(credentials)
  } catch (error) {
    if (!disposed) initError.value = error instanceof Error ? error.message : String(error)
  }
}

</script>

<template>
  <!-- Documentation preview and loading indicator; in production apps you can keep only the inner phone bar. -->
  <doc-phone-preview :active="ready" :loading="loading" :failed="Boolean(initError)" :error-text="initError">
    <nf-softphone
      v-if="ready"
      lang="en"
      ref="nfSoftPhoneToken"
      :auto-start="false"

      :agentTag="agentTag"
      :appKey="appKey"
      v-model:accessToken="accessToken"
      v-model:accessTokenTimestamp="accessTokenTimestamp"
      extStatus="1"

      env="sg"
      sg-open="1"
      sg-domain="1"
      sg-base="1"
      sg-gateway="1"

      name="nf-softphone-access-token"
      destination-origin="nf-softphone-access-token"
      ancestor-origin="nf-softphone-access-token"

      @softphone-connect="softphoneConnectCallBack1"
      @softphone-call-refresh="softphoneCallRefreshCallBack1"
      @softphone-seats-status-change="softphoneSeatStatusChangeCallBack1"
      @softphone-accept="softphoneAcceptCallBack1"
      @softphone-ignore="softphoneIgnoreCallBack1"
      @softphone-hangup="softphoneHangupCallBack1"
      @softphone-auto-ignore-callback="softphoneAutoIgnoreCallback1"
      @softphone-session-state-change="softphoneSessionStateChangeCallBack1"
      @softphone-incoming="softphoneIncomingCallBack1"
      @softphone-send-dtmf="softphoneSendDtmfCallBack1"
      @softphone-connect-registered="softphoneConnectRegisteredCallBack1"
      @softphone-access-token-overdued="softphoneAccessTokenOverduedCallBack"
    />
  </doc-phone-preview>
</template>
```

<div id="runtime定制"></div>

## Custom runtime {#custom-runtime}

This example uses an offline simulated runtime to demonstrate action dispatch and callback notifications. It neither loads a real microfrontend nor places calls. `runtime` replaces the built-in qiankun / wujie loader. For a real phone bar, remove `:runtime="runtime"` and provide valid agent information and a signature. The runtime customizes loading, communication, and unmounting.

### Intercept dispatched actions and invoke notification callbacks manually
```vue
<script setup lang="ts">
import { ref } from 'vue'
import { NfConfigProvider, NfSoftphone, NfButton } from '@94ai-plus/common-ui'
import type { SoftphoneRuntime, SoftphoneState, SoftphoneMountConfig, SoftphoneConnection } from '@94ai-plus/common-ui'

const phone = ref<InstanceType<typeof NfSoftphone>>()

const ready = ref(false) // Runtime mount completed; the simulated adapter is ready
const events = ref('Connected: false')

const agentId = ''
const appKey = ''
const sign = ref('DEMO_SIGN')
const timestamp = ref(0)

const runtime: SoftphoneRuntime = { // The custom runtime handles loading, communication, and cleanup; this example is offline only
    async mount({
      container,
      receive,
      shared
  }: SoftphoneMountConfig): Promise<SoftphoneConnection> { // Called during initialization; resolving the Promise emits @ready, indicating that mount completed and manager actions are available.
    // const { sign, timestamp, appKey, agentId, agentTag } = shared.getUserInfo()
    const bar = document.createElement('div')
    bar.textContent = '94AI · Offline phone bar'
    bar.className = 'phone-bar'
    container.append(bar)
    return {
      send(state: SoftphoneState) { // Manual action dispatch calls send; simulate the remote result here
        events.value = state.type + ': ' + JSON.stringify(state.data)
        receive({ ...state, origin: 'ai-softphone' }) // Invoke the corresponding softphone notification callback
      },
      unmount() { bar.remove() }, // Clean up resources created by the simulated runtime when the component is destroyed
    }
  },
}
</script>

<template>
  <NfConfigProvider theme="chalk" locale="en-US">
    <NfSoftphone
      lang="en"      ref="phone"
      :runtime="runtime"
      :agentId="agentId"
      :appKey="appKey"
      v-model:sign="sign"
      v-model:timestamp="timestamp"
      @ready="ready = true"
      @softphone-connect="data => events = 'Connected: ' + data.status"
      @softphone-hangup="events = 'Hang up'"
      @error="error => events = error.message"
    />
    <div class="softphone-demo-actions">
      <NfButton :disabled="!ready" @click="phone?.connect()">Connect</NfButton>
      <NfButton :disabled="!ready" @click="phone?.disconnect()">Disconnect</NfButton>
      <NfButton :disabled="!ready" @click="phone?.hangup()">Hang up</NfButton>
    </div>
    <output>{{ events }}</output>
  </NfConfigProvider>
</template>

<style scoped>
.softphone-demo-actions { display:flex; gap:8px; flex-wrap:wrap; margin:12px 0; }
:deep(.phone-bar) { padding:16px; border:1px solid var(--el-color-primary); border-radius:6px; }
output { display:block; overflow-wrap:anywhere; }
</style>
```

<div id="manager"></div>

## Library integration (factory) {#factory-integration}

`loading` starts when signature retrieval begins. `phone.ready` only signals that the microfrontend mounted; then call `waitForSoftphoneRender(host)` and wait for visible phone-bar content before ending loading. It shares detection logic with `NfSoftphone`, defaults to a 30-second timeout, accepts a custom timeout in milliseconds as its second argument, and returns `{ ready, cancel }`. Call `cancel()` on unmount to stop detection if the page disappears before the phone renders. Calling it after completion has no further effect. Do not hide the container with `v-if` / `v-show` during loading, or mounting and visible-content detection cannot work.

### Manager integration. Generate production signatures on your backend; do not keep secrets in frontend code. Shows an unconnected preview by default; fill in appKey, appSecret, and agentTag to load.
```vue
<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { NfConfigProvider, NfButton, nfSoftphoneManager } from '@94ai-plus/common-ui'
import { createSoftphoneSign, waitForSoftphoneRender } from '@94ai-plus/nf-softphone'
import type { SoftphoneSignDone } from '@94ai-plus/nf-softphone'

// Fill in the three fields below for integration testing; leave empty to show the unconnected preview.
// In production, generate signatures on your backend and do not keep secrets in frontend code.
const appKey = ''
const appSecret = ''
const agentTag = ''
const configured = Boolean(appKey.trim() && appSecret.trim() && agentTag.trim())

const host = ref<HTMLElement>()
const ready = ref(false)
const loading = ref(configured)
const error = ref('')
const message = ref('Getting the signature and loading the phone...')
const phone = new nfSoftphoneManager()
let disposed = false
let rendering: ReturnType<typeof waitForSoftphoneRender> | undefined

async function renewSign(done: SoftphoneSignDone) {
  try {
    const timestamp = Date.now()
    const sign = await createSoftphoneSign(appKey, timestamp, appSecret)
    if (!disposed) done({ sign, timestamp })
  } catch (reason) {
    if (!disposed) error.value = reason instanceof Error ? reason.message : String(reason)
  }
}

onMounted(async () => {
  if (!configured) return
  try {
    const timestamp = Date.now()
    const sign = await createSoftphoneSign(appKey, timestamp, appSecret)
    if (disposed) return
    phone.initSoftphone({
      el: host.value,
      env: 'prod',
      mode: 'qiankun',
      lang: 'en',
      name: 'nf-softphone-manager',
      ancestorOrigin: 'nf-softphone-manager',
      destinationOrigin: 'nf-softphone-manager',
      agentTag, appKey, sign, timestamp,
      extStatus: '1',
      softphoneConnectCallBack: data => { message.value = data.status ? 'Signed in' : 'Signed out' },
      softphoneHangupCallBack: () => { message.value = 'Hung up' },
      softphoneSignOverduedCallBack: renewSign,
    })
    await phone.ready
    ready.value = true
    message.value = 'Phone controller ready'
    if (disposed) return
    rendering = waitForSoftphoneRender(host.value!)
    await rendering.ready
    if (disposed) return
    message.value = 'Phone bar displayed'
  } catch (reason) {
    if (!disposed) error.value = reason instanceof Error ? reason.message : String(reason)
  } finally {
    if (!disposed) loading.value = false
  }
})
onBeforeUnmount(() => {
  disposed = true
  rendering?.cancel()
  loading.value = false
  ready.value = false
  void phone.destroy().catch(() => {})
})
</script>
<template>
  <NfConfigProvider theme="chalk" locale="en-US">
    <!-- Documentation preview and loading indicator; in production apps you can keep only the inner phone bar. -->
    <doc-phone-preview :active="configured">
      <div v-if="configured" class="softphone-manager-stage" :aria-busy="loading">
        <div ref="host" class="softphone-manager-host" :aria-hidden="loading || undefined" />
        <p v-if="loading" class="softphone-manager-loading" role="status" aria-live="polite">Loading...</p>
      </div>
      <div v-if="ready" class="softphone-manager-controls">
        <div class="softphone-manager-actions">
          <NfButton @click="phone.connect()">Sign in</NfButton>
          <NfButton @click="phone.disconnect()">Sign out</NfButton>
          <NfButton @click="phone.hangup()">Hang up</NfButton>
        </div>
        <output v-if="!error">{{ message }}</output>
      </div>
      <p v-if="error" role="alert">Phone loading failed: {{ error }}</p>
    </doc-phone-preview>
  </NfConfigProvider>
</template>

<style scoped>
.softphone-manager-stage { display:grid; }
.softphone-manager-host, .softphone-manager-loading { grid-area:1 / 1; position:relative; min-width:0; }
.softphone-manager-host { z-index:0; padding:12px; }
.softphone-manager-loading { z-index:1; display:flex; align-items:center; justify-content:center; min-height:48px; margin:0; background:var(--el-bg-color, #fff); }
.softphone-manager-controls { margin-top:12px; text-align:center; }
.softphone-manager-actions { display:flex; justify-content:center; flex-wrap:wrap; gap:8px; }
.softphone-manager-actions :deep(.nf-button + .nf-button) { margin-left:0; }
output { display:block; margin-top:12px; }
</style>
```

<div id="singleton"></div>

## Library integration (singleton) {#singleton-integration}

For multiple phones, use the constructor with unique `name`, `ancestorOrigin`, and `destinationOrigin` values. The singleton mounts only one phone bar. Ordinary prop updates synchronize shared configuration. Destroy the instance before changing mode, URL, environment, name, or communication namespaces.

### Singleton integration. Generate production signatures on your backend; do not keep secrets in frontend code. Shows an unconnected preview by default; fill in appKey, appSecret, and agentTag to load.
```vue
<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { NfConfigProvider, NfButton, nfSoftphone } from '@94ai-plus/common-ui'
import { createSoftphoneSign, waitForSoftphoneRender } from '@94ai-plus/nf-softphone'
import type { SoftphoneSignDone } from '@94ai-plus/nf-softphone'

// Fill in the three fields below for integration testing; leave empty to show the unconnected preview.
// In production, generate signatures on your backend and do not keep secrets in frontend code.
const appKey = ''
const appSecret = ''
const agentTag = ''
const configured = Boolean(appKey.trim() && appSecret.trim() && agentTag.trim())

const host = ref<HTMLElement>()
const ready = ref(false)
const loading = ref(configured)
const error = ref('')
const message = ref('Getting the signature and loading the phone...')
const phone = nfSoftphone
let ownsPhone = false
let disposed = false
let rendering: ReturnType<typeof waitForSoftphoneRender> | undefined

async function renewSign(done: SoftphoneSignDone) {
  try {
    const timestamp = Date.now()
    const sign = await createSoftphoneSign(appKey, timestamp, appSecret)
    if (!disposed) done({ sign, timestamp })
  } catch (reason) {
    if (!disposed) error.value = reason instanceof Error ? reason.message : String(reason)
  }
}

onMounted(async () => {
  if (!configured) return
  try {
    const timestamp = Date.now()
    const sign = await createSoftphoneSign(appKey, timestamp, appSecret)
    if (disposed) return
    // Another page may own the singleton; do not mount twice or destroy another caller’s instance.
    if (phone.status === 'loading' || phone.status === 'ready') {
      throw new Error('The nfSoftphone singleton is already in use; use nfSoftphoneManager for multiple phones.')
    }
    phone.initSoftphone({
      el: host.value,
      env: 'prod',
      mode: 'qiankun',
      lang: 'en',
      name: 'nf-softphone-singleton',
      ancestorOrigin: 'nf-softphone-singleton',
      destinationOrigin: 'nf-softphone-singleton',
      agentTag, appKey, sign, timestamp,
      extStatus: '1',
      softphoneConnectCallBack: data => { message.value = data.status ? 'Signed in' : 'Signed out' },
      softphoneHangupCallBack: () => { message.value = 'Hung up' },
      softphoneSignOverduedCallBack: renewSign,
    })
    ownsPhone = true
    await phone.ready
    if (disposed) return
    ready.value = true
    message.value = 'Phone controller ready'
    rendering = waitForSoftphoneRender(host.value!)
    await rendering.ready
    if (disposed) return
    message.value = 'Phone bar displayed'
  } catch (reason) {
    if (!disposed) error.value = reason instanceof Error ? reason.message : String(reason)
  } finally {
    if (!disposed) loading.value = false
  }
})
onBeforeUnmount(() => {
  disposed = true
  rendering?.cancel()
  loading.value = false
  ready.value = false
  if (ownsPhone) void phone.destroy().catch(() => {})
})
</script>
<template>
  <NfConfigProvider theme="chalk" locale="en-US">
    <!-- Documentation preview and loading indicator; in production apps you can keep only the inner phone bar. -->
    <doc-phone-preview :active="configured">
      <div v-if="configured" class="softphone-singleton-stage" :aria-busy="loading">
        <div ref="host" class="softphone-singleton-host" :aria-hidden="loading || undefined" />
        <p v-if="loading" class="softphone-singleton-loading" role="status" aria-live="polite">Loading...</p>
      </div>
      <div v-if="ready" class="softphone-singleton-controls">
        <div class="softphone-singleton-actions">
          <NfButton @click="phone.connect()">Sign in</NfButton>
          <NfButton @click="phone.disconnect()">Sign out</NfButton>
          <NfButton @click="phone.hangup()">Hang up</NfButton>
        </div>
        <output v-if="!error">{{ message }}</output>
      </div>
      <p v-if="error" role="alert">Phone loading failed: {{ error }}</p>
    </doc-phone-preview>
  </NfConfigProvider>
</template>

<style scoped>
.softphone-singleton-stage { display:grid; }
.softphone-singleton-host, .softphone-singleton-loading { grid-area:1 / 1; position:relative; min-width:0; }
.softphone-singleton-host { z-index:0; padding:12px; }
.softphone-singleton-loading { z-index:1; display:flex; align-items:center; justify-content:center; min-height:48px; margin:0; background:var(--el-bg-color, #fff); }
.softphone-singleton-controls { margin-top:12px; text-align:center; }
.softphone-singleton-actions { display:flex; justify-content:center; flex-wrap:wrap; gap:8px; }
.softphone-singleton-actions :deep(.nf-button + .nf-button) { margin-left:0; }
output { display:block; margin-top:12px; }
</style>
```

## Credential helpers {#credential-helpers}

Use these helpers for local integration debugging. Production secrets and credential generation belong on your backend.

| API | Result |
| --- | --- |
| `createSoftphoneAccessToken(appKey, appSecret, options?)` | Returns an OpenAPI access token and the millisecond timestamp used for its request. |
| `createSoftphoneToken(appKey, appSecret, options)` | Returns an agent-system token string, distinct from OpenAPI accessToken. |

Both helpers accept `env`, `cryptoJsUrl`, and `signal` for cancellation; requests time out after 15 seconds. `createSoftphoneAccessToken` also accepts `openGatewayUrl` and `accessTokenTimestamp`. `createSoftphoneToken` accepts `agentId` / `agentTag`, `openGatewayUrl`, and `openBaseUrl`; agentId takes priority, while agentTag triggers an agent-ID lookup. Use `env: 'sg'` overseas; other environments default to domestic gateways.

| env | openGatewayUrl | openBaseUrl |
| --- | --- | --- |
| default / dev / test / gray / prod | `https://seat.94ai.com/openapigateway` | `https://seat.94ai.com/openapi` |
| sg | `https://seat.teleai.com/teleaiopenapigateway` | `https://seat.teleai.com/teleaiopenapi` |

```ts
import { createSoftphoneAccessToken, createSoftphoneToken } from '@94ai-plus/nf-softphone'

const credentials = await createSoftphoneAccessToken(appKey, appSecret, { env: 'sg' })
const token = await createSoftphoneToken(appKey, appSecret, { env: 'sg', agentId })
const tokenByTag = await createSoftphoneToken(appKey, appSecret, { env: 'sg', agentTag })
```

## Props {#props}

| Prop / option | Type | Default / meaning |
| --- | --- | --- |
| mode | `'qiankun' \| 'wujie'` | `qiankun` |
| env / envMap | `SoftphoneEnv` / `Partial<Record<SoftphoneEnv, SoftphoneEnvironment>>` | Defaults to `prod`; supports `dev` / `test` / `sg` / `gray` / `prod` |
| url | string | Optional HTTP(S) microfrontend entry override; query parameters are preserved |
| name | string | The component generates a unique name; the manager defaults to `nf-microphone` |
| origin | string | The <b>previous-source identifier</b> of an action notification, used to isolate communication namespaces when multiple qiankun / wujie instances share one bus. <b>For manually triggered instance actions, filter self-notifications and accept only notifications from the phone on the shared bus.</b> Defaults to `ai-softphone`. The legacy iframe approach isolates DOM / communication through different iframe `contentWindow` objects and may omit this option; this package only provides qiankun / wujie integration, not the legacy iframe mode. |
| ancestorOrigin | string | The <b>original-source identifier</b> of an action notification, used for multi-instance namespace isolation. <b>Only respond to phone notifications caused by this instance’s manual actions; filter notifications caused by other instances on the shared bus.</b> The manager defaults to `nf-softphone`; the Vue component derives a unique namespace from `name` when not explicitly configured. |
| destinationOrigin | string | The <b>designated responding-source identifier</b> for multi-instance namespace isolation. <b>When notifications across instances share the same `origin` and `ancestorOrigin` (for example, remote applications using `ai-softphone`), only the designated instance responds.</b> The manager defaults to `*`, a wildcard destination identifier; the Vue component derives a namespace from `name` unless explicitly configured. |
| agentId / agentTag / appKey / appSecret | string | Business credentials; prefer backend-issued signatures and do not retain `appSecret` in frontend code |
| sign / timestamp | `string`／`string` or `number` | Use Vue `v-model:sign` / `v-model:timestamp` for two-way binding |
| accessToken / accessTokenTimestamp | `string` / `string` / `number` | Server-issued access token and optional timestamp, forwarded through `shared.getUserInfo()`. Supports `v-model:accessToken` / `v-model:accessTokenTimestamp`. The `softphone-access-token-overdued` event receives `done({ accessToken, accessTokenTimestamp })`; managers use `softphoneAccessTokenOverduedCallBack`. `shared.setUserInfo()` and renewal emit the corresponding `update:*` events. |
| extStatus | string | Defaults to `1` for online; other values indicate a break. Control this externally to keep state transitions consistent |
| callShow / transferToLaborShow / restShow / networkDetectShow / muteShow / logShow / timingShow / signShow | `'0' \| '1'` | Defaults to `1`; `0` hides the corresponding outgoing-call, transfer-to-agent, break, network-diagnostics, mute, call-history, accumulated-status-time, or sign-in/sign-out control |
| lang | string | Defaults to `zh`; supports `id`, `es`, `ja`, `en`, `zh`, `pt`, `th`, `tl` |
| extensionInfo | object | Extension information including `status`, `wsRegisterAddress`, `wsProtocol`, and `accountCode` |
| extPassword / extensionNumber / wsRegisterAddress / wsProtocol | string | Extension configuration |
| isOem | boolean | Enable the OEM theme; defaults to `true` |
| numberKeyBoard | boolean | Enable the number keypad; defaults to `true` |
| accessMode | `'mobile'` or `'pc'` | Mobile / PC mode; defaults to `pc` |
| sipHeaders | string[] | Additional custom SIP communication headers; unset by default |
| open | string | openapi / normal mode: `0` selects normal and `1` selects open. Legacy docs listed `0`; the current manager defaults to `1` and passes it to the remote app through shared configuration. |
| sgGateway | string | Gateway API URL / request prefix: `0` selects domestic production, `1` overseas production; a domain / HTTP(S) URL supplies a custom gateway API. Unset by default. <b>Legacy behavior followed `env` when omitted; the current implementation uses domestic services when omitted and does not follow `env`. Overseas integrations must explicitly pass `1` or a custom URL.</b> |
| sgBase | string | Base API URL / request prefix: `0` selects domestic production, `1` overseas production; a domain / HTTP(S) URL supplies a custom base API. Unset by default. <b>Legacy behavior followed `env` when omitted; the current implementation uses domestic services when omitted and does not follow `env`. Overseas integrations must explicitly pass `1` or a custom URL.</b> |
| sgOpen | string | Overseas softphone proxy selection: `0` domestic production, `1` overseas production; omission uses domestic production. A domain / HTTP(S) URL supplies a custom hosting proxy. Unset by default. |
| sgDomain | string | Select the overseas proxy path for domestic or overseas phones: `0` domestic production, `1` overseas production; omission uses domestic production. Unset by default; currently selects `openapi` / `sgopenapi` respectively. |
| countryId | number | `0` indicates domestic operation by default; nonzero values use English hangup audio |
| getOfflineInfo | function | Custom offline detection. Agent sign-in synchronization may lag by 0–3 seconds; use this to determine precisely whether sign-in completed. Optional callback exposed to the remote app through `shared`; unset by default. |
| changeALittleRest | function | Custom break action. Optional callback exposed to the remote app through `shared`; unset by default. |
| quickCallWin | function | Custom quick-call action. Optional callback exposed to the remote app through `shared`; unset by default. |
| autoStart | boolean | Component only; defaults to `true`, loading the microfrontend on mount. With `:auto-start="false"`, loading starts only after manually calling `initSoftphone()`. |
| runtime | SoftphoneRuntime | Optional host runtime injection, replacing built-in microfrontend loading and communication; useful for offline demos |
| el | `string` or `HTMLElement` | Manager only; a valid mount container is required |

> **tip Tip**
`origin=ai-softphone && ancestorOrigin=ai-softphone && destinationOrigin=*` means that a notification caused by interaction within a phone-bar instance is dispatched for every instance to respond.

`origin=ai-softphone && ancestorOrigin=nf-softphone && destinationOrigin=xxx` means that a notification resulting from a manually triggered action by the instance identified as `nf-softphone` is dispatched to the instance identified as `xxx`.

## Events {#events}

| Component event | Library callback |
| --- | --- |
| `softphone-connect` | `softphoneConnectCallBack` |
| `softphone-call-refresh` | `softphoneCallRefreshCallBack` |
| `softphone-seats-status-change` | `softphoneSeatStatusChangeCallBack` |
| `softphone-accept` | `softphoneAcceptCallBack` |
| `softphone-ignore` | `softphoneIgnoreCallBack` |
| `softphone-hangup` | `softphoneHangupCallBack` |
| `softphone-session-state-change` | `softphoneSessionStateChangeCallBack` |
| `softphone-incoming` | `softphoneIncomingCallBack` |
| `softphone-send-dtmf` | `softphoneSendDtmfCallBack` |
| `softphone-connect-registered` | `softphoneConnectRegisteredCallBack` |
| `softphone-auto-ignore-callback` | `softphoneAutoIgnoreCallback` |
| `softphone-sign-overdued` | `softphoneSignOverduedCallBack` |
| `softphone-access-token-overdued` | `softphoneAccessTokenOverduedCallBack` |

> **tip Tip**
Regular notifications preserve the remote payload reference. `data.commonSoftphone` exposes the remote instance when provided by the online phone API. `softphone-sign-overdued` receives a `done({ sign, timestamp })` callback; stale callbacks after destruction do not send messages. `shared.setUserInfo()` and signature renewal synchronize `update:sign` / `update:timestamp`, even when the initial sign is empty. The component also emits `ready(manager)` and `error(error)`; the class exposes the `ready` Promise / `onError` for initialization results.

## Methods {#methods}

| Method | Description |
| --- | --- |
| initSoftphone(options?) | The manager returns itself; await `ready` before actions. The component method returns an initialization Promise |
| connect() / disconnect() | Sign in / sign out |
| seatsStatusChange(boolean) | Switch online / break state |
| accept() / ignore() / hangup() | Preserve existing remote command aliases: dispatch `connect` / `hangup` / `hangup` respectively |
| sendDtmf(data?) | Send transfer / DTMF command data |
| changeServerToRegister() | Switch the registration server |
| updateOptions(options) | Update the manager’s shared configuration |
| microCommunicat(type, data?, operationType?, ancestorOrigin?, destinationOrigin?) | Advanced manager API to dispatch commands to a designated communication namespace |
| destroy() / destory() | Asynchronous resource cleanup; the legacy spelling `destory()` remains a compatibility alias |

> **tip Tip**
The component ref exposes the manager and common actions. Do not reuse the same active name until `destroy()` completes. Correct the configuration and retry after initialization failures. The default slot adds content; the `error` slot receives `{ error }`; use the `loading` slot for custom loading UI. `phone.ready` only means the microfrontend mounted; actual rendering detection completes through `rendering.ready`.
```vue
<NfSoftphone v-bind="options">
  <template #loading>Loading phone, please wait...</template>
</NfSoftphone>
```
