test: add receive display msglib smoke

This commit is contained in:
zhaoyilun
2026-07-10 08:24:08 +08:00
parent 298482c25d
commit 07d127c44a
5 changed files with 225 additions and 17 deletions

View File

@@ -28,7 +28,7 @@ try {
Push-Location $repo
try {
if (-not $SkipBuild) {
& powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $repo "scripts\build-msglib-sidecar.ps1") | Out-Host
$buildOutput = & powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $repo "scripts\build-msglib-sidecar.ps1") 2>&1
if ($LASTEXITCODE -ne 0) { throw "build-msglib-sidecar.ps1 failed with exit code $LASTEXITCODE" }
}
Assert-True (Test-Path -LiteralPath $sidecarPath) "sidecar not found: $sidecarPath"
@@ -39,10 +39,14 @@ package main
import (
"context"
"crypto/cipher"
"crypto/des"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -53,10 +57,18 @@ import (
type summary struct {
Count int `json:"count"`
Sources []string `json:"sources"`
FirstID string
FirstDisplayName string
}
type receiveDisplaySummary struct {
MessageCount int
SenderNamePopulated bool
ConversationDisplayPopulated bool
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
serverTransport, clientTransport := mcp.NewInMemoryTransports()
@@ -82,6 +94,13 @@ func main() {
groups := callSearch(ctx, session, "isphere_search_groups", "groups")
if contacts.Count == 0 { fail("contacts", fmt.Errorf("no msglib_readonly contacts returned")) }
if groups.Count == 0 { fail("groups", fmt.Errorf("no msglib_readonly groups returned")) }
if contacts.FirstID == "" || contacts.FirstDisplayName == "" { fail("contacts", fmt.Errorf("contact display fixture unavailable")) }
if groups.FirstID == "" || groups.FirstDisplayName == "" { fail("groups", fmt.Errorf("group display fixture unavailable")) }
receiveDisplay := verifyReceiveDisplay(ctx, contacts, groups)
if receiveDisplay.MessageCount == 0 { fail("receive_display", fmt.Errorf("receive message fixture returned no messages")) }
if !receiveDisplay.SenderNamePopulated { fail("receive_display", fmt.Errorf("sender display was not populated")) }
if !receiveDisplay.ConversationDisplayPopulated { fail("receive_display", fmt.Errorf("conversation display was not populated")) }
out := map[string]any{
"ok": true,
@@ -90,8 +109,13 @@ func main() {
"contact_sources": contacts.Sources,
"group_count": groups.Count,
"group_sources": groups.Sources,
"receive_display_smoke": true,
"receive_message_count": receiveDisplay.MessageCount,
"receive_sender_name_populated": receiveDisplay.SenderNamePopulated,
"receive_conversation_display_populated": receiveDisplay.ConversationDisplayPopulated,
"printed_entity_values": false,
"message_bodies_returned": false,
"file_paths_returned": false,
"raw_rows_returned": false,
}
encoded, _ := json.Marshal(out)
@@ -111,9 +135,12 @@ func callSearch(ctx context.Context, session *mcp.ClientSession, tool string, fi
var decoded map[string]any
if err := json.Unmarshal(payload, &decoded); err != nil { fail(tool+"_decode", err) }
values, ok := decoded[field].([]any)
if !ok { fail(tool+"_shape", fmt.Errorf("%s missing or not array", field)) }
if !ok { fail(tool+"_shape", fmt.Errorf("result field missing or not array")) }
idKey := "contact_id"
if field == "groups" { idKey = "group_id" }
sourceSet := map[string]bool{}
count := 0
out := summary{}
for _, value := range values {
item, ok := value.(map[string]any)
if !ok { continue }
@@ -121,12 +148,140 @@ func callSearch(ctx context.Context, session *mcp.ClientSession, tool string, fi
if source != "msglib_readonly" { continue }
rawRef, _ := item["raw_ref"].(string)
if rawRef != "" { sourceSet[rawRef] = true }
id, _ := item[idKey].(string)
displayName, _ := item["display_name"].(string)
if out.FirstID == "" && strings.TrimSpace(id) != "" && strings.TrimSpace(displayName) != "" {
out.FirstID = strings.TrimSpace(id)
out.FirstDisplayName = strings.TrimSpace(displayName)
}
count++
}
sources := make([]string, 0, len(sourceSet))
for source := range sourceSet { sources = append(sources, source) }
sort.Strings(sources)
return summary{Count: count, Sources: sources}
out.Count = count
out.Sources = sources
return out
}
func verifyReceiveDisplay(ctx context.Context, contact summary, group summary) receiveDisplaySummary {
groupPlaintext := packetFixturePlaintext("c33-group-display-fixture", group.FirstID+"/imp_pc_4.1.2.6842", contact.FirstID, "groupchat", "redacted-group-body")
directPlaintext := packetFixturePlaintext("c33-contact-display-fixture", contact.FirstID+"/imp_pc_4.1.2.6842", "receiver-redacted@imopenfire1-lanzhou", "chat", "redacted-contact-body")
groupLine, err := encryptPacketLogLineForHarness(groupPlaintext)
if err != nil { fail("receive_display_encrypt", err) }
directLine, err := encryptPacketLogLineForHarness(directPlaintext)
if err != nil { fail("receive_display_encrypt", err) }
file, err := os.CreateTemp("", "isphere-msglib-receive-display-*.txt")
if err != nil { fail("receive_display_fixture", err) }
fixturePath := file.Name()
defer os.Remove(fixturePath)
if _, err := file.WriteString("\n" + groupLine + "\n" + directLine + "\n"); err != nil {
_ = file.Close()
fail("receive_display_fixture", err)
}
if err := file.Close(); err != nil { fail("receive_display_fixture", err) }
oldFileValue, hadOldFileValue := os.LookupEnv("ISPHERE_PACKET_LOG_FILE")
oldDirValue, hadOldDirValue := os.LookupEnv("ISPHERE_PACKET_LOG_DIR")
_ = os.Unsetenv("ISPHERE_PACKET_LOG_DIR")
if err := os.Setenv("ISPHERE_PACKET_LOG_FILE", fixturePath); err != nil { fail("receive_display_env", err) }
defer func() {
if hadOldFileValue { _ = os.Setenv("ISPHERE_PACKET_LOG_FILE", oldFileValue) } else { _ = os.Unsetenv("ISPHERE_PACKET_LOG_FILE") }
if hadOldDirValue { _ = os.Setenv("ISPHERE_PACKET_LOG_DIR", oldDirValue) } else { _ = os.Unsetenv("ISPHERE_PACKET_LOG_DIR") }
}()
serverCtx, cancel := context.WithCancel(ctx)
defer cancel()
serverTransport, clientTransport := mcp.NewInMemoryTransports()
server, err := mcpserver.NewServerFromEnv()
if err != nil { fail("receive_display_server", err) }
serverErr := make(chan error, 1)
go func() { serverErr <- server.Run(serverCtx, serverTransport) }()
client := mcp.NewClient(&mcp.Implementation{Name: "verify-msglib-mcp-receive-display", Version: "0.1.0"}, nil)
session, err := client.Connect(serverCtx, clientTransport, nil)
if err != nil {
cancel()
fail("receive_display_connect", err)
}
defer func() {
_ = session.Close()
cancel()
select {
case <-serverErr:
case <-time.After(2*time.Second):
fail("receive_display_shutdown", fmt.Errorf("server did not stop"))
}
}()
result, err := session.CallTool(serverCtx, &mcp.CallToolParams{Name: "isphere_receive_messages", Arguments: map[string]any{
"source_preference": "auto",
"preview": true,
"cursor": "",
"include_attachment_metadata": false,
"limit": 5,
}})
if err != nil { fail("receive_display_call", err) }
if result.IsError { fail("receive_display_call", fmt.Errorf("tool returned isError=true")) }
payload, _ := json.Marshal(result.StructuredContent)
var decoded map[string]any
if err := json.Unmarshal(payload, &decoded); err != nil { fail("receive_display_decode", err) }
messages, ok := decoded["messages"].([]any)
if !ok { fail("receive_display_shape", fmt.Errorf("messages missing or not array")) }
out := receiveDisplaySummary{MessageCount: len(messages)}
if conversation, ok := decoded["conversation"].(map[string]any); ok {
displayName, _ := conversation["display_name"].(string)
out.ConversationDisplayPopulated = displayName == group.FirstDisplayName
}
for _, value := range messages {
message, ok := value.(map[string]any)
if !ok { continue }
senderID, _ := message["sender_id"].(string)
senderName, _ := message["sender_name"].(string)
if senderID == contact.FirstID && senderName == contact.FirstDisplayName {
out.SenderNamePopulated = true
}
}
return out
}
func packetFixturePlaintext(id string, from string, to string, messageType string, body string) string {
return "--------------------------------------------------------------------------------------------------------------------------------------------\n" +
"2026/7/10 09:30:00\n" +
fmt.Sprintf("<message id=\"%s\" from=\"%s\" to=\"%s\" type=\"%s\">\n", xmlAttr(id), xmlAttr(from), xmlAttr(to), xmlAttr(messageType)) +
fmt.Sprintf(" <body>%s</body>\n", xmlText(body)) +
" <received xmlns=\"urn:xmpp:receipts\" id=\"receipt-c33-display-fixture\" type=\"1\" stamp=\"\" />\n" +
" <subject>DISPLAY_SMOKE</subject>\n" +
" <isphere xmlns=\"isphere.im\" type=\"1001\" sendtime=\"1783423807000\" version=\"1\" />\n" +
" <readed />\n" +
"</message>"
}
func xmlAttr(value string) string {
return strings.NewReplacer("&", "&amp;", "\"", "&quot;", "<", "&lt;", ">", "&gt;").Replace(value)
}
func xmlText(value string) string {
return strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;").Replace(value)
}
func encryptPacketLogLineForHarness(plaintext string) (string, error) {
block, err := des.NewCipher([]byte("hyhccdtm"))
if err != nil { return "", err }
plain := padPKCS7ForHarness([]byte(plaintext), des.BlockSize)
ciphertext := make([]byte, len(plain))
iv := []byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF}
cipher.NewCBCEncrypter(block, iv).CryptBlocks(ciphertext, plain)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func padPKCS7ForHarness(data []byte, blockSize int) []byte {
pad := blockSize - len(data)%blockSize
out := append([]byte(nil), data...)
for i := 0; i < pad; i++ { out = append(out, byte(pad)) }
return out
}
func fail(step string, err error) {
@@ -163,6 +318,9 @@ func fail(step string, err error) {
Assert-True ($json.printed_entity_values -eq $false) "harness must not print entity values"
Assert-True ($json.contact_count -gt 0) "contact_count should be > 0"
Assert-True ($json.group_count -gt 0) "group_count should be > 0"
Assert-True (($json.PSObject.Properties.Name -contains "receive_display_smoke") -and $json.receive_display_smoke -eq $true) "receive display smoke should be true"
Assert-True (($json.PSObject.Properties.Name -contains "receive_sender_name_populated") -and $json.receive_sender_name_populated -eq $true) "receive sender_name should be populated"
Assert-True (($json.PSObject.Properties.Name -contains "receive_conversation_display_populated") -and $json.receive_conversation_display_populated -eq $true) "receive conversation.display_name should be populated"
}
finally { Pop-Location }
}