mirror of
https://github.com/NanmiCoder/claude-code-haha.git
synced 2026-10-10 11:53:10 +08:00
814c02a786
Connecting Feishu meant creating a bot by hand on the open platform and pasting an App ID and App Secret back. Feishu also exposes an RFC 8628 device-authorization flow, so the desktop can now render a QR code, and confirming it in the app creates the bot and stores its credentials directly. `adapters/feishu/registration.ts` implements that protocol rather than importing `registerApp` from `@larksuiteoapi/node-sdk@1.73`: the repository pins 1.60 for the chat client, and the SDK runs the whole poll inside one un-cancellable promise where the desktop needs the stateless begin/poll pair the DingTalk registration already uses. The scan is create-only, so it can never rewrite the configuration of a bot the user already runs, and it pre-fills exactly the scopes, events and callbacks this adapter calls. International tenants finish on Lark's domain, which is now persisted and honoured by the client. WeCom, QQ and Slack join the same session model. WeCom and QQ bind by scanning; Slack has no scan flow, so it uses an app manifest that pre-fills the scopes and Socket Mode. All three run over long connections, so no public callback URL is needed, and all three accept private chats only — pairing authorizes one person, and answering in a group would extend that authorization to everyone else in the room. They are built on a new `adapters/common/chat-runtime.ts` instead of a fourth copy of the loop the five existing adapters each carry. A platform supplies a `ChatPort` — how to say something, how to open a streaming reply, optionally how to send an image — and the runtime owns pairing, command routing, session restore, permission bookkeeping and the translation of the server's stream. The existing five are deliberately left on their own copies; migrating them is a separate change with its own regression surface. Attachments are downloaded through a deferred loader that runs after the pairing gate and inside the per-chat queue. Resolving them eagerly would let an unpaired stranger make the adapter fetch bytes and write them under ~/.claude/im-downloads — on Slack with the bot token attached — and would let a slow attachment overtake a text message sent after it. The sidecar launcher's per-adapter branches become one table. It is declared above the mode dispatch on purpose: `runAdapters` is hoisted and runs at module top level, so a table declared below it is still in its temporal dead zone when the adapters mode reads it — which type checks, lints and unit tests all miss, and only the compiled binary reveals. Verified with the checks `check:impact` selects: adapters, server, desktop, electron, policy, chat-contract, agent-flow, docs, native (sidecar compile, packaging and an adapters-mode smoke against the real binary) and coverage. The scan flows themselves are not verified against live platforms — that needs real WeCom, QQ and Slack accounts and would create real bots. Claude-Session: https://claude.ai/code/session_01CCGoP316AK7wdQG3Ms6Uwq
164 lines
4.6 KiB
TypeScript
164 lines
4.6 KiB
TypeScript
import { afterEach, describe, expect, it } from 'bun:test'
|
|
import { EventEmitter } from 'node:events'
|
|
import type WebSocket from 'ws'
|
|
import { SlackSocketMode, type SocketEnvelope } from '../socket-mode.js'
|
|
|
|
class FakeSocket extends EventEmitter {
|
|
readyState = 1 // WebSocket.OPEN
|
|
sent: string[] = []
|
|
closedWith: Array<[number, string]> = []
|
|
|
|
send(payload: string): void {
|
|
this.sent.push(payload)
|
|
}
|
|
|
|
close(code: number, reason: string): void {
|
|
this.closedWith.push([code, reason])
|
|
this.readyState = 3
|
|
this.emit('close')
|
|
}
|
|
|
|
deliver(envelope: SocketEnvelope): void {
|
|
this.emit('message', Buffer.from(JSON.stringify(envelope)))
|
|
}
|
|
}
|
|
|
|
const sockets: FakeSocket[] = []
|
|
let started: SlackSocketMode | null = null
|
|
|
|
function createSocketMode(options: {
|
|
onEnvelope?: (envelope: SocketEnvelope) => void
|
|
openConnection?: () => Promise<string>
|
|
} = {}) {
|
|
const received: SocketEnvelope[] = []
|
|
const opened: string[] = []
|
|
const mode = new SlackSocketMode({
|
|
openConnection: options.openConnection
|
|
?? (async () => {
|
|
opened.push('wss://wss.slack.com/link')
|
|
return 'wss://wss.slack.com/link'
|
|
}),
|
|
onEnvelope: options.onEnvelope ?? ((envelope) => received.push(envelope)),
|
|
createWebSocket: () => {
|
|
const socket = new FakeSocket()
|
|
sockets.push(socket)
|
|
return socket as unknown as WebSocket
|
|
},
|
|
logPrefix: '[Test]',
|
|
})
|
|
started = mode
|
|
return { mode, received, opened }
|
|
}
|
|
|
|
afterEach(() => {
|
|
started?.stop()
|
|
started = null
|
|
sockets.length = 0
|
|
})
|
|
|
|
describe('SlackSocketMode', () => {
|
|
it('acknowledges an envelope before handing it to the handler', async () => {
|
|
const order: string[] = []
|
|
const { mode } = createSocketMode({
|
|
onEnvelope: () => order.push('handled'),
|
|
})
|
|
await mode.start()
|
|
const socket = sockets[0]!
|
|
socket.send = (payload: string) => {
|
|
order.push('acked')
|
|
socket.sent.push(payload)
|
|
}
|
|
|
|
socket.deliver({ type: 'events_api', envelope_id: 'env-1', payload: {} })
|
|
|
|
// Slack redelivers anything unacked within three seconds, and handling can
|
|
// take far longer than that — so the ack must not wait on the handler.
|
|
expect(order).toEqual(['acked', 'handled'])
|
|
expect(JSON.parse(socket.sent[0]!)).toEqual({ envelope_id: 'env-1' })
|
|
})
|
|
|
|
it('passes an events_api envelope to the handler', async () => {
|
|
const { mode, received } = createSocketMode()
|
|
await mode.start()
|
|
|
|
sockets[0]!.deliver({
|
|
type: 'events_api',
|
|
envelope_id: 'env-1',
|
|
payload: { event: { type: 'message', text: 'hi' } },
|
|
})
|
|
|
|
expect(received).toHaveLength(1)
|
|
expect(received[0]!.payload?.event).toMatchObject({ text: 'hi' })
|
|
})
|
|
|
|
it('swallows the hello frame instead of routing it as an event', async () => {
|
|
const { mode, received } = createSocketMode()
|
|
await mode.start()
|
|
|
|
sockets[0]!.deliver({ type: 'hello' })
|
|
|
|
expect(received).toHaveLength(0)
|
|
})
|
|
|
|
it('reconnects with a freshly opened URL when Slack asks it to', async () => {
|
|
let opens = 0
|
|
const { mode } = createSocketMode({
|
|
openConnection: async () => {
|
|
opens += 1
|
|
return 'wss://wss.slack.com/link'
|
|
},
|
|
})
|
|
await mode.start()
|
|
expect(opens).toBe(1)
|
|
|
|
sockets[0]!.deliver({ type: 'disconnect', envelope_id: 'env-2', reason: 'refresh_requested' })
|
|
await new Promise((resolve) => setTimeout(resolve, 1_200))
|
|
|
|
expect(sockets[0]!.closedWith[0]![1]).toBe('slack requested reconnect')
|
|
expect(opens).toBe(2)
|
|
})
|
|
|
|
it('does not reconnect after stop()', async () => {
|
|
let opens = 0
|
|
const { mode } = createSocketMode({
|
|
openConnection: async () => {
|
|
opens += 1
|
|
return 'wss://wss.slack.com/link'
|
|
},
|
|
})
|
|
await mode.start()
|
|
mode.stop()
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 1_200))
|
|
|
|
expect(opens).toBe(1)
|
|
})
|
|
|
|
it('survives a malformed frame without dropping the connection', async () => {
|
|
const { mode, received } = createSocketMode()
|
|
await mode.start()
|
|
|
|
sockets[0]!.emit('message', Buffer.from('not json'))
|
|
sockets[0]!.deliver({ type: 'events_api', envelope_id: 'env-3', payload: {} })
|
|
|
|
expect(received).toHaveLength(1)
|
|
})
|
|
|
|
it('schedules a reconnect when opening the connection fails', async () => {
|
|
let attempts = 0
|
|
const { mode } = createSocketMode({
|
|
openConnection: async () => {
|
|
attempts += 1
|
|
if (attempts === 1) throw new Error('rate limited')
|
|
return 'wss://wss.slack.com/link'
|
|
},
|
|
})
|
|
await mode.start()
|
|
|
|
expect(sockets).toHaveLength(0)
|
|
await new Promise((resolve) => setTimeout(resolve, 1_200))
|
|
expect(attempts).toBe(2)
|
|
expect(sockets).toHaveLength(1)
|
|
})
|
|
})
|